branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>limbachia/clothes-recommender-app<file_sep>/requirements.txt
argon2-cffi==20.1.0
async-generator==1.10
attrs==20.3.0
backcall==0.2.0
bleach==3.2.3
cffi==1.14.4
click==7.1.2
cycler==0.10.0
decorator==4.4.2
defusedxml==0.6.0
entrypoints==0.3
Flask==1.1.2
gunicorn==19.9.0
importlib-metadata==2.1.1
iniconfig==1.1.1
itsdangerous==1.1.0
jedi==0.18.0
Jinja2==2.11.2
joblib==0.14.1
jsonschema==3.2.0
kiwisolver==1.3.1
MarkupSafe==1.1.1
matplotlib==3.3.4
mistune==0.8.4
nest-asyncio==1.5.1
numpy==1.18.5
packaging==20.9
pandas==0.25.3
pandocfilters==1.4.3
parso==0.8.1
patsy==0.5.1
pexpect==4.8.0
pickleshare==0.7.5
Pillow==8.1.0
pluggy==0.13.1
prometheus-client==0.9.0
prompt-toolkit==3.0.14
ptyprocess==0.7.0
py==1.10.0
pycparser==2.20
Pygments==2.7.4
pypandoc==1.5
pyparsing==2.4.7
pyrsistent==0.17.3
pytest==6.2.2
pytest-runner==5.2
python-dateutil==2.8.1
pytz==2020.5
pyzmq==22.0.2
qtconsole==5.0.2
QtPy==1.9.0
-e git+https://github.com/limbachia/clothes-recommender-app.git@<PASSWORD>6f4d6c573fce90686ee82822a663#egg=recommender_model&subdirectory=packages
scikit-learn==0.22.2.post1
scipy==1.5.4
seaborn==0.11.1
Send2Trash==1.5.0
six==1.15.0
statsmodels==0.12.1
terminado==0.9.2
testpath==0.4.4
toml==0.10.2
tornado==6.1
traitlets==4.3.3
typing-extensions==3.7.4.3
watermark==2.0.2
wcwidth==0.2.5
webencodings==0.5.1
Werkzeug==1.0.1
widgetsnbextension==3.5.1
zipp==3.4.0
<file_sep>/packages/recommender_model/processing/preprocessors.py
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class TransformHeight(BaseEstimator, TransformerMixin):
'''
convert height info provided as string (feet' inch") to float (inches)
'''
def __init__(self, height=None):
self.height=height
def fit(self, X, y=None):
return self
def transform(self, X):
def convert_height_to_inch(string):
feet, inch = string.split()
feet = np.float32(feet.strip("'"))
inch = np.float32(inch.strip('"'))
height_in_inch = feet*12 + inch
return height_in_inch
X = X.copy()
X[self.height+'_inch'] = X[self.height].apply(
lambda x: convert_height_to_inch(x) if type(x)==str else np.nan)
return X
class DropFeatures(BaseEstimator,TransformerMixin):
'''
Drop unecessary features
'''
def __init__(self, variables_to_drop=None):
if not isinstance(variables_to_drop,list):
self.variables = [variables_to_drop]
else:
self.variables = variables_to_drop
def fit(self, X, y=None):
return self
def transform(self, X):
# drop variables
X = X.copy()
X = X.drop(self.variables, axis=1)
return X
class ConvertToFloat(BaseEstimator,TransformerMixin):
'''
convert numerical variables to float
'''
def __init__(self, variables_to_float=None):
if not isinstance(variables_to_float,list):
self.variables = [variables_to_float]
else:
self.variables = variables_to_float
def fit(self, X,y=None):
return self
def transform(self,X):
X = X.copy()
for var in self.variables:
if var == 'weight':
X[var] = X[var].apply(lambda x: np.float32(x.strip("lbs")) if type(x) == str else x)
else:
X[var] = X[var].astype(np.float32)
return X<file_sep>/packages/recommender_model/recommender.py
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from recommender_model.config import config
from recommender_model.processing.data_management import load_datasets
# import preproc and feature engineering pipelines
from recommender_model import pipeline as pp
# sklearn
from sklearn.preprocessing import normalize
class Recommender:
def __init__(self):
self.df = load_datasets(file_name=config.DATA_FILE)
self.proc_df = pp.proc_pipe.transform(self.df)
self.proc_df.rename(columns={"rented for":"occasion"},inplace=True)
self.user_df = None
self.target_user_df = None
self.recommendations = None
def get_user_info(self,user_info=None):
'''
Pass user information as a list.
Items in the list should be in following order:
Bust size, weight, body type, size, age, height
'''
user_attribs = ["bust size","weight","body type","size","age","height_inch"]
user_info = dict(zip(user_attribs, user_info))
for attrib, val in user_info.items():
if attrib in ["bust size","body type"]:
user_info[attrib] = val if val else np.nan
else:
user_info[attrib] = np.float64(val) if val else np.nan
self.target_user_df = pd.Series(user_info).to_frame().T.dropna(axis=1)
'''
Filter out attibutes from the processed dataframe for
which no information is provided in the target_user_df
and create a new processed df called user_df
'''
user_attribs = self.target_user_df.columns
self.user_df = self.proc_df[["user_id"]+list(user_attribs)]
# Set user id as the index
self.user_df.set_index("user_id",inplace=True)
# Drop repeated row
self.user_df.drop_duplicates(inplace=True)
def transform(self):
# transform both target and user dfs
self.target_user_df = pp.user_pipe.transform(self.target_user_df)
self.user_df = pp.user_pipe.transform(self.user_df)
self.user_df.dropna(inplace=True)
def get_recommendations(self):
'''
Computes cosine similarity between the new customer and
existing customers
'''
user_IDs = np.array(self.user_df.index)
norm_target = np.squeeze(normalize(self.target_user_df))
norm_users = normalize(self.user_df)
similarities = pd.Series(norm_users.dot(norm_target),index=user_IDs)
top_10_similar_users = similarities.sort_values(ascending=False)[:10].index
self.recommendations = self.proc_df[self.proc_df['user_id'].isin(top_10_similar_users)][
["item_id","occasion","category","body type"]].drop_duplicates().reset_index(drop=True)
return self.recommendations
<file_sep>/README.md
# Clothes Recommender System
This repository consists of code to built a clothes recommender web application. The application recommends clothes to existing and new customers of Rent The Runway clothes rental company.
[Clik here to see the demo](https://clothes-recommender-api.herokuapp.com/)
<file_sep>/app.py
import numpy as np
from flask import Flask, request, jsonify, render_template
from recommender_model.recommender import Recommender
app = Flask(__name__)
recommender = Recommender()
@app.route('/')
def home():
return render_template('index.html')
@app.route('/recommend',methods=['POST'])
def recommend():
'''
For rendering results on HTML GUI
'''
user_info = [x for x in request.form.values()]
recommender.get_user_info(user_info)
recommender.transform()
output = recommender.get_recommendations()
return render_template('index.html',
tables=[output.to_html(classes='data')])
if __name__ == "__main__":
app.run(debug=True)<file_sep>/packages/recommender_model/processing/data_management.py
import json
from pandas.io.json import json_normalize
import pandas as pd
from recommender_model.config import config
def load_datasets(*, file_name: str) -> pd.DataFrame:
if 'txt' in file_name:
df = pd.read_csv(f"{config.DATASET_DIR}/{file_name}",sep=',')
else:
with open(f"{config.DATASET_DIR}/{file_name}") as f:
_data = json.loads("[" +
f.read().replace("}\n{", "},\n{") + "]")
df = json_normalize(_data)
return df<file_sep>/packages/setup.py
from distutils.core import setup
setup(
name='recommender_model',
version='0.1.0',
description='Clothes recommendations',
classifiers=[
'Programming Language :: Python :: 3',
],
# Substitute <github_account> with the name of your GitHub account
url='https://github.com/<github_account>/<git repo>',
author='<NAME>', # Substitute your name
author_email='<EMAIL>', # Substitute your email
license='MIT',
packages=['recommender_model'],
install_requires=[
'pypandoc>=1.4',
'pytest>=4.3.1',
'pytest-runner>=4.4',
'click>=7.0'
],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
)<file_sep>/packages/recommender_model/pipeline.py
from sklearn.pipeline import Pipeline
from recommender_model.config import config
from recommender_model.processing import preprocessors as pp
from recommender_model.processing import features as fe
proc_pipe = Pipeline(
[
("Process Height", pp.TransformHeight(config.HEIGHT)),
("Drop Features", pp.DropFeatures(config.VARS_TO_DROP)),
("Convert To Float", pp.ConvertToFloat(config.VARS_TO_NUM)),
]
)
user_pipe = Pipeline(
[
('TrasformBustSize', fe.TransformBustSize(bust_size=config.BUST_SIZE)),
('OneHotEncode', fe.OneHotEncode(variable='body type',
mapper=config.BODY_TYPE_MAP)),
]
)
<file_sep>/packages/recommender_model/processing/features.py
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from recommender_model.config.config import BUST_SIZE, CUP_MAP
class TransformBustSize(BaseEstimator,TransformerMixin):
def __init__(self, bust_size=BUST_SIZE):
self.variable=bust_size
def fit(self, user_df, y=None):
return self
def transform(self, user_df):
user_df = user_df.copy()
if self.variable in user_df.columns:
user_df['cup'] = user_df[self.variable].apply(
lambda x: ''.join(filter(str.isalpha,x)) if type(x) == str else x)
user_df['cup'] = user_df['cup'].map(CUP_MAP)
user_df[self.variable] = user_df[self.variable].apply(
lambda x: np.float(''.join(filter(str.isdigit,x))) if type(x) == str else x)
return user_df
class OneHotEncode(BaseEstimator, TransformerMixin):
def __init__(self,variable=None, mapper=None):
self.variable = variable
self.mapper = mapper
def fit(self, user_df, y=None):
return self
def transform(self, user_df):
user_df = user_df.copy()
if self.variable in user_df.columns:
tmp_df = user_df.apply(
lambda x: self.mapper[x[self.variable]], axis=1, result_type='expand')
tmp_df.columns = [''.join(self.variable.split())+'_{:02d}'.format(ii) for ii in range(tmp_df.shape[1])]
return user_df.drop(self.variable,axis=1).join(tmp_df).drop_duplicates()
else:
return user_df<file_sep>/packages/recommender_model/config/config.py
import pathlib
import recommender_model
import numpy as np
PACKAGE_ROOT = pathlib.Path(recommender_model.__file__).resolve().parent
DATASET_DIR = PACKAGE_ROOT / "datasets"
DATA_FILE = 'renttherunway_final_data.txt' # 'renttherunway_final_data.json'
HEIGHT = 'height'
BUST_SIZE = 'bust size'
VARS_TO_DROP = ["review_text","review_summary","review_date","height"]
VARS_TO_NUM = ['rating','size','age','weight']
CUP_MAP = {
'a': 1, 'aa': 2,
'b': 3,
'c': 4,
'd': 5, 'dd': 6, 'ddde': 7,
'f': 8,
'g': 9,
'h': 10,
'i': 11,
'j': 12
}
BODY_TYPE_MAP = {
'apple': [0, 0, 0, 0, 0, 0, 1],
'athletic': [0, 0, 0, 1, 0, 0, 0],
'full bust': [0, 0, 0, 0, 1, 0, 0],
'hourglass': [1, 0, 0, 0, 0, 0, 0],
'pear': [0, 0, 1, 0, 0, 0, 0],
'petite': [0, 0, 0, 0, 0, 1, 0],
'straight & narrow': [0, 1, 0, 0, 0, 0, 0],
np.nan:[np.nan]*7,
}
FIT_MAP = {
'fit':[0, 0, 1],
'small':[0, 1, 0],
'large':[1, 0, 0],
np.nan:[np.nan]*3,
}
RENTED_FOR_MAP = {
'date':[0, 0, 0, 0, 0, 1, 0, 0],
'everyday':[0, 0, 0, 0, 0, 0, 1, 0],
'formal affair':[0, 0, 0, 1, 0, 0, 0, 0],
'other':[0, 1, 0, 0, 0, 0, 0, 0],
'party':[0, 0, 1, 0, 0, 0, 0, 0],
'vacation':[1, 0, 0, 0, 0, 0, 0, 0],
'wedding':[0, 0, 0, 0, 1, 0, 0, 0],
'work':[0, 0, 0, 0, 0, 0, 0, 1],
np.nan: [np.nan]*8
} | b62890b4aee62b661f3a6181cfe2e24d35a40642 | [
"Markdown",
"Python",
"Text"
] | 10 | Text | limbachia/clothes-recommender-app | ff32e2a7d84f198e6efc920b66464a2bf5e016ee | b049f81db00516356f68fbdb08f8f51e6bf1ad56 |
refs/heads/master | <repo_name>OloberCropp/BrainCoin<file_sep>/keyboard_defs.py
import telebot
from telebot import types
import const
import texts
import html
bot = telebot.TeleBot(const.API_TOKEN)
#Главные клавиатуры
def start_keyboard(message):
murkup = types.ReplyKeyboardMarkup(True, False)
murkup.row('🏆💯💍 Играть 💍💯🏆')
murkup.row('Рейтинг', 'Мой счёт', 'About')
bot.send_message(message.chat.id, '<strong>Играй. Разивайся. Зарабатывай.</strong>', parse_mode="HTML", reply_markup=murkup)
def about_keyboard(message):
murkup = types.ReplyKeyboardMarkup(True, False)
murkup.row('Пригласить друга')
murkup.row('Что-то не так?', 'Назад')
bot.send_message(message.chat.id, texts.about_text, parse_mode="HTML", reply_markup=murkup)
def wallet_keyboard(message):
murkup = types.ReplyKeyboardMarkup(True, False)
murkup.row('Ввести', 'Вывести')
murkup.row('Хочешь больше?')
murkup.row('Назад')
bot.send_message(message.chat.id, 'Загружаю...', reply_markup=murkup)
def freecoins_menu(message): #Меню реферов
murkup = types.ReplyKeyboardMarkup(True, False)
murkup.row('Пригласить друга')
murkup.row('Назад')
bot.send_message(message.chat.id, texts.free_coins, reply_markup=murkup)
def hide(message):
reply_markup = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, "Я вернуcь",reply_markup=reply_markup)<file_sep>/defs.py
import telebot
from telebot import types
import const
import random
import index
import time
import threading
from index import get_db_connection, DBNAME, queries
bot = telebot.TeleBot(const.API_TOKEN)
global rating
def ques_9():
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['Rand_q'])
return cursor.fetchall()
"""
def pquest(message):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['pquest_num_get'], (message.chat.id,))
q_id = cursor.fetchone()[0]
cursor.execute(queries['random_question'], (q_id,q_id+5))
x = cursor.fetchall()
cursor.execute(queries['pquest_num_upd'], (q_id,))
connection.commit()
return x
def fquest(message):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['fquest_num_get'],(message.chat.id,))
q_id = cursor.fetchone()[0]
cursor.execute(queries['random_question'], (q_id,q_id+5))
x = cursor.fetchall()
cursor.execute(queries['fquest_num_upd'], (q_id,))
connection.commit()
return x
"""
def create_question(cur_quests, num):
print(num)
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton(cur_quests[num][2], callback_data="answer1"))
row.append(types.InlineKeyboardButton(cur_quests[num][3], callback_data="answer2"))
markup.row(*row)
row = []
row.append(types.InlineKeyboardButton(cur_quests[num][4], callback_data="answer3"))
row.append(types.InlineKeyboardButton(cur_quests[num][5], callback_data="answer4"))
markup.row(*row)
return markup
def counter_time(call):
try:
battle = const.battle_array.get(call.from_user.id)
except:
return
markup = create_question(battle[0].nine_questions, const.battle_array.get(call.message.chat.id)[1])
second = const.seconds
while second > 0 and const.users_time.get(call.from_user.id) == 1:
try:
bot.edit_message_text(const.time.format(second) + battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
except:
pass
second -= 1
time.sleep(1)
if const.users_time.get(call.from_user.id) == 1 and second == 0: # если время вышло, то
const.users_time.update({call.from_user.id: 2})
try:
bot.edit_message_text("Ввремя вышло, правильный ответ - '" + battle[0].nine_questions[battle[1]][6] + "'.",
call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
time.sleep(2)
const.users_time.update({call.from_user.id: 0})
curr = const.battle_array.get(call.message.chat.id)[1]
e = battle[0].get_another(call.from_user.id)
battle[0].set_ready(call.message.chat.id)
if battle[0].is_two_ready():
battle[0].inc_quest_count()
if (curr == const.count_questions):
const.users_time.update({call.from_user.id: 3})
end_path(call, e, battle)
else:
# отправить следующий вопрос себе
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(
target=counter_time, args=(call,))
my_thread1.start()
# отправить следующий вопрос сопернику
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=counter_time, args=(e,))
my_thread2.start()
else:
const.users_time.update({call.from_user.id: 0})
try:
bot.edit_message_text("Ждём соперника", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text("Ждём соперника", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
def end_path(call, e, battle):
# максимальное количество вопросов достигнута
# удаляем ник противника и глём гифку
#bot.delete_message(call.message.chat.id, call.message.message_id)
#bot.delete_message(e.message.chat.id, e.message.message_id)
if battle[0].cur_bet == 0:
if battle[0].get_score(call.from_user.id) > battle[0].get_score(e.from_user.id):
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('before', Ra, Rb)
upd_rating(call.message, count_new_rating(Ra, Rb, 1))
upd_rating(e.message, count_new_rating(Rb, Ra, 0))
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('after', Ra, Rb)
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)), call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)), e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
elif battle[0].get_score(call.from_user.id) < battle[0].get_score(e.from_user.id):
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('before', Ra, Rb)
upd_rating(call.message, count_new_rating(Ra, Rb, 0))
upd_rating(e.message, count_new_rating(Rb, Ra, 1))
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('after', Ra, Rb)
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)), call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
# отправить следующий вопрос соперникy
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)), e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
else:
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('before', Ra, Rb)
upd_rating(call.message, count_new_rating(Ra, Rb, 0.5))
upd_rating(e.message, count_new_rating(Rb, Ra, 0.5))
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
print('after', Ra, Rb)
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)), call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(
const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id), get_rating(call.message)), call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
# отправить следующий вопрос соперникy
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)), e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id), get_rating(e.message)),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
else:
if battle[0].get_score(call.from_user.id) > battle[0].get_score(e.from_user.id):
upd_money(call.message, get_money(call.message), battle[0].cur_bet)
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
upd_rating(call.message, count_new_rating(Ra, Rb, 1))
upd_rating(e.message, count_new_rating(Rb, Ra, 0))
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
# отправить следующий вопрос соперникy
upd_money(e.message, get_money(e.message), -1 * battle[0].cur_bet)
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
elif battle[0].get_score(call.from_user.id) < battle[0].get_score(e.from_user.id):
upd_money(call.message, get_money(call.message), -1 * battle[0].cur_bet)
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
upd_rating(call.message, count_new_rating(Ra, Rb, 0))
upd_rating(e.message, count_new_rating(Rb, Ra, 1))
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.lose, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
# отправить следующий вопрос соперникy
upd_money(e.message, get_money(e.message), battle[0].cur_bet)
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.win, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
else:
Ra = int(get_rating(call.message))
Rb = int(get_rating(e.message))
upd_rating(call.message, count_new_rating(Ra, Rb, 0.5))
upd_rating(e.message, count_new_rating(Rb, Ra, 0.5))
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(
const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(call.from_user.id),
battle[0].get_score(e.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(call.message))),
call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
# отправить следующий вопрос соперникy
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
try:
bot.edit_message_text(const.end_str.format(const.ne_vam_ne_nam, battle[0].get_score(e.from_user.id),
battle[0].get_score(call.from_user.id),
"Теперь ваш баланс - {} Braincoins".format(
get_money(e.message))),
e.from_user.id,
e.message.message_id)
bot.answer_callback_query(e.id, text="")
except:
pass
try:
const.battle_array.pop(call.message.chat.id)
const.battle_array.pop(e.message.chat.id)
except:
pass
try:
const.in_game.pop(call.message.chat.id)
const.in_game.pop(e.message.chat.id)
except:
pass
try:
const.users_time.pop(call.from_user.id)
const.users_time.pop(e.from_user.id)
except:
pass
def answer(call, num):
# объект класса битвы [0]
#const.users_time.update({call.from_user.id: 0}) уже установлено
battle = const.battle_array.get(call.message.chat.id)
if battle[0].nine_questions[battle[1]][1+num] == battle[0].nine_questions[battle[1]][6]:
# добавляем очков
battle[0].inc_score(call.message.chat.id)
try:
bot.edit_message_text("Вы выбрали правильный ответ.", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text("Вы выбрали правильный ответ.", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
time.sleep(2)
const.users_time.update({call.from_user.id: 0})
# поставить таймер и отсчитывать 3 секунды, показывая сообщение "Правильно"
else:
try:
bot.edit_message_text("Вы ошиблись, правильный ответ - '" + battle[0].nine_questions[battle[1]][6] + "'.", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text(
"Вы ошиблись, правильный ответ - '" + battle[0].nine_questions[battle[1]][6] + "'.",
call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
time.sleep(2)
const.users_time.update({call.from_user.id: 0})
# показать правильный ответ
e = battle[0].get_another(call.from_user.id)
battle[0].set_ready(call.message.chat.id)
if battle[0].is_two_ready():
battle[0].inc_quest_count()
if const.battle_array.get(call.message.chat.id)[1] == const.count_questions:
const.users_time.update({call.from_user.id: 3})
end_path(call, e, battle)
else:
# отправить следующий вопрос себе
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=counter_time, args=(call,))
my_thread1.start()
# отправить следующий вопрос сопернику
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=counter_time, args=(e,))
my_thread2.start()
else: # вывести сообщение, что ждём соперник
try:
bot.edit_message_text("Ждём соперника", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
try:
bot.edit_message_text("Ждём соперника", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
except:
pass
def count_new_rating(ra, rb, sa):
ea = (1/(1 + (10 ** ((rb - ra)/400))))
na = ra + 15 * (sa - ea)
return int(na)
def random_ques():
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['max_ques_id'])
max_ques_id = cursor.fetchone()[0]
x = random.randrange(1, max_ques_id + 1, 1)
cursor.execute(queries['random_question'], (x,))
return cursor.fetchone()
def upd_rating(message, rate):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['rating_update'], (rate, message.chat.id))
connection.commit()
def gl_rate():
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['gl_rate'])
return cursor.fetchall()
def max_id():
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['max_id'])
return cursor.fetchone()[0]
def upd_money(message, money, earn):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cash = money + earn
cursor.execute(queries['money_update'], (cash, message.chat.id))
connection.commit()
def get_rating(message):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['rating_get'], (message.chat.id,))
return cursor.fetchone()[0]
def get_money(message):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['money_get'], (message.chat.id,))
return cursor.fetchone()[0]
def ref_get(ref_chid):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['referal_get'], (ref_chid,))
return cursor.fetchone()[0]<file_sep>/index.py
import telebot
import keyboard_defs
import const
import defs
import texts
import sqlite3
import threading
from telebot import types
from classes import Battle
import flask
import requests
from flask import request
import time
# Запросы
queries = {
'table_users_create': "CREATE TABLE IF NOT EXISTS users (id INTEGER, chat_id INTEGER, username INTEGER, money INTEGER, referal INTEGER, rating INTEGER)",
'table_question_create': "CREATE TABLE IF NOT EXISTS questions (id INTEGER, category VARCHAR(32), question VARCHAR(128), ans1 VARCHAR, ans2 VARCHAR, ans3 VARCHAR, ans4 VARCHAR, right_ansver VARCHAR)",
'rating_update': "UPDATE users SET rating = ? WHERE chat_id = ?",
'money_update': "UPDATE users SET money = ? WHERE chat_id = ?",
'referal_insert': "UPDATE users SET referal = ? WHERE chat_id = ?",
'rating_get': "SELECT rating FROM users WHERE chat_id =?",
'money_get': "SELECT money FROM users WHERE chat_id =?",
'referal_get': "SELECT referal FROM users WHERE chat_id =?",
'user_insert': "INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)",
'user_delete': "DELETE FROM users WHERE chat_id = ?",
'user_get': "SELECT * FROM users WHERE chat_id = ?",
'users_get': "SELECT * FROM users",
'random_usname_chat_id': "SELECT chat_id, username FROM users WHERE id = ? AND NOT chat_id = ?",
'my_chat_id': "SELECT id FROM users WHERE chat_id = ?",
'max_id': "SELECT max(id) FROM users",
'max_ques_id': "SELECT max(id) FROM questions",
'random_question': "SELECT * FROM questions WHERE id = ?",
'Rand_q': "SELECT * FROM questions WHERE id IN (SELECT id FROM questions ORDER BY RANDOM() LIMIT 5)",
'inc_ref': "UPDATE users SET referal=? WHERE chat_id=?",
'gl_rate': "SELECT username, rating FROM users ORDER BY rating DESC"
}
DBNAME = 'main.db'
def get_db_connection(DBNAME):
"""
:param dbname: <str> name of database (like test.db)
:return: <sqlite3.connection>
"""
return sqlite3.connect(DBNAME)
bot = telebot.TeleBot(const.API_TOKEN)
app = flask.Flask(__name__)
"""
def exit_loop():
word = ''
while word != 'stop':
word = input()
exit(0)
"""
connection = get_db_connection('main.db')
connection.execute(queries['table_users_create'])
connection.execute(queries['table_question_create'])
connection.commit()
connection.close()
welcome_text = """Ваш противник: {}"""
your_bet_is = """Ваша ставка: {} Braincoin-ов"""
bet = 0
def create_question(cur_quests, num):
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton(cur_quests[num][2], callback_data="answer1"))
row.append(types.InlineKeyboardButton(cur_quests[num][3], callback_data="answer2"))
markup.row(*row)
row = []
row.append(types.InlineKeyboardButton(cur_quests[num][4], callback_data="answer3"))
row.append(types.InlineKeyboardButton(cur_quests[num][5], callback_data="answer4"))
markup.row(*row)
return markup
@bot.callback_query_handler(func=lambda call: call.data == 'answer1')
def answer1(call):
const.users_time.update({call.from_user.id: 2})
defs.answer(call, 1)
@bot.callback_query_handler(func=lambda call: call.data == 'answer2')
def answer2(call):
const.users_time.update({call.from_user.id: 2})
defs.answer(call, 2)
@bot.callback_query_handler(func=lambda call: call.data == 'answer3')
def answer3(call):
const.users_time.update({call.from_user.id: 2})
defs.answer(call, 3)
@bot.callback_query_handler(func=lambda call: call.data == 'answer4')
def answer4(call):
const.users_time.update({call.from_user.id: 2})
defs.answer(call, 4)
@bot.callback_query_handler(func=lambda call: call.data == 'accept')
def accept_bet(call):
#начaло самой игры
print("user started the game")
try:
bet = const.in_game.get(call.message.chat.id)
except:
bet = 25
if bet == 25:
if defs.get_money(call.message) >= 25:
if len(const.map_25) == 0:
const.map_25.append([call.message.chat.id, call.message.chat.first_name, call])
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Отмена поиска", callback_data="cancel_25_search"))
markup.row(*row)
# изменение текста на "Поиск соперника"
bot.edit_message_text("Поиск соперника", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
return
elif const.map_25[0][0] != call.message.chat.id:
x = Battle(call.message, const.map_25[0], 25)
const.battle_array.update({call.message.chat.id: [x, 0]})
const.battle_array.update({const.map_25[0][0]: [x, 0]})
battle = const.battle_array.get(call.message.chat.id)
battle[0].set_id(call)
battle[0].set_id(const.map_25[0][2])
try:
const.map_25.remove(const.map_25[0])
except:
pass
# отправка сообщения сопернику
e = battle[0].get_another(call.from_user.id)
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=defs.counter_time, args=(call,))
my_thread1.start()
# print("ya tut")
# bot.edit_message_text(battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
# reply_markup=markup)
# bot.answer_callback_query(call.id, text="")
# отправить следующий вопрос соперника
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=defs.counter_time, args=(e,))
my_thread2.start()
else:
bot.edit_message_text("Маловато у тебя Braincoin, для такой ставки, выбери меньше.", call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
time.sleep(3)
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
elif bet == 50:
if defs.get_money(call.message) >= 50:
if len(const.map_50) == 0:
const.map_50.append([call.message.chat.id, call.message.chat.first_name, call])
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Отмена поиска", callback_data="cancel_50_search"))
markup.row(*row)
# изменение текста на "Поиск соперника"
bot.edit_message_text("Поиск соперника", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
return
elif const.map_50[0][0] != call.message.chat.id:
x = Battle(call.message, const.map_50[0], 50)
const.battle_array.update({call.message.chat.id: [x, 0]})
const.battle_array.update({const.map_50[0][0]: [x, 0]})
battle = const.battle_array.get(call.message.chat.id)
battle[0].set_id(call)
battle[0].set_id(const.map_50[0][2])
try:
const.map_50.remove(const.map_50[0])
except:
pass
# отправка сообщения сопернику
e = battle[0].get_another(call.from_user.id)
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=defs.counter_time, args=(call,))
my_thread1.start()
# print("ya tut")
# bot.edit_message_text(battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
# reply_markup=markup)
# bot.answer_callback_query(call.id, text="")
# отправить следующий вопрос соперника
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=defs.counter_time, args=(e,))
my_thread2.start()
else:
bot.edit_message_text("Маловато у тебя Braincoin, для такой ставки, выбери меньше.", call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
time.sleep(3)
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
elif bet == 100:
if defs.get_money(call.message) >= 100:
if len(const.map_100) == 0:
const.map_100.append([call.message.chat.id, call.message.chat.first_name, call])
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Отмена поиска", callback_data="cancel_100_search"))
markup.row(*row)
# изменение текста на "Поиск соперника"
bot.edit_message_text("Поиск соперника", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
return
elif const.map_100[0][0] != call.message.chat.id:
x = Battle(call.message, const.map_100[0], 100)
const.battle_array.update({call.message.chat.id: [x, 0]})
const.battle_array.update({const.map_100[0][0]: [x, 0]})
battle = const.battle_array.get(call.message.chat.id)
battle[0].set_id(call)
battle[0].set_id(const.map_100[0][2])
try:
const.map_100.remove(const.map_100[0])
except:
pass
# отправка сообщения сопернику
e = battle[0].get_another(call.from_user.id)
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=defs.counter_time, args=(call,))
my_thread1.start()
# print("ya tut")
# bot.edit_message_text(battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
# reply_markup=markup)
# bot.answer_callback_query(call.id, text="")
# отправить следующий вопрос соперника
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=defs.counter_time, args=(e,))
my_thread2.start()
else:
bot.edit_message_text("Маловато у тебя Braincoin, для такой ставки, выбери меньше.", call.from_user.id,
call.message.message_id)
bot.answer_callback_query(call.id, text="")
time.sleep(3)
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
elif bet == 200:
if defs.get_money(call.message) >= 200:
if len(const.map_200) == 0:
const.map_200.append([call.message.chat.id, call.message.chat.first_name, call])
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Отмена поиска", callback_data="cancel_200_search"))
markup.row(*row)
# изменение текста на "Поиск соперника"
bot.edit_message_text("Поиск соперника", call.from_user.id, call.message.message_id,
reply_markup=markup)
bot.answer_callback_query(call.id, text="")
return
elif const.map_200[0][0] != call.message.chat.id:
x = Battle(call.message, const.map_200[0], 200)
const.battle_array.update({call.message.chat.id: [x, 0]})
const.battle_array.update({const.map_200[0][0]: [x, 0]})
battle = const.battle_array.get(call.message.chat.id)
battle[0].set_id(call)
battle[0].set_id(const.map_200[0][2])
try:
const.map_200.remove(const.map_200[0])
except:
pass
# отправка сообщения сопернику
e = battle[0].get_another(call.from_user.id)
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=defs.counter_time, args=(bet, call))
my_thread1.start()
# print("ya tut")
# bot.edit_message_text(battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
# reply_markup=markup)
# bot.answer_callback_query(call.id, text="")
# отправить следующий вопрос соперника
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=defs.counter_time, args=(bet, e))
my_thread2.start()
else:
bot.edit_message_text("Маловато у тебя Braincoin, для такой ставки, выбери меньше.", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
time.sleep(3)
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "cancel_free_search")
def cancel_search(call):
const.map_free.remove(const.map_free[0])
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "cancel_25_search")
def cancel_25_search(call):
const.map_25.remove(const.map_25[0])
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "cancel_50_search")
def cancel_50_search(call):
const.map_50.remove(const.map_50[0])
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "cancel_100_search")
def cancel_100_search(call):
const.map_100.remove(const.map_100[0])
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "cancel_200_search")
def cancel_200_search(call):
const.map_200.remove(const.map_200[0])
markup = create_choice()
bot.edit_message_text("Выбери свою ставку чтобы начать ⚔️", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == 'accept_free')
def accept_bet(call):
#начaло самой игры
print("user started the free game")
if len(const.map_free) == 0:
const.map_free.append([call.message.chat.id, call.message.chat.first_name, call])
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Отмена поиска", callback_data="cancel_free_search"))
markup.row(*row)
#изменение текста на "Поиск соперника"
bot.edit_message_text("Поиск соперника", call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
return
elif const.map_free[0][0] != call.message.chat.id:
x = Battle(call.message, const.map_free[0], 0)
const.battle_array.update({call.message.chat.id: [x, 0]})
const.battle_array.update({const.map_free[0][0]: [x, 0]})
battle = const.battle_array.get(call.message.chat.id)
battle[0].set_id(call)
battle[0].set_id(const.map_free[0][2])
try:
const.map_free.remove(const.map_free[0])
except:
pass
# отправка сообщения сопернику
e = battle[0].get_another(call.from_user.id)
const.users_time.update({call.from_user.id: 1})
my_thread1 = threading.Thread(target=defs.counter_time, args=(call,))
my_thread1.start()
# print("ya tut")
# bot.edit_message_text(battle[0].nine_questions[battle[1]][1], call.from_user.id, call.message.message_id,
# reply_markup=markup)
# bot.answer_callback_query(call.id, text="")
# отправить следующий вопрос соперника
const.users_time.update({e.from_user.id: 1})
my_thread2 = threading.Thread(target=defs.counter_time, args=(e,))
my_thread2.start()
def create_choice():
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("0 (На интерес)", callback_data="accept_free"))
markup.row(*row)
row = []
row.append(types.InlineKeyboardButton("25", callback_data="bet_25"))
row.append(types.InlineKeyboardButton("50", callback_data="bet_50"))
row.append(types.InlineKeyboardButton("100", callback_data="bet_100"))
row.append(types.InlineKeyboardButton("200", callback_data="bet_200"))
markup.row(*row)
row = []
row.append(types.InlineKeyboardButton("Подтвердить и начать", callback_data="accept"))
markup.row(*row)
return markup
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_25')
def change_bet_25(curr_bet):
const.in_game.update({curr_bet.message.chat.id: 25})
markup = create_choice()
bot.edit_message_text(your_bet_is.format(25), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_50')
def change_bet_50(curr_bet):
const.in_game.update({curr_bet.message.chat.id: 50})
markup = create_choice()
bot.edit_message_text(your_bet_is.format(50), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_100')
def change_bet_100(curr_bet):
const.in_game.update({curr_bet.message.chat.id: 100})
markup = create_choice()
bot.edit_message_text(your_bet_is.format(100), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_200')
def change_bet_200(curr_bet):
const.in_game.update({curr_bet.message.chat.id: 200})
markup = create_choice()
bot.edit_message_text(your_bet_is.format(200), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.message_handler(commands=['start'])
def start(message):
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute(queries['user_get'], (message.chat.id,))
if cursor.fetchone() is None:
x = message.text[7:]
if x != '':
y = int(defs.ref_get(x))+1
cursor.execute(queries['inc_ref'], (y, x))
bot.send_message(x, "Привет, твой друг: "+message.chat.first_name+""" перешёл по твоей ссылке!
теперь у тебя: """+str(y)+""" приглашений, ещё:
"""+str(5-y)+""" до очистки рекламы, и
"""+str(13-y)+""" до снятия комиссии""")
connection.commit()
# Создание нумерации пользователей
connection = get_db_connection(DBNAME)
cursor = connection.cursor()
cursor.execute('SELECT max(id) FROM users')
max_id = cursor.fetchone()[0]
try:
if max_id is None:
max_id = 0
except:
pass
# Запись пользователя в базу
money = 0
rating = 1200
referal = 0
payedquest = 1
freequest = 1
cursor.execute(queries['user_insert'], (max_id+1, message.chat.id, message.chat.first_name, money, referal, rating, payedquest, freequest))
connection.commit()
print(message.chat.id, 'started the bot.')
bot.send_message(message.chat.id, 'Привет, ' + message.chat.first_name + texts.Start_text )
else:
bot.send_message(message.chat.id, '<strong>С возвращением, '+message.chat.first_name+"</strong>\n"+'Загружаю твой прогресс...', parse_mode="HTML")
cursor.close()
connection.close()
print(message.chat.id, 'started the bot')
keyboard_defs.start_keyboard(message)
def send_pay(message, call):
if call == 0:
r = requests.post(const.BOT_GET_WALLET,
data={'k': const.TRADE_TOKEN, 'tgid': message.chat.id})
js = r.json()
if js["ok"] == 1:
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Я оплатил", callback_data="cp_%s" % js['wi']))
row.append(types.InlineKeyboardButton("Отмена", callback_data="cancel"))
markup.row(*row)
bot.send_message(message.chat.id, '💳Перевод по номеру карты VISA.'
+ "\n\nПополнение через карту QIWI: \n<stong>" + js["r"]
+ "</strong>\n\nПополнение через QIWI кошелёк: \n<strong>" + js['qw']
+ "\n\n\n" + "Для пополнения балланса переведите необходимую сумму на счёт и нажмите \"Я оплатил\"</strong>"
+ "\n\n<strong>Если решили повременить, пожалуйста, освободите реквизит, нажав на кнопку \"Отмена\""
+ "\n\nТекущий курс BrainCoin к российскому рублю 0.89/1.00"
+ "\n\nРеквизит выдаётся на 30 минут!!!</strong>", parse_mode="HTML", reply_markup=markup)
else:
bot.send_message(message.chat.id, "Свободного реквизита нет, повторите попытку через 15 минут.")
else:
r = requests.post(const.BOT_GET_WALLET,
data={'k': const.TRADE_TOKEN, 'tgid': message.chat.id})
js = r.json()
if js["ok"] == 1:
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Я оплатил", callback_data="cp_%s" % js['wi']))
row.append(types.InlineKeyboardButton("Отмена", callback_data="cancel"))
markup.row(*row)
bot.edit_message_text('💳Перевод по номеру карты VISA.'
+ "\n\nПополнение через карту QIWI: \n<stong>" + js["r"]
+ "</strong>\n\nПополнение через QIWI кошелёк: \n<strong>" + js['qw']
+ "\n\n\n" + "Для пополнения балланса переведите необходимую сумму на счёт и нажмите \"Я оплатил\"</strong>"
+ "\n\n<strong>Если решили повременить, пожалуйста, освободите реквизит, нажав на кнопку \"Отмена\""
+ "\n\nТекущий курс BrainCoin к российскому рублю 0.89/1.00"
+ "\n\nРеквизит выдаётся на 30 минут!!!</strong>",
call.from_user.id, call.message.message_id, parse_mode="HTML", reply_markup=markup)
bot.answer_callback_query(call.id, text="")
else:
bot.send_message(message.chat.id, "Свободного реквизита нет, повторите попытку через 15 минут.")
@bot.callback_query_handler(func=lambda call: call.data == 'cancel')
def cancel_button(call):
keyboard_defs.start_keyboard(call.message)
bot.edit_message_text('Платёж отменён', call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data[:3] == 'cp_')
def check_pay(call):
r = requests.post(const.BOT_CHECK_PAY,
data={'k': const.TRADE_TOKEN, 'wi': call.data[3:]})
js = r.json()
if js['a'] == 0:
bot.edit_message_text("Средства ещё не поступили на счёт.", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
time.sleep(3)
send_pay(call.message, call)
else:
earn = int(js['a'])
money = defs.get_money(call.message)
defs.upd_money(call.message, money, earn)
bot.send_message(call.message.chat.id, 'Ты пополнил кошелёк на %s' % js['a'] + "\n\n"
+ 'Теперь на твоём счету: ' + str(defs.get_money(call.message)) + ' BrainCoin-ов!')
def pay_out(message):
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Я ввёл реквизит", callback_data="out_1"))
markup.row(*row)
bot.send_message(message.chat.id, 'Введите ваш номер кошелька киви в формате 79991112233 и нажмите на кнопку \"Я ввёл реквизит\"\n\n'
+ 'Порядок действий:\nОтправить боту сообщение с вашим номером QIWI кошелька -> Нажать на кнопку', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data == 'out_1')
def out(call):
if len(const.last_sended_message.get(call.from_user.id)) == 11:
const.pay_req.update({call.from_user.id : const.last_sended_message.get(call.from_user.id)})
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("Я ввёл сумму вывода", callback_data="out_2"))
markup.row(*row)
bot.edit_message_text('Введите сумму вывода не превышающую ваш баланс и нажмите на кнопку'
+ '"Я ввёл сумму вывода\"\n\nУ вас на счету: '
+ str(defs.get_money(call.message)) + ' BrainCoin-ов.',
call.from_user.id, call.message.message_id, reply_markup=markup)
bot.answer_callback_query(call.id, text="")
else:
bot.edit_message_text("Вы ввели не корректный номер️", call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
@bot.callback_query_handler(func=lambda call: call.data == "out_2")
def out2(call):
if int(const.last_sended_message.get(call.from_user.id)) <= defs.get_money(call.message):
r = requests.post(const.BOT_PAY_OUT,
data={'k': const.TRADE_TOKEN, 'd': const.pay_req.get(call.from_user.id),
'a': int(const.last_sended_message.get(call.from_user.id))})
js = r.json()
earn = -1 * int(const.last_sended_message.get(call.from_user.id))
defs.upd_money(call.message, defs.get_money(call.message), earn)
bot.edit_message_text('Ты вывел %s' % const.last_sended_message.get(call.from_user.id)
+ " BrainCoin-ов.\n\n" + 'Теперь на твоём счету: ' + str(defs.get_money(call.message))
+ ' BrainCoin-ов.', call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
else:
bot.edit_message_text('Маловато у тебя BrainCoin-ов для такого вывода!', call.from_user.id, call.message.message_id)
bot.answer_callback_query(call.id, text="")
@bot.message_handler(content_types='text')
def start_handler(message):
if message.text == 'Рейтинг':
f = defs.gl_rate()
global i
i = 0
while message.chat.first_name != f[i][0]:
i += 1
stri = '1 место: '+ f[0][0] + ' с рейтингом: ' + str(f[0][1]) + "\n" + '2 место: '\
+ f[1][0] + ' с рейтингом: ' + str(f[1][1]) + "\n" + '3 место: ' + f[2][0]\
+ ' с рейтингом: ' + str(f[2][1]) + "\n" + '4 место: ' + f[3][0] + ' с рейтингом: ' \
+ str(f[3][1]) + "\n"+ '5 место: '+f[4][0]+ ' с рейтингом: '+str(f[4][1])
bot.send_message(message.chat.id, stri)
bot.send_message(message.chat.id, 'Твой рейтинг: ' + str(defs.get_rating(message))
+ '\n' + 'Позиция в рейтинге: ' + str(i+1))
elif message.text == 'About':
keyboard_defs.about_keyboard(message)
elif message.text == 'Назад':
keyboard_defs.start_keyboard(message)
elif message.text == '🏆💯💍 Играть 💍💯🏆':
markup = create_choice()
bot.send_message(message.chat.id, "Выбери свою ставку чтобы начать ⚔️", reply_markup=markup)
elif message.text == 'Мой счёт':
keyboard_defs.wallet_keyboard(message)
bot.send_message(message.chat.id, 'На твоём счету ' + str(defs.get_money(message)) + ' BrainCoin-ов')
elif message.text == 'Ввести':
send_pay(message, 0)
elif message.text == 'Вывести':
pay_out(message)
elif message.text == 'Хочешь больше?':
keyboard_defs.freecoins_menu(message)
elif message.text == 'Написать о проблеме':
bot.send_message(message.chat.id, """Напиши нашему менеджеру о своей проблеме.
Это может быть как баг, так и ошибка перевода средств.""")
elif message.text == 'Пригласить друга':
bot.send_message(message.chat.id, """Твоя персональная ссылка:
https://telegram.me/Crypto_Shit_Fucking_bot?start="""+str(message.chat.id))
else:
const.last_sended_message.update({message.chat.id: message.text})
bot.send_message(680328648, 'Сообщение от: ' + message.chat.first_name + """
Следующего содержания: """ + message.text)
@app.route('/', methods=['GET', 'HEAD'])
def index():
return ''
@app.route(const.WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
if flask.request.headers.get('content-type') == 'application/json':
json_string = flask.request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
flask.abort(403)
if __name__ == '__main__':
print('launching bot')
bot.remove_webhook()
time.sleep(1)
bot.set_webhook(url=const.WEBHOOK_URL_BASE + const.WEBHOOK_URL_PATH,
certificate=open(const.WEBHOOK_SSL_CERT, 'rb'))
app.run(host=const.WEBHOOK_LISTEN,
port=const.WEBHOOK_PORT,
ssl_context=(const.WEBHOOK_SSL_CERT, const.WEBHOOK_SSL_PRIV),
debug=True)
"""
if __name__ == '__main__':
bot.polling(none_stop=True)
"""<file_sep>/README.md
# BrainCoin
BrainCoin
<file_sep>/classes.py
#import random
import const
import defs
from telebot import types
import telebot
bot = telebot.TeleBot(const.API_TOKEN)
# const for battle
welcome_text = """Ваш противник {}"""
your_bet_is = """Ваша ставка - {}"""
def create_choice():
markup = types.InlineKeyboardMarkup()
row = []
row.append(types.InlineKeyboardButton("50", callback_data="bet_50"))
row.append(types.InlineKeyboardButton("100", callback_data="bet_100"))
row.append(types.InlineKeyboardButton("200", callback_data="bet_200"))
markup.row(*row)
return markup
def create_table_vote(num):
markup = types.InlineKeyboardMarkup()
if num == 0:
row = []
row.append(types.InlineKeyboardButton("1 theme", callback_data="set_1_t" + "1 theme"))
row.append(types.InlineKeyboardButton("2 theme", callback_data="set_1_t" + "2 theme"))
row.append(types.InlineKeyboardButton("3 theme", callback_data="set_1_t" + "3 theme"))
markup.row(*row)
row = []
row.append(types.InlineKeyboardButton("1 theme", callback_data="set_3_t" + "1 theme"))
row.append(types.InlineKeyboardButton("2 theme", callback_data="set_3_t" + "2 theme"))
row.append(types.InlineKeyboardButton("3 theme", callback_data="set_3_t" + "3 theme"))
markup.row(*row)
else:
row = []
row.append(types.InlineKeyboardButton("1 theme", callback_data="set_2_t" + "1 theme"))
row.append(types.InlineKeyboardButton("2 theme", callback_data="set_2_t" + "2 theme"))
row.append(types.InlineKeyboardButton("3 theme", callback_data="set_2_t" + "3 theme"))
markup.row(*row)
return markup
class Battle:
def __init__(self, message, s_us, bet):
# убрать пользователя из базы ищущих игру
# s_us = id, username, call
self.cur_bet = bet
self.first_player = message.chat.id
self.name_fp = message.chat.username
# get_user = defs.random_user(message)
self.second_player = s_us[0] # get_user[0] #get id
self.name_sp = s_us[1] # get_user[1] #get username
self.sp_call = s_us[2]
bot.send_message(self.first_player, welcome_text.format(self.name_sp))
bot.send_message(self.second_player, welcome_text.format(self.name_fp))
self.fp_score = 0
self.sp_score = 0
self.fp_ready = 0
self.sp_ready = 0
self.nine_questions = defs.ques_9()
print(len(self.nine_questions))
# self.fp_ready = 0
# self.sp_ready = 0
# self.tema1 = "Не выбрана"
# self.tema2 = "Не выбрана"
# self.tema3 = "Не выбрана"
# self.temaN = "Её выбирает соперник"
# self.start_battle()
def set_id(self, call):
if self.first_player == call.message.chat.id:
self.fp_call = call
else:
self.sp_call = call
def get_another(self, cur_id):
if self.first_player == cur_id:
return self.sp_call
else:
return self.fp_call
def inc_quest_count(self):
const.battle_array.get(self.first_player)[1] += 1
const.battle_array.get(self.second_player)[1] += 1
def inc_score(self, id):
if self.first_player == id:
self.fp_score += 1
else:
self.sp_score += 1
def get_score(self, id):
if self.first_player == id:
return self.fp_score
else:
return self.sp_score
def set_ready(self, id):
if self.first_player == id:
self.fp_ready = 1
else:
self.sp_ready = 1
def is_two_ready(self):
if self.fp_ready == 1 and self.sp_ready == 1:
self.fp_ready = 0
self.sp_ready = 0
return True
else:
return False
x = """
def set_fp_theme_id(self, id):
self.fp_theme_id = id
def set_sp_theme_id(self, id):
self.sp_theme_id = id
def start_battle(self):
# выводим выбор категорий
x = random.randrange(0, 2, 1)
print(x)
if x == 0:
markup1 = create_table_vote(0)
markup2 = create_table_vote(1)
self.fp_num = 0
self.sp_num = 1
bot.send_message(self.first_player,
"Первая тема - {}\nВторая тема - {}\nТретья тема - {}".format(self.tema1, self.temaN, self.tema3),
reply_markup=markup1)
bot.send_message(self.second_player,
"Первая тема - {}\nВторая тема - {}\nТретья тема - {}".format(self.temaN, self.tema2, self.temaN),
reply_markup=markup2)
else:
markup1 = create_table_vote(0)
markup2 = create_table_vote(1)
self.fp_num = 1
self.sp_num = 0
bot.send_message(self.second_player,
"Первая тема - {}\nВторая тема - {}\nТретья тема - {}".format(self.tema1, self.temaN, self.tema3),
reply_markup=markup1)
bot.send_message(self.first_player,
"Первая тема - {}\nВторая тема - {}\nТретья тема - {}".format(self.temaN, self.tema2, self.temaN),
reply_markup=markup2)
# выводим кнопк
"""
hui = """
@bot.message_handler(commands=['start'])
def start(message):
#const.map[message] = [message.chat.username, 0]
keyboard_defs.start_keyboard(message)
############################################
def sender(u_id, message_id, num, t_id):
markup = create_table_vote(num)
bot.edit_message_text(const.theme.format(const.battle_array.get(u_id).tema1,
const.battle_array.get(u_id).tema2,
const.battle_array.get(u_id).tema3),
u_id, message_id, reply_markup=markup)
bot.answer_callback_query(t_id, text="")
@bot.callback_query_handler(func=lambda theme: theme.data[0:7] == 'set_1_t')
def change_1_theme(theme):
const.battle_array.get(theme.from_user.id).tema1 = theme.data[7:]
markup = create_table_vote(0)
bot.edit_message_text(const.theme.format(const.battle_array.get(theme.from_user.id).tema1,
const.battle_array.get(theme.from_user.id).tema2,
const.battle_array.get(theme.from_user.id).tema3),
theme.from_user.id, theme.message.message_id, reply_markup=markup)
bot.answer_callback_query(theme.id, text="")
#sender(theme.from_user.id, theme.message.message_id, 1, theme.id)
@bot.callback_query_handler(func=lambda theme: theme.data[0:7] == 'set_2_t')
def change_2_theme(theme):
const.battle_array.get(theme.from_user.id).tema2 = theme.data[7:]
markup = create_table_vote(1)
bot.edit_message_text(const.theme.format(const.battle_array.get(theme.from_user.id).tema1,
const.battle_array.get(theme.from_user.id).tema2,
const.battle_array.get(theme.from_user.id).tema3),
theme.from_user.id, theme.message.message_id, reply_markup=markup)
bot.answer_callback_query(theme.id, text="")
#sender(theme.from_user.id, theme.message.message_id, 0, theme.id)
@bot.callback_query_handler(func=lambda theme: theme.data[0:7] == 'set_3_t')
def change_3_theme(theme):
const.battle_array.get(theme.from_user.id).tema3 = theme.data[7:]
markup = create_table_vote(0)
bot.edit_message_text(const.theme.format(const.battle_array.get(theme.from_user.id).tema1,
const.battle_array.get(theme.from_user.id).tema2,
const.battle_array.get(theme.from_user.id).tema3),
theme.from_user.id, theme.message.message_id, reply_markup=markup)
bot.answer_callback_query(theme.id, text="")
#sender(theme.from_user.id, theme.message.message_id, 1, theme.id)
##############################################
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_50')
def change_bet_50(curr_bet):
const.bet = 50
markup = create_choice()
bot.edit_message_text(your_bet_is.format(str(const.bet)), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_100')
def change_bet_50(curr_bet):
const.bet = 100
markup = create_choice()
bot.edit_message_text(your_bet_is.format(str(const.bet)), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.callback_query_handler(func=lambda curr_bet: curr_bet.data == 'bet_200')
def change_bet_50(curr_bet):
const.bet = 200
markup = create_choice()
bot.edit_message_text(your_bet_is.format(str(const.bet)), curr_bet.from_user.id, curr_bet.message.message_id, reply_markup=markup)
bot.answer_callback_query(curr_bet.id, text="")
@bot.message_handler(content_types='text')
def start_handler(message):
if message.text == 'Заработать':
markup = create_choice()
bot.send_message(message.chat.id, your_bet_is.format(str(const.bet)), reply_markup=markup)
keyboard_defs.paygame_keyboard(message)
elif message.text == 'Поиск':
if len(const.map) == 0:
const.map.append([message.chat.id, message.chat.username, 1])
else:
x = battle(message, const.map[0][0], const.map[0][1])
const.battle_array.update({message.chat.id: x})
#const.battle_array[-1].start_battle
elif message.text == 'Назад':
try:
const.map.extend([message.chat.id, message.chat.username, 1])
except:
pass
keyboard_defs.start_keyboard(message)
if __name__ == '__main__':
bot.polling(none_stop=True)
"""<file_sep>/texts.py
Start_text = ''', добро пожаловать в BrainStorm Bot!
Этот игра, сделанная по идее блокбастера "<NAME>",
но как минимму с одним отличием...
Теперь ты можешь зарабатывать своим умом!
полную инструкцию ты найдёшь в "About".
Играй. Познавай. Зарабатывай.
Удачи тебе!'''
about_text = """<strong>________Как играть________</strong>
В игре есть 2 режима, обычный и со ставками.
<strong>Если у вас нет денег на счету.</strong>
Вы можете:
Внести их перейдя в кошелёк.
Играть в обычном режиме.
Нажать на кнопку "Хочу больше"*
Тут мы будем предлагать вам различные предложения
каждый день, чтобы пополнить ваш карман.
<strong>***Игра***</strong>
Далее выбери свою ставку или стартуй.
Начинается поиск соперника...
Советуем не отвлекаться, скорее всего игра уже началась и ты потеряешь свои драгоценные BrainCoins.
На выбор правильного варианта у тебя именно столько времени сколько нужно для честной игры (да-да, загуглить не получится).
После завершения победивший игрок получает удвоенную ставку.
<strong>___Рейтинг___</strong>
С начала игры у тебя есть рейтинг 1200.
В конце каждого месяца мы даём ценные призы трём лучшим игрокам.
<strong>Не упусти свой шанс показать свои навыки!!!</strong>
<strong>Вуаля! Удачной игры!</strong>"""
paymenu_text = """<strong>___ПРАВИЛА ИГРЫ___</strong>
Режим <strong>ставок</strong>:
Ты можешь поставить на свою победу!
Ты играешь с человеком, ставка которого равна твоей.
<strong>После окончания игры все ставки переходит победителю если таковой имеется.</strong>
Режим <strong>"На интерес"</strong>:
Здесь ты можешь расслабиться от напряжённых битв за вознаграждение или проверить свой уровень знаний, сражаясь с оппонентом на интерес.
<strong>В игре 5 вопросов</strong>
<strong>На каждый по 8 секунд для выбора</strong>
<strong>Играй. Познавай. Зарабатывай.</strong>
Удачи!
"""
free_coins = """
Предложение, от которого сложно отказаться...
Не хочешь отдавать комиссию с каждой манипуляцией со своими средствами?
Пригласи 7 друзей в нашу игру и зарабатывай БЕЗ КОМИССИИ!!!
Как только все семь друзей зайдут в игру и хоть один из них сделает свою первую ставку, ты сможешь забыть про комиссиию!
"Как это сделать?"
Проще простого, нажимай на кнопку "Пригласить друга" и получи свою уникальную ссылку.
Отправь эту ссылку друзьям... Готово!!!
""" | 4794558fce117a825898a409d430f340109a8a73 | [
"Markdown",
"Python"
] | 6 | Python | OloberCropp/BrainCoin | bbd1fbb1d9451c6e431d54cb7bc2af3fbda1464a | 6e5d87135d59374d71b0e682aafb8ec55c278060 |
refs/heads/master | <file_sep>## Toolchain configuration
CC = mips-linux-gnu-gcc
LD = mips-linux-gnu-ld
AS = mips-linux-gnu-as
AR = mips-linux-gnu-ar
## Options
CFLAGS = -Wall -W -O1 -std=c99 -pedantic
LDFLAGS = -static
## Targets
all :: false.s false true.s true hello.s hello yes.s yes
clean :: ; $(RM) false.s false true.s true hello.s hello yes.s yes
## Pattern Rules
%.s : %.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -S -o $@ $<
<file_sep>/* yes - implementation of /bin/yes - public domain. */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static char buf[8192];
static unsigned bufused;
/* append string to buffer */
static void addbuf(const char *s)
{
unsigned n = strlen(s);
memcpy(buf + bufused, s, n);
bufused += n;
}
static void repbuf(void)
{
unsigned n = bufused;
/* copy - doubling each time */
while (bufused * 2 < sizeof(buf)) {
memcpy(buf + bufused, buf, bufused);
bufused *= 2;
}
/* copy linearly */
while (bufused + n < sizeof(buf)) {
memcpy(buf + bufused, buf, n);
bufused += n;
}
}
static void loopbuf(void)
{
while (1) {
ssize_t written;
unsigned total;
for (total = 0; total < bufused; total += written) {
written = write(STDOUT_FILENO, buf, bufused);
if (written <= 0)
return; /* error */
}
}
}
int main(int argc, char **argv)
{
/* bufused = 0; * reset buffer position */
if (argc == 1) {
addbuf("y\n");
} else {
int i;
for (i = 1; i < argc; i++) {
addbuf(argv[i]);
addbuf(i + 1 < argc ? " " : "\n");
}
}
repbuf();
loopbuf();
perror(argv[0]);
return 1;
}
<file_sep># MIPS program examples
## Ownership, License and Copyright Information
mips-tutorial - MIPS program examples
Written in 2018 by <NAME> <<EMAIL>>
To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the public
domain worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along with
this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
## Programs
* true - returns true to the shell (0)
* false - returns false to the shell (1)
* hello - Prints "Hello World" message
## Setup: How to setup MIPS toolchain (gcc) on Ubuntu 14.04
### Step 1: Add following to /etc/apt/sources.list
```
## add in Squeeze (Debian 6.0) and Emdebian
deb http://archive.debian.org/debian squeeze main
deb http://archive.debian.org/debian squeeze-lts main
deb http://www.emdebian.org/debian/ squeeze main
```
### Step 2: Update apt and instal keyrings
```
sudo apt-get update
sudo apt-get install debian-archive-keyring debian-ports-archive-keyring
sudo apt-get install emdebian-archive-keyring
```
### Step 3: Install MIPS tools
```
apt-get install linux-libc-dev-mips-cross libc6-mips-cross \
libc6-dev-mips-cross binutils-mips-linux-gnu \
gcc-4.4-mips-linux-gnu g++-4.4-mips-linux-gnu
```
### Step 4: Check MIPS tools
mips-linux-gnu-gcc -dumpmachine
### Step 5: Install qemu tools (optional)
sudo apt-get install qemu qemu-system-mips qemu-user
### Step 6: Install MIPS simulators (optional)
The classic option is SPIM, but it has some syntax limiations that makes it hard to use the output of gcc directly.
```
sudo apt-get install spim
```
Another option is drmips. (I haven't done much with it myself)
```
sudo apt-get install drmips
```
## Building
You should be able to type `make` and get some MIPS binaries out. You can edit the *Makefile* if you need to change the tool names or paths.
## Running
The Hello World program:
```
qemu-mips ./hello
```
The True/False programs
```
qemu-mips ./true ; echo $?
qemu-mips ./false; echo $?
```
## Contributing
Send a pull request via Github.com, or send e-mails containing patches.
<file_sep>/* false - implementation of /bin/false - public domain. */
int main(void)
{
return 1;
}
<file_sep>/* true - implementation of /bin/true - public domain. */
int main(void)
{
return 0;
}
<file_sep>/* hello - a hello world program - public domain. */
#include <stdio.h>
int main(void)
{
puts("Hello World");
}
| 8132506a5426043d1c06bc7aaea99776198a1815 | [
"Markdown",
"C",
"Makefile"
] | 6 | Makefile | OrangeTide/mips-tutorial | 959a022ad87ce8a9cafd115e7b9421bf10b133bb | e2cc34966d6c3bf91724603b2c94d2f2a3f9ae7a |
refs/heads/main | <repo_name>Arun-George-Zachariah/AMIDST-SRLearn<file_sep>/src/main/java/edu/missouri/constants/Constants.java
package edu.missouri.constants;
public class Constants {
public static final String CSV_EXTENSION = "csv";
public static final String ARFF_EXTENSION = "arff";
public static final String JSON_EXTENSION = "json";
public static final String DOT = ".";
public static final String APP_NAME = "AMIDST-SRLearn";
public static final String MASTER = "local";
public static final int BATCH_SIZE = 100;
}
<file_sep>/src/main/java/edu/missouri/LearnBayesianNetwork.java
package edu.missouri;
import edu.missouri.constants.Constants;
import edu.missouri.util.CSV2Arff;
import eu.amidst.core.datastream.DataInstance;
import eu.amidst.core.datastream.DataStream;
import eu.amidst.core.io.DataStreamLoader;
import eu.amidst.core.learning.parametric.ParallelMaximumLikelihood;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.variables.Variable;
import eu.amidst.core.variables.Variables;
public class LearnBayesianNetwork {
public static DAG getNaiveBayesStructure(DataStream<DataInstance> dataStream, int classIndex){
// Creating a Variables object from the attributes of the data stream
Variables modelHeader = new Variables(dataStream.getAttributes());
// Define the predictive class variable
Variable classVar = modelHeader.getVariableById(classIndex);
// Creating a DAG object with the defined model header
DAG dag = new DAG(modelHeader);
//We set the links of the DAG.
dag.getParentSets().stream().filter(w -> w.getMainVar() != classVar).forEach(w -> w.addParent(classVar));
return dag;
}
public static void main(String[] args) throws Exception {
if(args.length != 1) {
System.out.println("edu.missouri.LearnBayesianNetwork <INPUT>");
System.exit(-1);
}
// Obtaining the input file.
String input = args[0];
// If the input is a CSV, we convert it to as ARFF.
String[] fileSplits = input.split("\\.");
if(fileSplits[fileSplits.length-1].equals(Constants.CSV_EXTENSION)) {
input = CSV2Arff.getInstance().convertCSV2Arff(input);
}
// Validating the conversion.
if(input == null) {
System.out.println("LearnBayesianNetwork :: main :: Invalid input provided.");
System.exit(-1);
}
// Opening the data stream.
DataStream<DataInstance> data = DataStreamLoader.open(input);
// Creating a ParallelMaximumLikelihood object.
ParallelMaximumLikelihood parameterLearningAlgorithm = new ParallelMaximumLikelihood();
// Activating parallel mode.
parameterLearningAlgorithm.setParallelMode(true);
// Deactivating debug mode.
parameterLearningAlgorithm.setDebug(false);
// Fixing the DAG structure.
parameterLearningAlgorithm.setDAG(getNaiveBayesStructure(data, 0));
// Setting the batch size which will be employed to learn the model in parallel.
parameterLearningAlgorithm.setWindowsSize(100);
// Setting the data to be used for leaning the parameters.
parameterLearningAlgorithm.setDataStream(data);
// Performing the learning.
parameterLearningAlgorithm.runLearning();
// Obtaining the model.
BayesianNetwork bnModel = parameterLearningAlgorithm.getLearntBayesianNetwork();
System.out.println(bnModel.toString());
}
}
| 2317e9dd0c781d69e7c008fab0137c62d7a5bf53 | [
"Java"
] | 2 | Java | Arun-George-Zachariah/AMIDST-SRLearn | 039e78d28edc4a8a94a196ed66092502d2899bea | 2fb29fb36870ebbc3ef1128c8de88e7a7386a93d |
refs/heads/master | <file_sep>let angleJaw = 2;
let bamYes = false;
var x = 1
let bone1;
let bone2;
let bone3;
let bone4;
function setup() {
createCanvas(400, 400);
angleMode(DEGREES);
//mic = new p5.AudioIn()
//mic.start();
bone1 = new Bone(width * .7, height * .8, 10, .3);
bone2 = new Bone(width * .3, height * .4, 10, 2);
bone3 = new Bone(width * .5, height * .3, 8, .4);
bone4 = new Bone(width * .8, height * .2, 10, 2);
}
function draw() {
//console.log("mic level " + mic.getLevel());
//console.log("mouse y is: " + mouseY);
//micLevel = mic.getLevel();
//angleBoneWag = map(mic.getLevel(), 4, 4, 400, 400);
background(0, 0, 0);
bone1.display();
bone2.display();
bone3.display();
bone4.display();
bone1.move();
bone2.move();
bone3.move();
bone4.move();
//right bone
//drawBone(micLevel * 200, width * .7, height * .8);
//left bone
//drawBone(micLevel * 200, width * .3, height * .4);
//drawBone(x, width * .5, height * .8, 50);
x = x + 3;
if (x >= height) {
x = 0;
}
drawSkullHead();
drawLeftEye();
drawLeftPupil();
drawRightEye();
drawRightPupil();
drawBottomJaw(angleJaw);
drawNose();
if (bamYes == true) {
circle(width / 2, height / 2.100);
}
//rect(width * .4, height * .05, width * .4, height * .3);
}
function mousePressed() {
// if the postion of the mouse in inside this region then do this
if (mouseX > width * 0.4 && mouseX < width * 0.8 && mouseY > height * 0.05 && mouseY < height * .35) {
console.log("lock jaw");
angleJaw = -angleJaw;
} else if (mouseX < width * .4 || mouseX > width * .8) {
bamYes = !bamYes;
console.log("chew");
}
}
function drawSkullHead() {
//top skull
//skull color
fill(246, 240, 88);
noStroke();
beginShape();
vertex(width * .4, height * .2);
vertex(width * .45, height * .05);
vertex(width * .7, height * .05);
vertex(width * .75, height * .2);
vertex(width * .7, height * .3);
vertex(width * .7, height * .4);
vertex(width * .65, height * .4);
vertex(width * .65, height * .3);
vertex(width * .60, height * .3);
vertex(width * .60, height * .4);
vertex(width * .55, height * .4);
vertex(width * .55, height * .3);
vertex(width * .5, height * .3);
vertex(width * .5, height * .4);
vertex(width * .45, height * .4);
vertex(width * .45, height * .3);
endShape(CLOSE);
}
function drawBottomJaw(rotation) {
//bottom jaw
//skull color
push();
rotate(rotation);
fill(246, 240, 88);
noStroke();
beginShape();
vertex(width * .5, height * .55);
vertex(width * .5, height * .6);
vertex(width * .7, height * .6);
vertex(width * .7, height * .5);
vertex(width * .65, height * .5);
vertex(width * .65, height * .55);
vertex(width * .6, height * .55);
vertex(width * .6, height * .5);
vertex(width * .55, height * .5);
vertex(width * .55, height * .55);
endShape(CLOSE);
pop();
}
function drawLeftEye() {
//draw left eye
fill(255, 0, 0);
noStroke();
circle(width * .5, width * .2, width * .07);
}
function drawLeftPupil() {
//draw left pupil
fill(20);
circle(width * .51, width * .2, width * .03);
}
function drawRightEye() {
//draw right eye
fill(255, 0, 0);
noStroke();
circle(width * .65, width * .2, width * .07);
}
function drawRightPupil() {
//draw right pupil
fill(20);
circle(width * .66, width * .2, width * .03);
}
function drawNose() {
//draw nose
fill(20);
triangle(235, 90, 250, 110, 220, 110);
} | 5be6d26ef0bc8ebc526de52cdf9c3d955cfdb574 | [
"JavaScript"
] | 1 | JavaScript | lybrandon/hungry-skull | d7bc1f7290dfd67a990967380b5ffe02febdffe9 | 5b1e39bc7597ca7ba655ed41c52743b413b15fdb |
refs/heads/master | <file_sep>#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//LEVEL50, a text-based command-line pokemon battle simulator written entirely in C
//By <NAME>
//cs50 final project
//https://github.com/BRYSONCARTER/level50
//UPDATES:
//i think i have recoil and absorb hp worked out. see fight() and deplete() and their foeforms
//pretty sure speed and priority check works now
//pretty sure major status infliction and retention works now
//u can type in lowercase letters now lol
//u can check ur party stats and moves and hp
//implemented status checks at beginning of fight and foe fight. if paralyzed, roll. if confused, roll. if asleep, roll. if flinched, roll
//all moves added (that i want to add)
//all fully-evolved pokemon added (minus ditto plus pikachu)
//pretty sure all end of turn checks are in place
//pretty sure status solution (awake, unconfuse, unfreeze) works using fight()
//p sure secondary effects of attacking moves all work now. flinching, status, etc. test each status on both sides befopre u rolll out tho
//stat mods work in damage foprmulas
//speed ties work now
//alll mons have thier moves
//pretty sure status moves work now, test them for bugs tho
//ai doesnt attack twice
//hp uses global pointer system
//speed checks use global pointer system
//speed mods work, agility works,
//u can request mons by name now B) hecc ya
//p sure i fixed the toxic/burn not killing and the extra switching and fainting
//first, struct and array definitions------------------------------------------------------------------------------------------------------------------------------------------------------------------
//this is the struct for one move. ------------------------------------------------------------------------------------------------------------------
struct move{
string name;
int basepower;
int acc;
string type;
int typeint;
string effect; //poison burn etc. will have an effect function with a bunch of "if string == flinch, then set foe's flinch counter to 1, if string == burn, then burn them" also wrap goes here
int effectchance;
int effectint;
int priority;
int physicalorspecial; //0 is physical, 1 is special
int attackorstatus; //0 is attacking move, 1 is a status/non-attacking move
int recoilordrain; //0 is none, -1 is 1/8 recoil, +1 is 1/8 drain, +4 is 4/8 drain
int hitcount; //1 for most moves, 2 for double kick, 5 for fury attack
int target; // 0 for other mon, 1 for self target
};
//we will reference moves by their index in the movedex array
struct move movedex[100];
struct move moveset[4]; //when we send in a pokemon, we write their moveset to this array. that way we can reference them as moveset[n]
struct move foemoveset[4];
//this is the struct for one pokedex entry. contains data shared by all members of a species---------------------------------------------------------
struct dex{
string name;
int baseatk;
int basedef;
int basespatk;
int basespdef;
int basespeed;
int basehp;
int growthmod;
int expyield;
int evolveat;
int evolveto;
string type1;
string type2;
int typeint1; //you will notice type integers throughout. why? because passing strings around in c is a FUCKING NIGHTMARE lmao, much easier to pass integers around
int typeint2;
struct move move1;
struct move move2;
struct move move3;
struct move move4;
};
//we will reference dex structs as part of the pokedex[151] array
struct dex pokedex[151];
//this contains the information for one individual pokemon-------------------------------------------------------------------------------------------
struct pokemon{
int dexno; //pokedex[dexno] contains the species info
string nickname;
string name;
int xp;
int growthmod;
int lvl;
int atk;
int def;
int maxhp;
int currenthp;
int spatk;
int spdef;
int speed;
string type1;
string type2;
int typeint1;
int typeint2;
int statusint; //0 for healthy 1 burn 2 freeze 3 sleep 4 poison 5 paralyze 6 fainted
int *statusintpointer;
string status; //make this a function of statusint
struct move move1;
struct move move2;
struct move move3;
struct move move4;
};
//we will reference individuals by their index number in either party or foeparty. change to 6 for final version?
struct pokemon party[3];
struct pokemon foeparty[3];
//probably won't end up using this. hypothetical storage for mons for many different trainers
struct pokemon trainermons[360];
//probably won't use this either. in overworld, this would be pc pokemon storage
struct pokemon box[100];
//this contains stat mods and stuff for the pokemon currently in battle------------------------------------------------------------------------------
struct combatmon{
int dexnumber; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
string nickname;
struct pokemon individualdata; //derive all stats from relevant indivual's struct. can access pokedex struct through indiv struct as well.
int atkmod; // combatants[0].hp = combatants[0].individualdata.currenthp
int defmod; //combatants[0].type1 = pokedex[ dexnumber ].type1
int spatkmod;
int spdefmod;
int speedmod;
int evasionmod;
int accuracymod;
int critmod;
int protectcounter;
string status;
int statusint; //0 for healthy 1 burn 2 freeze 3 sleep 4 poison 5 paralyze 6 fainted
int confused;
int disabled;
int disabledmove; //1 thru 4, denotes which move in a moveset it disabled
int toxiccounter; //0 if no toxic,
int leechseeded;
int flinched;
int substitute;
int substitutehp;
string hyperskyskull; //if this is hyperbeam, cant move. if this is sky attack or skull bash, cant move. same with dig and fly
int invulnerable; //protect, fly, dig
int caughtinwrap; //if theyre being wrapped or fire spun. subtract 1/16 hp and print "user is caught in foe's attack!"
int cursed;
int biding; //0 if not biding, 1 if biding
int bidedamagetracker; // if pokemon is biding, track damage it recieves
int countering;
int counterdamagetracker;
int thrashcounter; //set to 2 or 3 when poke uses thrash or petal dance. decrease each turn. when it hits 0, confuse the user
int whichpartymemberami; //set to 0, 1 or 2 so we can do &party[whichpartymemberami].currenthp
};
//we will reference active combatants as either index 0 or 1 in the combatants array
struct combatmon combatants[2];
//below are effects that stay on the field even if we switch pokemon
struct fieldeffects{
int reflect;
int lightscreen;
int safeguard;
int mist;
int lastmoveused; //for mirror move. the int will n for be movedex[n]
};
//0 is our side, 1 is their side. no weather 1st gen lol
struct fieldeffects field[2];
//the below struct should be used as a container for move info after user and ai are queried for moves. then speed check will look at priority and speed to see whether fight or foefight goes first
struct moveselection{
struct move movechoice;
int STAB;
struct combatmon attacker;
struct combatmon defender;
};
//0 is our side, 1 is their side
struct moveselection bothmoves[2];
int typechart[18][18]; //contains type matchups
//here are a couple toggles.
int isover = 0; //if this is 0, the battle doesnt end. if this is 1, the battle ends.
int *isoverpointer = &isover; //make a pointer so we can change this from anywhere
int run = 0;
int *runpointer = &run; //same deal but with E to ESCAPE
int didfoejustfaint = 0; //0 if no 1 if yes. this is so that opponent doesnt get a free turn after getting kod
int *foefaint = &didfoejustfaint;
int diduserjustfaint = 0;
int *userfaint = &diduserjustfaint;
int userswitch = 0;
int *userswitchpointer = &userswitch;
int combatcurrenthp = 1;
int *combathppointer = &combatcurrenthp;
int foecombatcurrenthp = 1;
int *foecombathppointer = &foecombatcurrenthp;
int combatspeed = 1;
int *combatspeedpointer = &combatspeed;
int foecombatspeed = 1;
int *foecombatspeedpointer = &foecombatspeed;
int loopcount = 0;
int *loopcountpointer = &loopcount;
int urmon1;
int urmon2;
int urmon3;
int *urmon1ptr = &urmon1;
int *urmon2ptr = &urmon2;
int *urmon3ptr = &urmon3;
int theirmon1;
int theirmon2;
int theirmon3;
int *theirmon1ptr = &theirmon1;
int *theirmon2ptr = &theirmon2;
int *theirmon3ptr = &theirmon3;
//then, function declarations go here ----------------------------------------------------------------------------------------------------------------------------------------------------------------
int query(string option, struct combatmon ourfighter); //gee why do u have dual functions for self and foe?
int foequery(struct combatmon theirfighter); // because hp pointers
int fight(struct move moveused, int STAB, struct combatmon attacker, struct combatmon defender);
int foefight(struct move moveused, int STAB, struct combatmon attacker, struct combatmon defender);
int attack(struct combatmon attacker, struct combatmon defender, struct move movestruct, int STAB);
int foeattack(struct combatmon attacker, struct combatmon defender, struct move movestruct, int STAB);
int deplete(int *hppoint, int damage, struct pokemon victim);
int foedeplete(int *hppoint, int damage, struct pokemon victim);
float speedchange(int statmod, int statusint); //factors in paralysis
float attackchange(int atkmod, int statusint); //factors in burn
float statchange(int statmod); //use for all other stats
string statinttostring(int g);
void userselection1(void);
void userselection2(void);
void userselection3(void);
void foeselection1(void);
void foeselection2(void);
void foeselection3(void);
//now, main function-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void)
{
//seed rng
srand( time(NULL) );
printf("\n\n LEVEL50\nA Pokemon battle simulator written entirely in C\n --cs50 Final Project--\n --<NAME> 2020--\n\n\n\n");
//first initialize movedex--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//we do this first because the pokemon structs have moves in them so we gotta initialize these b4 those
movedex[0].name = "Tackle";
movedex[0].basepower = 40;
movedex[0].acc = 95;
movedex[0].type = "Normal";
movedex[0].typeint = 1;
movedex[0].effect = "None"; //poison burn etc. will have an effect function with a bunch of "if string == flinch, then set foe's flinch counter to 1, if string == burn, then burn them"
movedex[0].effectchance = 0;
movedex[0].priority = 0;
movedex[0].attackorstatus = 0;
movedex[0].physicalorspecial = 0;
movedex[0].recoilordrain = 0;
movedex[0].hitcount = 1;
movedex[0].target = 0;
movedex[1].name = "<NAME>";
movedex[1].basepower = 40;
movedex[1].acc = 95;
movedex[1].type = "Grass";
movedex[1].typeint = 5;
movedex[1].effect = "None";
movedex[1].effectchance = 0;
movedex[1].priority = 0;
movedex[1].attackorstatus = 0;
movedex[1].physicalorspecial = 0;
movedex[1].recoilordrain = 0;
movedex[1].hitcount = 1;
movedex[1].target = 0;
movedex[2].name = "Ember";
movedex[2].basepower = 40;
movedex[2].acc = 95;
movedex[2].type = "Fire";
movedex[2].typeint = 2;
movedex[2].effect = "Burn";
movedex[2].effectint = 1; //ok so i have effectint here but i might just use strcmp its not that much different
movedex[2].effectchance = 100;
movedex[2].priority = 0;
movedex[2].attackorstatus = 0;
movedex[2].physicalorspecial = 1;
movedex[2].recoilordrain = 0;
movedex[2].hitcount = 1;
movedex[2].target = 0;
movedex[3].name = "<NAME>";
movedex[3].basepower = 40;
movedex[3].acc = 95;
movedex[3].type = "Water";
movedex[3].typeint = 3;
movedex[3].effect = "None";
movedex[3].effectchance = 0;
movedex[3].priority = 0;
movedex[3].attackorstatus = 0;
movedex[3].physicalorspecial = 1;
movedex[3].recoilordrain = 0;
movedex[3].hitcount = 1;
movedex[3].target = 0;
movedex[4].name = "Absorb";
movedex[4].basepower = 40;
movedex[4].acc = 100;
movedex[4].type = "Grass";
movedex[4].typeint = 5;
movedex[4].effect = "None";
movedex[4].effectchance = 0;
movedex[4].priority = 0;
movedex[4].attackorstatus = 0;
movedex[4].physicalorspecial = 1;
movedex[4].recoilordrain = 4;
movedex[4].hitcount = 1;
movedex[4].target = 0;
movedex[5].name = "Acid";
movedex[5].basepower = 40;
movedex[5].acc = 100;
movedex[5].type = "Poison";
movedex[5].typeint = 8;
movedex[5].effect = "-def"; //i might actually just string compare for the effect
movedex[5].effectchance = 10; ///like a bunch of if strcmp(movedex[5].effect, "-def") == 0) then do this
movedex[5].priority = 0;
movedex[5].attackorstatus = 0;
movedex[5].physicalorspecial = 1;
movedex[5].recoilordrain = 0;
movedex[5].hitcount = 1;
movedex[5].target = 0;
movedex[6].name = "<NAME>";
movedex[6].basepower = 0;
movedex[6].acc = 100;
movedex[6].type = "Poison";
movedex[6].typeint = 8;
movedex[6].effect = "+2def";
movedex[6].effectchance = 100;
movedex[6].priority = 0;
movedex[6].attackorstatus = 1;
movedex[6].physicalorspecial = 1;
movedex[6].recoilordrain = 0;
movedex[6].hitcount = 1;
movedex[6].target = 1;
movedex[7].name = "Agility";
movedex[7].basepower = 0;
movedex[7].acc = 100;
movedex[7].type = "Normal";
movedex[7].typeint = 1;
movedex[7].effect = "+2speed";
movedex[7].effectchance = 100;
movedex[7].priority = 0;
movedex[7].attackorstatus = 1;
movedex[7].physicalorspecial = 1;
movedex[7].recoilordrain = 0;
movedex[7].hitcount = 1;
movedex[7].target = 1;
movedex[8].name = "Amnesia";
movedex[8].basepower = 0;
movedex[8].acc = 100;
movedex[8].type = "Psychic";
movedex[8].typeint = 11;
movedex[8].effect = "+2spdef";
movedex[8].effectchance = 100;
movedex[8].priority = 0;
movedex[8].attackorstatus = 1;
movedex[8].physicalorspecial = 1;
movedex[8].recoilordrain = 4;
movedex[8].hitcount = 1;
movedex[8].target = 1;
movedex[9].name = "<NAME>";
movedex[9].basepower = 65;
movedex[9].acc = 100;
movedex[9].type = "Ice";
movedex[9].typeint = 6;
movedex[9].effect = "-atk";
movedex[9].effectchance = 10;
movedex[9].priority = 0;
movedex[9].attackorstatus = 0;
movedex[9].physicalorspecial = 1;
movedex[9].recoilordrain = 0;
movedex[9].hitcount = 1;
movedex[9].target = 0;
movedex[10].name = "Barrage";
movedex[10].basepower = 15;
movedex[10].acc = 85;
movedex[10].type = "Normal";
movedex[10].typeint = 1;
movedex[10].effect = "None";
movedex[10].effectchance = 0;
movedex[10].priority = 0;
movedex[10].attackorstatus = 0;
movedex[10].physicalorspecial = 0;
movedex[10].recoilordrain = 0;
movedex[10].hitcount = 5;
movedex[10].target = 0;
movedex[11].name = "Barrier";
movedex[11].basepower = 0;
movedex[11].acc = 100;
movedex[11].type = "Psychic";
movedex[11].typeint = 11;
movedex[11].effect = "+2def";
movedex[11].effectchance = 100;
movedex[11].priority = 0;
movedex[11].attackorstatus = 1;
movedex[11].physicalorspecial = 1;
movedex[11].recoilordrain = 0;
movedex[11].hitcount = 1;
movedex[11].target = 1;
movedex[12].name = "Bide";
movedex[13].name = "Bind";
movedex[14].name = "Bite";
movedex[14].basepower = 60;
movedex[14].acc = 100;
movedex[14].type = "Dark";
movedex[14].typeint = 16;
movedex[14].effect = "Flinch";
movedex[14].effectchance = 30;
movedex[14].priority = 0;
movedex[14].attackorstatus = 0;
movedex[14].physicalorspecial = 0;
movedex[14].recoilordrain = 0;
movedex[14].hitcount = 1;
movedex[14].target = 0;
movedex[15].name = "Blizzard";
movedex[15].basepower = 120;
movedex[15].acc = 70;
movedex[15].type = "Ice";
movedex[15].typeint = 6;
movedex[15].effect = "Freeze";
movedex[15].effectchance = 10;
movedex[15].priority = 0;
movedex[15].attackorstatus = 0;
movedex[15].physicalorspecial = 1;
movedex[15].recoilordrain = 0;
movedex[15].hitcount = 1;
movedex[15].target = 0;
movedex[16].name = "<NAME>";
movedex[16].basepower = 85;
movedex[16].acc = 100;
movedex[16].type = "Normal";
movedex[16].typeint = 1;
movedex[16].effect = "Paralyze";
movedex[16].effectchance = 30;
movedex[16].priority = 0;
movedex[16].attackorstatus = 0;
movedex[16].physicalorspecial = 0;
movedex[16].recoilordrain = 0;
movedex[16].hitcount = 1;
movedex[16].target = 0;
movedex[17].name = "<NAME>";
movedex[17].basepower = 65;
movedex[17].acc = 85;
movedex[17].type = "Ground";
movedex[17].typeint = 9;
movedex[17].effect = "Flinch";
movedex[17].effectchance = 10;
movedex[17].priority = 0;
movedex[17].attackorstatus = 0;
movedex[17].physicalorspecial = 0;
movedex[17].recoilordrain = 0;
movedex[17].hitcount = 1;
movedex[18].name = "Bonemarang";
movedex[18].basepower = 50;
movedex[18].acc = 90;
movedex[18].type = "Ground";
movedex[18].typeint = 9;
movedex[18].effect = "None";
movedex[18].effectchance = 0;
movedex[18].priority = 0;
movedex[18].attackorstatus = 0;
movedex[18].physicalorspecial = 0;
movedex[18].recoilordrain = 0;
movedex[18].hitcount = 2;
movedex[18].target = 0;
movedex[19].name = "<NAME>";
movedex[19].basepower = 0;
movedex[19].acc = 100;
movedex[19].type = "Ghost";
movedex[19].typeint = 14;
movedex[19].effect = "Confuse";
movedex[19].effectchance = 100;
movedex[19].priority = 0;
movedex[19].attackorstatus = 1;
movedex[19].physicalorspecial = 1;
movedex[19].recoilordrain = 0;
movedex[19].hitcount = 1;
movedex[19].target = 0;
movedex[20].name = "Counter";
movedex[20].basepower = 0;
movedex[20].acc = 100;
movedex[20].type = "Fighting";
movedex[20].typeint = 7;
movedex[20].effect = "Counter";
movedex[20].effectchance = 100;
movedex[20].priority = -5;
movedex[20].attackorstatus = 1;
movedex[20].physicalorspecial = 0;
movedex[20].recoilordrain = 0;
movedex[20].hitcount = 1;
movedex[20].target = 0;
movedex[21].name = "Crabhammer";
movedex[21].basepower = 100;
movedex[21].acc = 90;
movedex[21].type = "Water";
movedex[21].typeint = 3;
movedex[21].effect = "Crit";
movedex[21].effectchance = 6;
movedex[21].priority = 0;
movedex[21].attackorstatus = 0;
movedex[21].physicalorspecial = 0;
movedex[21].recoilordrain = 0;
movedex[21].hitcount = 1;
movedex[21].target = 0;
movedex[22].name = "Disable";
movedex[22].basepower = 0;
movedex[22].acc = 100;
movedex[22].type = "Normal";
movedex[22].typeint = 1;
movedex[22].effect = "Disable";
movedex[22].effectchance = 100;
movedex[22].priority = 0;
movedex[22].attackorstatus = 1;
movedex[22].physicalorspecial = 1;
movedex[22].recoilordrain = 0;
movedex[22].hitcount = 1;
movedex[22].target = 0;
movedex[23].name = "<NAME>";
movedex[23].basepower = 30;
movedex[23].acc = 100;
movedex[23].type = "Fighting";
movedex[23].typeint = 7;
movedex[23].effect = "None";
movedex[23].effectchance = 0;
movedex[23].priority = 0;
movedex[23].attackorstatus = 0;
movedex[23].physicalorspecial = 0;
movedex[23].recoilordrain = 0;
movedex[23].hitcount = 2;
movedex[23].target = 0;
movedex[24].name = "<NAME>";
movedex[24].basepower = 0;
movedex[24].acc = 100;
movedex[24].type = "Normal";
movedex[24].typeint = 1;
movedex[24].effect = "+1eva";
movedex[24].effectchance = 100;
movedex[24].priority = 0;
movedex[24].attackorstatus = 1;
movedex[24].physicalorspecial = 1;
movedex[24].recoilordrain = 0;
movedex[24].hitcount = 1;
movedex[24].target = 1;
movedex[25].name = "<NAME>";
movedex[25].basepower = 120;
movedex[25].acc = 100;
movedex[25].type = "Normal";
movedex[25].typeint = 1;
movedex[25].effect = "None";
movedex[25].effectchance = 0;
movedex[25].priority = 0;
movedex[25].attackorstatus = 0;
movedex[25].physicalorspecial = 0;
movedex[25].recoilordrain = -2;
movedex[25].hitcount = 1;
movedex[25].target = 0;
movedex[26].name = "Flamethrower"; //
movedex[26].basepower = 95;
movedex[26].acc = 100;
movedex[26].type = "Fire";
movedex[26].typeint = 2;
movedex[26].effect = "Burn";
movedex[26].effectchance = 10;
movedex[26].priority = 0;
movedex[26].attackorstatus = 0;
movedex[26].physicalorspecial = 1;
movedex[26].recoilordrain = 0;
movedex[26].hitcount = 1;
movedex[26].target = 0;
movedex[27].name = "Surf";
movedex[27].basepower = 95;
movedex[27].acc = 100;
movedex[27].type = "Water";
movedex[27].typeint = 3;
movedex[27].effect = "None";
movedex[27].effectchance = 0;
movedex[27].priority = 0;
movedex[27].attackorstatus = 0;
movedex[27].physicalorspecial = 1;
movedex[27].recoilordrain = 0;
movedex[27].hitcount = 1;
movedex[27].target = 0;
movedex[28].name = "<NAME>";
movedex[28].basepower = 75;
movedex[28].acc = 100;
movedex[28].type = "Grass";
movedex[28].typeint = 5;
movedex[28].effect = "None";
movedex[28].effectchance = 0;
movedex[28].priority = 0;
movedex[28].attackorstatus = 0;
movedex[28].physicalorspecial = 1;
movedex[28].recoilordrain = 4;
movedex[28].hitcount = 1;
movedex[28].target = 0;
movedex[29].name = "<NAME>";
movedex[29].basepower = 90;
movedex[29].acc = 100;
movedex[29].type = "Poison";
movedex[29].typeint = 8;
movedex[29].effect = "Poison";
movedex[29].effectchance = 10;
movedex[29].priority = 0;
movedex[29].attackorstatus = 0;
movedex[29].physicalorspecial = 1;
movedex[29].recoilordrain = 0;
movedex[29].hitcount = 1;
movedex[29].target = 0;
movedex[30].name = "Earthquake";
movedex[30].basepower = 100;
movedex[30].acc = 100;
movedex[30].type = "Ground";
movedex[30].typeint = 9;
movedex[30].effect = "None";
movedex[30].effectchance = 0;
movedex[30].priority = 0;
movedex[30].attackorstatus = 0;
movedex[30].physicalorspecial = 0;
movedex[30].recoilordrain = 0;
movedex[30].hitcount = 1;
movedex[30].target = 0;
movedex[31].name = "Toxic";
movedex[31].basepower = 0;
movedex[31].acc = 90;
movedex[31].type = "Poison";
movedex[31].typeint = 8;
movedex[31].effect = "Toxic";
movedex[31].effectchance = 100;
movedex[31].priority = 0;
movedex[31].attackorstatus = 1;
movedex[31].physicalorspecial = 1;
movedex[31].recoilordrain = 0;
movedex[31].hitcount = 1;
movedex[31].target = 0;
movedex[32].name = "Air Slash";
movedex[32].basepower = 75;
movedex[32].acc = 95;
movedex[32].type = "Flying";
movedex[32].typeint = 10;
movedex[32].effect = "Flinch";
movedex[32].effectchance = 30;
movedex[32].priority = 0;
movedex[32].attackorstatus = 0;
movedex[32].physicalorspecial = 1;
movedex[32].recoilordrain = 0;
movedex[32].hitcount = 1;
movedex[32].target = 0;
movedex[33].name = "Fire Blast";
movedex[33].basepower = 120;
movedex[33].acc = 85;
movedex[33].type = "Fire";
movedex[33].typeint = 2;
movedex[33].effect = "Burn";
movedex[33].effectchance = 10;
movedex[33].priority = 0;
movedex[33].attackorstatus = 0;
movedex[33].physicalorspecial = 1;
movedex[33].recoilordrain = 0;
movedex[33].hitcount = 1;
movedex[33].target = 0;
movedex[34].name = "Ice Beam";
movedex[34].basepower = 95;
movedex[34].acc = 100;
movedex[34].type = "Ice";
movedex[34].typeint = 6;
movedex[34].effect = "Freeze";
movedex[34].effectchance = 10;
movedex[34].priority = 0;
movedex[34].attackorstatus = 0;
movedex[34].physicalorspecial = 1;
movedex[34].recoilordrain = 0;
movedex[34].hitcount = 1;
movedex[34].target = 0;
movedex[35].name = "Bug Buzz";
movedex[35].basepower = 90;
movedex[35].acc = 100;
movedex[35].type = "Bug";
movedex[35].typeint = 12;
movedex[35].effect = "-spdef";
movedex[35].effectchance = 10;
movedex[35].priority = 0;
movedex[35].attackorstatus = 0;
movedex[35].physicalorspecial = 1;
movedex[35].recoilordrain = 0;
movedex[35].hitcount = 1;
movedex[35].target = 0;
movedex[36].name = "Psychic";
movedex[36].basepower = 90;
movedex[36].acc = 100;
movedex[36].type = "Psychic";
movedex[36].typeint = 11;
movedex[36].effect = "-spdef";
movedex[36].effectchance = 10;
movedex[36].priority = 0;
movedex[36].attackorstatus = 0;
movedex[36].physicalorspecial = 1;
movedex[36].recoilordrain = 0;
movedex[36].hitcount = 1;
movedex[36].target = 0;
movedex[37].name = "<NAME>";
movedex[37].basepower = 0;
movedex[37].acc = 75;
movedex[37].type = "Grass";
movedex[37].typeint = 5;
movedex[37].effect = "Sleep";
movedex[37].effectchance = 100;
movedex[37].priority = 0;
movedex[37].attackorstatus = 1;
movedex[37].physicalorspecial = 1;
movedex[37].recoilordrain = 0;
movedex[37].hitcount = 1;
movedex[37].target = 0;
movedex[38].name = "Poisonpowder";
movedex[38].basepower = 0;
movedex[38].acc = 75;
movedex[38].type = "Grass";
movedex[38].typeint = 5;
movedex[38].effect = "Poison";
movedex[38].effectchance = 100;
movedex[38].priority = 0;
movedex[38].attackorstatus = 1;
movedex[38].physicalorspecial = 1;
movedex[38].recoilordrain = 0;
movedex[38].hitcount = 1;
movedex[38].target = 0;
movedex[39].name = "<NAME>";
movedex[39].basepower = 80;
movedex[39].acc = 100;
movedex[39].type = "Poison";
movedex[39].typeint = 8;
movedex[39].effect = "Poison";
movedex[39].effectchance = 30;
movedex[39].priority = 0;
movedex[39].attackorstatus = 0;
movedex[39].physicalorspecial = 0;
movedex[39].recoilordrain = 0;
movedex[39].hitcount = 1;
movedex[39].target = 0;
movedex[40].name = "X-Scissor";
movedex[40].basepower = 80;
movedex[40].acc = 100;
movedex[40].type = "Bug";
movedex[40].typeint = 12;
movedex[40].effect = "None";
movedex[40].effectchance = 0;
movedex[40].priority = 0;
movedex[40].attackorstatus = 0;
movedex[40].physicalorspecial = 0;
movedex[40].recoilordrain = 0;
movedex[40].hitcount = 1;
movedex[40].target = 0;
movedex[41].name = "Quick Attack";
movedex[41].basepower = 40;
movedex[41].acc = 100;
movedex[41].type = "Normal";
movedex[41].typeint = 1;
movedex[41].effect = "None";
movedex[41].effectchance = 0;
movedex[41].priority = 1;
movedex[41].attackorstatus = 0;
movedex[41].physicalorspecial = 0;
movedex[41].recoilordrain = 0;
movedex[41].hitcount = 1;
movedex[41].target = 0;
movedex[42].name = "Roost";
movedex[42].basepower = 0;
movedex[42].acc = 100;
movedex[42].type = "Flying";
movedex[42].typeint = 10;
movedex[42].effect = "Restore";
movedex[42].effectchance = 100;
movedex[42].priority = 0;
movedex[42].attackorstatus = 1;
movedex[42].physicalorspecial = 1;
movedex[42].recoilordrain = 0;
movedex[42].hitcount = 1;
movedex[42].target = 0;
movedex[43].name = "Thunderbolt";
movedex[43].basepower = 95;
movedex[43].acc = 100;
movedex[43].type = "Electric";
movedex[43].typeint = 4;
movedex[43].effect = "Paralyze";
movedex[43].effectchance = 10;
movedex[43].priority = 0;
movedex[43].attackorstatus = 0;
movedex[43].physicalorspecial = 1;
movedex[43].recoilordrain = 0;
movedex[43].hitcount = 1;
movedex[43].target = 0;
movedex[44].name = "Thunderwave";
movedex[44].basepower = 0;
movedex[44].acc = 100;
movedex[44].type = "Electric";
movedex[44].typeint = 5;
movedex[44].effect = "Paralyze";
movedex[44].effectchance = 100;
movedex[44].priority = 0;
movedex[44].attackorstatus = 1;
movedex[44].physicalorspecial = 1;
movedex[44].recoilordrain = 0;
movedex[44].hitcount = 1;
movedex[44].target = 0;
movedex[45].name = "<NAME>";
movedex[45].basepower = 80;
movedex[45].acc = 100;
movedex[45].type = "Flying";
movedex[45].typeint = 10;
movedex[45].effect = "None";
movedex[45].effectchance = 0;
movedex[45].priority = 0;
movedex[45].attackorstatus = 0;
movedex[45].physicalorspecial = 0;
movedex[45].recoilordrain = 0;
movedex[45].hitcount = 1;
movedex[45].target = 0;
movedex[46].name = "Agility";
movedex[46].basepower = 0;
movedex[46].acc = 100;
movedex[46].type = "Psychic";
movedex[46].typeint = 11;
movedex[46].effect = "+2speed";
movedex[46].effectchance = 100;
movedex[46].priority = 0;
movedex[46].attackorstatus = 1;
movedex[46].physicalorspecial = 1;
movedex[46].recoilordrain = 0;
movedex[46].hitcount = 1;
movedex[46].target = 1;
movedex[47].name = "Crunch";
movedex[47].basepower = 80;
movedex[47].acc = 100;
movedex[47].type = "Dark";
movedex[47].typeint = 16;
movedex[47].effect = "-def";
movedex[47].effectchance = 20;
movedex[47].priority = 0;
movedex[47].attackorstatus = 0;
movedex[47].physicalorspecial = 0;
movedex[47].recoilordrain = 0;
movedex[47].hitcount = 1;
movedex[47].target = 0;
movedex[48].name = "Thunder";
movedex[48].basepower = 120;
movedex[48].acc = 70;
movedex[48].type = "Electric";
movedex[48].typeint = 4;
movedex[48].effect = "Paralyze";
movedex[48].effectchance = 30;
movedex[48].priority = 0;
movedex[48].attackorstatus = 0;
movedex[48].physicalorspecial = 1;
movedex[48].recoilordrain = 0;
movedex[48].hitcount = 1;
movedex[48].target = 0;
movedex[49].name = "<NAME>";
movedex[49].basepower = 0;
movedex[49].acc = 100;
movedex[49].type = "Dark";
movedex[49].typeint = 16;
movedex[49].effect = "+2spatk";
movedex[49].effectchance = 100;
movedex[49].priority = 0;
movedex[49].attackorstatus = 1;
movedex[49].physicalorspecial = 1;
movedex[49].recoilordrain = 0;
movedex[49].hitcount = 1;
movedex[49].target = 1;
movedex[50].name = "<NAME>";
movedex[50].basepower = 0;
movedex[50].acc = 100;
movedex[50].type = "Normal";
movedex[50].typeint = 1;
movedex[50].effect = "+2atk";
movedex[50].effectchance = 100;
movedex[50].priority = 0;
movedex[50].attackorstatus = 1;
movedex[50].physicalorspecial = 1;
movedex[50].recoilordrain = 0;
movedex[50].hitcount = 1;
movedex[50].target = 1;
movedex[51].name = "<NAME>";
movedex[51].basepower = 75;
movedex[51].acc = 100;
movedex[51].type = "Fighting";
movedex[51].typeint = 7;
movedex[51].effect = "None";
movedex[51].effectchance = 0;
movedex[51].priority = 0;
movedex[51].attackorstatus = 0;
movedex[51].physicalorspecial = 0;
movedex[51].recoilordrain = 0;
movedex[51].hitcount = 1;
movedex[51].target = 0;
movedex[52].name = "<NAME>";
movedex[52].basepower = 80;
movedex[52].acc = 100;
movedex[52].type = "Grass";
movedex[52].typeint = 5;
movedex[52].effect = "-spdef";
movedex[52].effectchance = 10;
movedex[52].priority = 0;
movedex[52].attackorstatus = 0;
movedex[52].physicalorspecial = 1;
movedex[52].recoilordrain = 0;
movedex[52].hitcount = 1;
movedex[52].target = 0;
movedex[53].name = "<NAME>";
movedex[53].basepower = 80;
movedex[53].acc = 100;
movedex[53].type = "Dark";
movedex[53].typeint = 16;
movedex[53].effect = "Flinch";
movedex[53].effectchance = 20;
movedex[53].priority = 0;
movedex[53].attackorstatus = 0;
movedex[53].physicalorspecial = 1;
movedex[53].recoilordrain = 0;
movedex[53].hitcount = 1;
movedex[53].target = 0;
movedex[54].name = "Spore";
movedex[54].basepower = 0;
movedex[54].acc = 100;
movedex[54].type = "Grass";
movedex[54].typeint = 5;
movedex[54].effect = "Sleep";
movedex[54].effectchance = 100;
movedex[54].priority = 0;
movedex[54].attackorstatus = 1;
movedex[54].physicalorspecial = 1;
movedex[54].recoilordrain = 0;
movedex[54].hitcount = 1;
movedex[54].target = 0;
movedex[55].name = "Rock Slide";
movedex[55].basepower = 75;
movedex[55].acc = 90;
movedex[55].type = "Rock";
movedex[55].typeint = 13;
movedex[55].effect = "Flinch";
movedex[55].effectchance = 30;
movedex[55].priority = 0;
movedex[55].attackorstatus = 0;
movedex[55].physicalorspecial = 0;
movedex[55].recoilordrain = 0;
movedex[55].hitcount = 1;
movedex[55].target = 0;
movedex[56].name = "<NAME>";
movedex[56].basepower = 70;
movedex[56].acc = 100;
movedex[56].type = "Ghost";
movedex[56].typeint = 14;
movedex[56].effect = "None";
movedex[56].effectchance = 0;
movedex[56].priority = 0;
movedex[56].attackorstatus = 0;
movedex[56].physicalorspecial = 0;
movedex[56].recoilordrain = 0;
movedex[56].hitcount = 1;
movedex[56].target = 0;
movedex[57].name = "<NAME>";
movedex[57].basepower = 70;
movedex[57].acc = 100;
movedex[57].type = "Dark";
movedex[57].typeint = 16;
movedex[57].effect = "None";
movedex[57].effectchance = 0;
movedex[57].priority = 0;
movedex[57].attackorstatus = 0;
movedex[57].physicalorspecial = 0;
movedex[57].recoilordrain = 0;
movedex[57].hitcount = 1;
movedex[57].target = 0;
movedex[58].name = "<NAME>";
movedex[58].basepower = 0;
movedex[58].acc = 100;
movedex[58].type = "Psychic";
movedex[58].typeint = 11;
movedex[58].effect = "+spatk+spdef";
movedex[58].effectchance = 100;
movedex[58].priority = 0;
movedex[58].attackorstatus = 1;
movedex[58].physicalorspecial = 1;
movedex[58].recoilordrain = 0;
movedex[58].hitcount = 1;
movedex[58].target = 1;
movedex[59].name = "Bulk Up";
movedex[59].basepower = 0;
movedex[59].acc = 100;
movedex[59].type = "Fighting";
movedex[59].typeint = 7;
movedex[59].effect = "+atk+def";
movedex[59].effectchance = 100;
movedex[59].priority = 0;
movedex[59].attackorstatus = 1;
movedex[59].physicalorspecial = 1;
movedex[59].recoilordrain = 0;
movedex[59].hitcount = 1;
movedex[59].target = 1;
movedex[60].name = "Fire Punch";
movedex[60].basepower = 75;
movedex[60].acc = 100;
movedex[60].type = "Fire";
movedex[60].typeint = 2;
movedex[60].effect = "Burn";
movedex[60].effectchance = 10;
movedex[60].priority = 0;
movedex[60].attackorstatus = 0;
movedex[60].physicalorspecial = 0;
movedex[60].recoilordrain = 0;
movedex[60].hitcount = 1;
movedex[60].target = 0;
movedex[61].name = "Extremespeed";
movedex[61].basepower = 80;
movedex[61].acc = 100;
movedex[61].type = "Normal";
movedex[61].typeint = 1;
movedex[61].effect = "None";
movedex[61].effectchance = 0;
movedex[61].priority = 2;
movedex[61].attackorstatus = 0;
movedex[61].physicalorspecial = 0;
movedex[61].recoilordrain = 0;
movedex[61].hitcount = 1;
movedex[61].target = 0;
movedex[62].name = "Shadow Ball";
movedex[62].basepower = 80;
movedex[62].acc = 100;
movedex[62].type = "Ghost";
movedex[62].typeint = 14;
movedex[62].effect = "-spdef";
movedex[62].effectchance = 20;
movedex[62].priority = 0;
movedex[62].attackorstatus = 0;
movedex[62].physicalorspecial = 1;
movedex[62].recoilordrain = 0;
movedex[62].hitcount = 1;
movedex[62].target = 0;
movedex[63].name = "Recover";
movedex[63].basepower = 0;
movedex[63].acc = 100;
movedex[63].type = "Normal";
movedex[63].typeint = 1;
movedex[63].effect = "Restore";
movedex[63].effectchance = 100;
movedex[63].priority = 0;
movedex[63].attackorstatus = 1;
movedex[63].physicalorspecial = 1;
movedex[63].recoilordrain = 0;
movedex[63].hitcount = 1;
movedex[63].target = 1;
movedex[64].name = "Synthesis";
movedex[64].basepower = 0;
movedex[64].acc = 100;
movedex[64].type = "Grass";
movedex[64].typeint = 5;
movedex[64].effect = "Restore";
movedex[64].effectchance = 100;
movedex[64].priority = 0;
movedex[64].attackorstatus = 1;
movedex[64].physicalorspecial = 1;
movedex[64].recoilordrain = 0;
movedex[64].hitcount = 1;
movedex[64].target = 1;
movedex[65].name = "Thunderpunch";
movedex[65].basepower = 75;
movedex[65].acc = 100;
movedex[65].type = "Electric";
movedex[65].typeint = 4;
movedex[65].effect = "Paralyze";
movedex[65].effectchance = 10;
movedex[65].priority = 0;
movedex[65].attackorstatus = 0;
movedex[65].physicalorspecial = 0;
movedex[65].recoilordrain = 0;
movedex[65].hitcount = 1;
movedex[65].target = 0;
movedex[66].name = "Megahorn";
movedex[66].basepower = 120;
movedex[66].acc = 100;
movedex[66].type = "Bug";
movedex[66].typeint = 12;
movedex[66].effect = "None";
movedex[66].effectchance = 0;
movedex[66].priority = 0;
movedex[66].attackorstatus = 0;
movedex[66].physicalorspecial = 0;
movedex[66].recoilordrain = 0;
movedex[66].hitcount = 1;
movedex[66].target = 0;
movedex[67].name = "<NAME>";
movedex[67].basepower = 0;
movedex[67].acc = 100;
movedex[67].type = "Fire";
movedex[67].typeint = 2;
movedex[67].effect = "Restore";
movedex[67].effectchance = 100;
movedex[67].priority = 0;
movedex[67].attackorstatus = 1;
movedex[67].physicalorspecial = 1;
movedex[67].recoilordrain = 0;
movedex[67].hitcount = 1;
movedex[67].target = 1;
movedex[68].name = "<NAME>";
movedex[68].basepower = 80;
movedex[68].acc = 100;
movedex[68].type = "Steel";
movedex[68].typeint = 17;
movedex[68].effect = "-spdef";
movedex[68].effectchance = 10;
movedex[68].priority = 0;
movedex[68].attackorstatus = 0;
movedex[68].physicalorspecial = 1;
movedex[68].recoilordrain = 0;
movedex[68].hitcount = 1;
movedex[68].target = 0;
movedex[69].name = "<NAME>";
movedex[69].basepower = 0;
movedex[69].acc = 100;
movedex[69].type = "Steel";
movedex[69].typeint = 17;
movedex[69].effect = "+2def";
movedex[69].effectchance = 100;
movedex[69].priority = 0;
movedex[69].attackorstatus = 1;
movedex[69].physicalorspecial = 1;
movedex[69].recoilordrain = 0;
movedex[69].hitcount = 1;
movedex[69].target = 1;
movedex[70].name = "<NAME>";
movedex[70].basepower = 120;
movedex[70].acc = 100;
movedex[70].type = "Flying";
movedex[70].typeint = 10;
movedex[70].effect = "None";
movedex[70].effectchance = 0;
movedex[70].priority = 0;
movedex[70].attackorstatus = 0;
movedex[70].physicalorspecial = 0;
movedex[70].recoilordrain = -2;
movedex[70].hitcount = 1;
movedex[70].target = 0;
movedex[71].name = "<NAME>";
movedex[71].basepower = 70;
movedex[71].acc = 100;
movedex[71].type = "Steel";
movedex[71].typeint = 17;
movedex[71].effect = "None";
movedex[71].effectchance = 0;
movedex[71].priority = 0;
movedex[71].attackorstatus = 0;
movedex[71].physicalorspecial = 0;
movedex[71].recoilordrain = 0;
movedex[71].hitcount = 1;
movedex[71].target = 0;
movedex[72].name = "Rest";
movedex[72].basepower = 0;
movedex[72].acc = 100;
movedex[72].type = "Normal";
movedex[72].typeint = 1;
movedex[72].effect = "Rest";
movedex[72].effectchance = 100;
movedex[72].priority = 0;
movedex[72].attackorstatus = 1;
movedex[72].physicalorspecial = 1;
movedex[72].recoilordrain = 0;
movedex[72].hitcount = 1;
movedex[72].target = 1;
movedex[73].name = "Ice Shard";
movedex[73].basepower = 40;
movedex[73].acc = 100;
movedex[73].type = "Ice";
movedex[73].typeint = 6;
movedex[73].effect = "None";
movedex[73].effectchance = 0;
movedex[73].priority = 1;
movedex[73].attackorstatus = 0;
movedex[73].physicalorspecial = 0;
movedex[73].recoilordrain = 0;
movedex[73].hitcount = 1;
movedex[73].target = 0;
movedex[74].name = "Stone Edge";
movedex[74].basepower = 100;
movedex[74].acc = 80;
movedex[74].type = "Rock";
movedex[74].typeint = 13;
movedex[74].effect = "None";
movedex[74].effectchance = 0;
movedex[74].priority = 0;
movedex[74].attackorstatus = 0;
movedex[74].physicalorspecial = 0;
movedex[74].recoilordrain = 0;
movedex[74].hitcount = 1;
movedex[74].target = 0;
movedex[75].name = "Rock Polish";
movedex[75].basepower = 0;
movedex[75].acc = 100;
movedex[75].type = "Rock";
movedex[75].typeint = 13;
movedex[75].effect = "+2speed";
movedex[75].effectchance = 100;
movedex[75].priority = 0;
movedex[75].attackorstatus = 1;
movedex[75].physicalorspecial = 1;
movedex[75].recoilordrain = 0;
movedex[75].hitcount = 1;
movedex[75].target = 1;
movedex[76].name = "<NAME>";
movedex[76].basepower = 80;
movedex[76].acc = 100;
movedex[76].type = "Steel";
movedex[76].typeint = 17;
movedex[76].effect = "Flinch";
movedex[76].effectchance = 30;
movedex[76].priority = 0;
movedex[76].attackorstatus = 0;
movedex[76].physicalorspecial = 0;
movedex[76].recoilordrain = 0;
movedex[76].hitcount = 1;
movedex[76].target = 0;
movedex[77].name = "<NAME>";
movedex[77].basepower = 75;
movedex[77].acc = 100;
movedex[77].type = "Bug";
movedex[77].typeint = 12;
movedex[77].effect = "Confuse";
movedex[77].effectchance = 10;
movedex[77].priority = 0;
movedex[77].attackorstatus = 0;
movedex[77].physicalorspecial = 1;
movedex[77].recoilordrain = 0;
movedex[77].hitcount = 1;
movedex[77].target = 0;
movedex[78].name = "<NAME>";
movedex[78].basepower = 85;
movedex[78].acc = 90;
movedex[78].type = "Fire";
movedex[78].typeint = 2;
movedex[78].effect = "Burn";
movedex[78].effectchance = 10;
movedex[78].priority = 0;
movedex[78].attackorstatus = 0;
movedex[78].physicalorspecial = 0;
movedex[78].recoilordrain = 0;
movedex[78].hitcount = 1;
movedex[78].target = 0;
movedex[79].name = "<NAME>";
movedex[79].basepower = 75;
movedex[79].acc = 100;
movedex[79].type = "Ice";
movedex[79].typeint = 6;
movedex[79].effect = "Freeze";
movedex[79].effectchance = 10;
movedex[79].priority = 0;
movedex[79].attackorstatus = 0;
movedex[79].physicalorspecial = 0;
movedex[79].recoilordrain = 0;
movedex[79].hitcount = 1;
movedex[79].target = 0;
movedex[80].name = "<NAME>";
movedex[80].basepower = 40;
movedex[80].acc = 100;
movedex[80].type = "Fighting";
movedex[80].typeint = 7;
movedex[80].effect = "None";
movedex[80].effectchance = 0;
movedex[80].priority = 1;
movedex[80].attackorstatus = 0;
movedex[80].physicalorspecial = 0;
movedex[80].recoilordrain = 0;
movedex[80].hitcount = 1;
movedex[80].target = 0;
movedex[81].name = "Will-o-wisp";
movedex[81].basepower = 0;
movedex[81].acc = 75;
movedex[81].type = "Fire";
movedex[81].typeint = 2;
movedex[81].effect = "Burn";
movedex[81].effectchance = 100;
movedex[81].priority = 0;
movedex[81].attackorstatus = 1;
movedex[81].physicalorspecial = 1;
movedex[81].recoilordrain = 0;
movedex[81].hitcount = 1;
movedex[81].target = 0;
movedex[82].name = "Softboiled";
movedex[82].basepower = 0;
movedex[82].acc = 100;
movedex[82].type = "Normal";
movedex[82].typeint = 1;
movedex[82].effect = "Restore";
movedex[82].effectchance = 100;
movedex[82].priority = 0;
movedex[82].attackorstatus = 1;
movedex[82].physicalorspecial = 1;
movedex[82].recoilordrain = 0;
movedex[82].hitcount = 1;
movedex[82].target = 1;
movedex[83].name = "<NAME>";
movedex[83].basepower = 0;
movedex[83].acc = 75;
movedex[83].type = "Grass";
movedex[83].typeint = 5;
movedex[83].effect = "Paralyze";
movedex[83].effectchance = 100;
movedex[83].priority = 0;
movedex[83].attackorstatus = 1;
movedex[83].physicalorspecial = 1;
movedex[83].recoilordrain = 0;
movedex[83].hitcount = 1;
movedex[83].target = 0;
movedex[84].name = "<NAME>";
movedex[84].basepower = 0;
movedex[84].acc = 100;
movedex[84].type = "Dragon";
movedex[84].typeint = 15;
movedex[84].effect = "+atk+speed";
movedex[84].effectchance = 100;
movedex[84].priority = 0;
movedex[84].attackorstatus = 1;
movedex[84].physicalorspecial = 1;
movedex[84].recoilordrain = 0;
movedex[84].hitcount = 1;
movedex[84].target = 1;
movedex[85].name = "Waterfall";
movedex[85].basepower = 80;
movedex[85].acc = 100;
movedex[85].type = "Water";
movedex[85].typeint = 3;
movedex[85].effect = "Flinch";
movedex[85].effectchance = 20;
movedex[85].priority = 0;
movedex[85].attackorstatus = 0;
movedex[85].physicalorspecial = 0;
movedex[85].recoilordrain = 0;
movedex[85].hitcount = 1;
movedex[85].target = 0;
movedex[86].name = "<NAME>";
movedex[86].basepower = 100;
movedex[86].acc = 80;
movedex[86].type = "Fighting";
movedex[86].typeint = 7;
movedex[86].effect = "None";
movedex[86].effectchance = 0;
movedex[86].priority = 0;
movedex[86].attackorstatus = 0;
movedex[86].physicalorspecial = 0;
movedex[86].recoilordrain = 0;
movedex[86].hitcount = 1;
movedex[86].target = 0;
movedex[87].name = "<NAME>";
movedex[87].basepower = 120;
movedex[87].acc = 100;
movedex[87].type = "Fire";
movedex[87].typeint = 2;
movedex[87].effect = "Burn";
movedex[87].effectchance = 10;
movedex[87].priority = 0;
movedex[87].attackorstatus = 0;
movedex[87].physicalorspecial = 0;
movedex[87].recoilordrain = -2;
movedex[87].hitcount = 1;
movedex[87].target = 0;
movedex[88].name = "<NAME>";
movedex[88].basepower = 80;
movedex[88].acc = 100;
movedex[88].type = "Dragon";
movedex[88].typeint = 15;
movedex[88].effect = "None";
movedex[88].effectchance = 0;
movedex[88].priority = 0;
movedex[88].attackorstatus = 0;
movedex[88].physicalorspecial = 0;
movedex[88].recoilordrain = 0;
movedex[88].hitcount = 1;
movedex[88].target = 0;
movedex[89].name = "<NAME>";
movedex[89].basepower = 0;
movedex[89].acc = 100;
movedex[89].type = "Normal";
movedex[89].typeint = 1;
movedex[89].effect = "+def";
movedex[89].effectchance = 100;
movedex[89].priority = 0;
movedex[89].attackorstatus = 1;
movedex[89].physicalorspecial = 1;
movedex[89].recoilordrain = 0;
movedex[89].hitcount = 1;
movedex[89].target = 1;
movedex[90].name = "<NAME>";
movedex[90].basepower = 100;
movedex[90].acc = 90;
movedex[90].type = "Fire";
movedex[90].typeint = 2;
movedex[90].effect = "Burn";
movedex[90].effectchance = 10;
movedex[90].priority = 0;
movedex[90].attackorstatus = 0;
movedex[90].physicalorspecial = 1;
movedex[90].recoilordrain = 0;
movedex[90].hitcount = 1;
movedex[90].target = 0;
//initialize pokedex-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for (int i = 0; i < 151; i++)
{
pokedex[i].name = "FillerFiller12401940"; //this is jsut so the program doesnt segfault when checking thru pokedex[i].name
}
pokedex[2].name = "Venusaur";
pokedex[2].baseatk = 82;
pokedex[2].basedef = 83;
pokedex[2].basespatk = 100;
pokedex[2].basespdef = 100;
pokedex[2].basespeed = 80;
pokedex[2].basehp = 80;
pokedex[2].growthmod = 3;
pokedex[2].expyield = 1;
pokedex[2].evolveat = 101;
pokedex[2].evolveto = 2;
pokedex[2].type1 = "Grass";
pokedex[2].type2 = "Poison";
pokedex[2].typeint1 = 5;
pokedex[2].typeint2 = 8;
pokedex[2].move1 = movedex[28];
pokedex[2].move2 = movedex[29];
pokedex[2].move3 = movedex[30];
pokedex[2].move4 = movedex[31];
pokedex[5].name = "Charizard";
pokedex[5].baseatk = 84;
pokedex[5].basedef = 78;
pokedex[5].basespatk = 109;
pokedex[5].basespdef = 85;
pokedex[5].basespeed = 100;
pokedex[5].basehp = 78;
pokedex[5].growthmod = 3;
pokedex[5].expyield = 1;
pokedex[5].evolveat = 101;
pokedex[5].evolveto = 5;
pokedex[5].type1 = "Fire";
pokedex[5].type2 = "Flying";
pokedex[5].typeint1 = 2;
pokedex[5].typeint2 = 10;
pokedex[5].move1 = movedex[26];
pokedex[5].move2 = movedex[32];
pokedex[5].move3 = movedex[30];
pokedex[5].move4 = movedex[33]; //33
pokedex[8].name = "Blastoise";
pokedex[8].baseatk = 83;
pokedex[8].basedef = 100;
pokedex[8].basespatk = 85;
pokedex[8].basespdef = 105;
pokedex[8].basespeed = 78;
pokedex[8].basehp = 79;
pokedex[8].growthmod = 3;
pokedex[8].expyield = 1;
pokedex[8].evolveat = 101;
pokedex[8].evolveto = 8;
pokedex[8].type1 = "Water";
pokedex[8].type2 = "None";
pokedex[8].typeint1 = 3;
pokedex[8].typeint2 = 0;
pokedex[8].move1 = movedex[27];
pokedex[8].move2 = movedex[34];
pokedex[8].move3 = movedex[30];
pokedex[8].move4 = movedex[25];
pokedex[11].name = "Butterfree";
pokedex[11].basehp = 60;
pokedex[11].baseatk = 45;
pokedex[11].basedef = 50;
pokedex[11].basespatk = 80;
pokedex[11].basespdef = 80;
pokedex[11].basespeed = 70;
pokedex[11].growthmod = 3;
pokedex[11].expyield = 1;
pokedex[11].evolveat = 101;
pokedex[11].evolveto = 8;
pokedex[11].type1 = "Bug";
pokedex[11].type2 = "Flying";
pokedex[11].typeint1 = 12;
pokedex[11].typeint2 = 10;
pokedex[11].move1 = movedex[35];
pokedex[11].move2 = movedex[36];
pokedex[11].move3 = movedex[37];
pokedex[11].move4 = movedex[38];
pokedex[14].name = "Beedrill";
pokedex[14].basehp = 65;
pokedex[14].baseatk = 80;
pokedex[14].basedef = 40;
pokedex[14].basespatk = 45;
pokedex[14].basespdef = 80;
pokedex[14].basespeed = 75;
pokedex[14].growthmod = 11;
pokedex[14].expyield = 11;
pokedex[14].evolveat = 11;
pokedex[14].evolveto = 11;
pokedex[14].type1 = "Bug";
pokedex[14].type2 = "Poison";
pokedex[14].typeint1 = 12;
pokedex[14].typeint2 = 8;
pokedex[14].move1 = movedex[39];
pokedex[14].move2 = movedex[40];
pokedex[14].move3 = movedex[31];
pokedex[14].move4 = movedex[28];
pokedex[17].name = "Pidgeot";
pokedex[17].basehp = 83;
pokedex[17].baseatk = 80;
pokedex[17].basedef = 75;
pokedex[17].basespatk = 70;
pokedex[17].basespdef = 70;
pokedex[17].basespeed = 91;
pokedex[17].growthmod = 11;
pokedex[17].expyield = 11;
pokedex[17].evolveat = 11;
pokedex[17].evolveto = 11;
pokedex[17].type1 = "Normal";
pokedex[17].type2 = "Flying";
pokedex[17].typeint1 = 1;
pokedex[17].typeint2 = 10;
pokedex[17].move1 = movedex[25];
pokedex[17].move2 = movedex[32];
pokedex[17].move3 = movedex[41];
pokedex[17].move4 = movedex[42];
pokedex[19].name = "Raticate";
pokedex[19].basehp = 55;
pokedex[19].baseatk = 81;
pokedex[19].basedef = 60;
pokedex[19].basespatk = 50;
pokedex[19].basespdef = 70;
pokedex[19].basespeed = 97;
pokedex[19].growthmod = 11;
pokedex[19].expyield = 11;
pokedex[19].evolveat = 11;
pokedex[19].evolveto = 11;
pokedex[19].type1 = "Normal";
pokedex[19].type2 = "None";
pokedex[19].typeint1 = 1;
pokedex[19].typeint2 = 0;
pokedex[19].move1 = movedex[25];
pokedex[19].move2 = movedex[43];
pokedex[19].move3 = movedex[34];
pokedex[19].move4 = movedex[44];
pokedex[21].name = "Fearow";
pokedex[21].basehp = 65;
pokedex[21].baseatk = 90;
pokedex[21].basedef = 65;
pokedex[21].basespatk = 61;
pokedex[21].basespdef = 61;
pokedex[21].basespeed = 100;
pokedex[21].growthmod = 11;
pokedex[21].expyield = 11;
pokedex[21].evolveat = 11;
pokedex[21].evolveto = 11;
pokedex[21].type1 = "Normal";
pokedex[21].type2 = "Flying";
pokedex[21].typeint1 = 1;
pokedex[21].typeint2 = 10;
pokedex[21].move1 = movedex[45];
pokedex[21].move2 = movedex[25];
pokedex[21].move3 = movedex[42];
pokedex[21].move4 = movedex[46];
pokedex[23].name = "Arbok";
pokedex[23].basehp = 60;
pokedex[23].baseatk = 85;
pokedex[23].basedef = 69;
pokedex[23].basespatk = 65;
pokedex[23].basespdef = 79;
pokedex[23].basespeed = 80;
pokedex[23].growthmod = 11;
pokedex[23].expyield = 11;
pokedex[23].evolveat = 11;
pokedex[23].evolveto = 11;
pokedex[23].type1 = "Poison";
pokedex[23].type2 = "None";
pokedex[23].typeint1 = 8;
pokedex[23].typeint2 = 0;
pokedex[23].move1 = movedex[29];
pokedex[23].move2 = movedex[30];
pokedex[23].move3 = movedex[47];
pokedex[23].move4 = movedex[16];
pokedex[24].name = "Pikachu";
pokedex[24].basehp = 35;
pokedex[24].baseatk = 55;
pokedex[24].basedef = 30;
pokedex[24].basespatk = 50;
pokedex[24].basespdef = 40;
pokedex[24].basespeed = 90;
pokedex[24].growthmod = 11;
pokedex[24].expyield = 11;
pokedex[24].evolveat = 11;
pokedex[24].evolveto = 11;
pokedex[24].type1 = "Electric";
pokedex[24].type2 = "None";
pokedex[24].typeint1 = 4;
pokedex[24].typeint2 = 0;
pokedex[24].move1 = movedex[43];
pokedex[24].move2 = movedex[44];
pokedex[24].move3 = movedex[48];
pokedex[24].move4 = movedex[49];
pokedex[25].name = "Raichu";
pokedex[25].basehp = 60;
pokedex[25].baseatk = 90;
pokedex[25].basedef = 55;
pokedex[25].basespatk = 90;
pokedex[25].basespdef = 80;
pokedex[25].basespeed = 100;
pokedex[25].growthmod = 11;
pokedex[25].expyield = 11;
pokedex[25].evolveat = 11;
pokedex[25].evolveto = 11;
pokedex[25].type1 = "Electric";
pokedex[25].type2 = "None";
pokedex[25].typeint1 = 4;
pokedex[25].typeint2 = 0;
pokedex[25].move1 = movedex[43];
pokedex[25].move2 = movedex[44];
pokedex[25].move3 = movedex[48];
pokedex[25].move4 = movedex[49];
pokedex[27].name = "Sandslash";
pokedex[27].basehp = 75;
pokedex[27].baseatk = 100;
pokedex[27].basedef = 110;
pokedex[27].basespatk = 45;
pokedex[27].basespdef = 55;
pokedex[27].basespeed = 65;
pokedex[27].growthmod = 11;
pokedex[27].expyield = 11;
pokedex[27].evolveat = 11;
pokedex[27].evolveto = 11;
pokedex[27].type1 = "Ground";
pokedex[27].type2 = "None";
pokedex[27].typeint1 = 9;
pokedex[27].typeint2 = 0;
pokedex[27].move1 = movedex[30];
pokedex[27].move2 = movedex[39];
pokedex[27].move3 = movedex[50];
pokedex[27].move4 = movedex[51];
pokedex[30].name = "Nidoqueen";
pokedex[30].basehp = 90;
pokedex[30].baseatk = 82;
pokedex[30].basedef = 87;
pokedex[30].basespatk = 75;
pokedex[30].basespdef = 85;
pokedex[30].basespeed = 76;
pokedex[30].growthmod = 11;
pokedex[30].expyield = 11;
pokedex[30].evolveat = 11;
pokedex[30].evolveto = 11;
pokedex[30].type1 = "Ground";
pokedex[30].type2 = "Poison";
pokedex[30].typeint1 = 9;
pokedex[30].typeint2 = 8;
pokedex[30].move1 = movedex[30];
pokedex[30].move2 = movedex[39];
pokedex[30].move3 = movedex[34];
pokedex[30].move4 = movedex[43];
pokedex[33].name = "Nidoking";
pokedex[33].basehp = 81;
pokedex[33].baseatk = 92;
pokedex[33].basedef = 77;
pokedex[33].basespatk = 85;
pokedex[33].basespdef = 75;
pokedex[33].basespeed = 85;
pokedex[33].growthmod = 11;
pokedex[33].expyield = 11;
pokedex[33].evolveat = 11;
pokedex[33].evolveto = 11;
pokedex[33].type1 = "Ground";
pokedex[33].type2 = "Poison";
pokedex[33].typeint1 = 9;
pokedex[33].typeint2 = 8;
pokedex[33].move1 = movedex[30];
pokedex[33].move2 = movedex[29];
pokedex[33].move3 = movedex[34];
pokedex[33].move4 = movedex[43];
pokedex[35].name = "Clefable";
pokedex[35].basehp = 95;
pokedex[35].baseatk = 70;
pokedex[35].basedef = 73;
pokedex[35].basespatk = 85;
pokedex[35].basespdef = 90;
pokedex[35].basespeed = 60;
pokedex[35].growthmod = 11;
pokedex[35].expyield = 11;
pokedex[35].evolveat = 11;
pokedex[35].evolveto = 11;
pokedex[35].type1 = "Normal";
pokedex[35].type2 = "None";
pokedex[35].typeint1 = 1;
pokedex[35].typeint2 = 0;
pokedex[35].move1 = movedex[43];
pokedex[35].move2 = movedex[34];
pokedex[35].move3 = movedex[36];
pokedex[35].move4 = movedex[16];
pokedex[37].name = "Ninetails";
pokedex[37].basehp = 73;
pokedex[37].baseatk = 76;
pokedex[37].basedef = 75;
pokedex[37].basespatk = 81;
pokedex[37].basespdef = 100;
pokedex[37].basespeed = 100;
pokedex[37].growthmod = 11;
pokedex[37].expyield = 11;
pokedex[37].evolveat = 11;
pokedex[37].evolveto = 11;
pokedex[37].type1 = "Fire";
pokedex[37].type2 = "None";
pokedex[37].typeint1 = 2;
pokedex[37].typeint2 = 0;
pokedex[37].move1 = movedex[26];
pokedex[37].move2 = movedex[52];
pokedex[37].move3 = movedex[49];
pokedex[37].move4 = movedex[53];
pokedex[39].name = "Wigglytuff";
pokedex[39].basehp = 140;
pokedex[39].baseatk = 70;
pokedex[39].basedef = 45;
pokedex[39].basespatk = 75;
pokedex[39].basespdef = 50;
pokedex[39].basespeed = 45;
pokedex[39].growthmod = 11;
pokedex[39].expyield = 11;
pokedex[39].evolveat = 11;
pokedex[39].evolveto = 11;
pokedex[39].type1 = "Normal";
pokedex[39].type2 = "None";
pokedex[39].typeint1 = 1;
pokedex[39].typeint2 = 0;
pokedex[39].move1 = movedex[16];
pokedex[39].move2 = movedex[33];
pokedex[39].move3 = movedex[15];
pokedex[39].move4 = movedex[48];
pokedex[41].name = "Golbat";
pokedex[41].basehp = 75;
pokedex[41].baseatk = 80;
pokedex[41].basedef = 70;
pokedex[41].basespatk = 65;
pokedex[41].basespdef = 75;
pokedex[41].basespeed = 90;
pokedex[41].growthmod = 11;
pokedex[41].expyield = 11;
pokedex[41].evolveat = 11;
pokedex[41].evolveto = 11;
pokedex[41].type1 = "Poison";
pokedex[41].type2 = "Flying";
pokedex[41].typeint1 = 8;
pokedex[41].typeint2 = 10;
pokedex[41].move1 = movedex[32];
pokedex[41].move2 = movedex[29];
pokedex[41].move3 = movedex[31];
pokedex[41].move4 = movedex[42];
pokedex[44].name = "Vileplume";
pokedex[44].basehp = 75;
pokedex[44].baseatk = 80;
pokedex[44].basedef = 85;
pokedex[44].basespatk = 100;
pokedex[44].basespdef = 90;
pokedex[44].basespeed = 50;
pokedex[44].growthmod = 11;
pokedex[44].expyield = 11;
pokedex[44].evolveat = 11;
pokedex[44].evolveto = 11;
pokedex[44].type1 = "Grass";
pokedex[44].type2 = "Poison";
pokedex[44].typeint1 = 5;
pokedex[44].typeint2 = 8;
pokedex[44].move1 = movedex[28];
pokedex[44].move2 = movedex[29];
pokedex[44].move3 = movedex[31];
pokedex[44].move4 = movedex[32];
pokedex[46].name = "Parasect";
pokedex[46].basehp = 60;
pokedex[46].baseatk = 95;
pokedex[46].basedef = 80;
pokedex[46].basespatk = 60;
pokedex[46].basespdef = 80;
pokedex[46].basespeed = 30;
pokedex[46].growthmod = 11;
pokedex[46].expyield = 11;
pokedex[46].evolveat = 11;
pokedex[46].evolveto = 11;
pokedex[46].type1 = "Bug";
pokedex[46].type2 = "Grass";
pokedex[46].typeint1 = 12;
pokedex[46].typeint2 = 5;
pokedex[46].move1 = movedex[40];
pokedex[46].move2 = movedex[52];
pokedex[46].move3 = movedex[31];
pokedex[46].move4 = movedex[54];
pokedex[48].name = "Venomoth";
pokedex[48].basehp = 70;
pokedex[48].baseatk = 65;
pokedex[48].basedef = 60;
pokedex[48].basespatk = 90;
pokedex[48].basespdef = 75;
pokedex[48].basespeed = 90;
pokedex[48].growthmod = 11;
pokedex[48].expyield = 11;
pokedex[48].evolveat = 11;
pokedex[48].evolveto = 11;
pokedex[48].type1 = "Bug";
pokedex[48].type2 = "Poison";
pokedex[48].typeint1 = 12;
pokedex[48].typeint2 = 8;
pokedex[48].move1 = movedex[36];
pokedex[48].move2 = movedex[29];
pokedex[48].move3 = movedex[35];
pokedex[48].move4 = movedex[31];
pokedex[50].name = "Dugtrio";
pokedex[50].basehp = 35;
pokedex[50].baseatk = 80;
pokedex[50].basedef = 50;
pokedex[50].basespatk = 50;
pokedex[50].basespdef = 70;
pokedex[50].basespeed = 120;
pokedex[50].growthmod = 11;
pokedex[50].expyield = 11;
pokedex[50].evolveat = 11;
pokedex[50].evolveto = 11;
pokedex[50].type1 = "Ground";
pokedex[50].type2 = "None";
pokedex[50].typeint1 = 9;
pokedex[50].typeint2 = 0;
pokedex[50].move1 = movedex[30];
pokedex[50].move2 = movedex[55];
pokedex[50].move3 = movedex[25];
pokedex[50].move4 = movedex[56];
pokedex[52].name = "Persian";
pokedex[52].basehp = 65;
pokedex[52].baseatk = 70;
pokedex[52].basedef = 60;
pokedex[52].basespatk = 65;
pokedex[52].basespdef = 65;
pokedex[52].basespeed = 115;
pokedex[52].growthmod = 11;
pokedex[52].expyield = 11;
pokedex[52].evolveat = 11;
pokedex[52].evolveto = 11;
pokedex[52].type1 = "Normal";
pokedex[52].type2 = "None";
pokedex[52].typeint1 = 1;
pokedex[52].typeint2 = 0;
pokedex[52].move1 = movedex[16];
pokedex[52].move2 = movedex[25];
pokedex[52].move3 = movedex[57];
pokedex[52].move4 = movedex[43];
pokedex[54].name = "Golduck";
pokedex[54].basehp = 80;
pokedex[54].baseatk = 82;
pokedex[54].basedef = 78;
pokedex[54].basespatk = 95;
pokedex[54].basespdef = 80;
pokedex[54].basespeed = 85;
pokedex[54].growthmod = 11;
pokedex[54].expyield = 11;
pokedex[54].evolveat = 11;
pokedex[54].evolveto = 11;
pokedex[54].type1 = "Water";
pokedex[54].type2 = "None";
pokedex[54].typeint1 = 3;
pokedex[54].typeint2 = 0;
pokedex[54].move1 = movedex[27];
pokedex[54].move2 = movedex[34];
pokedex[54].move3 = movedex[36];
pokedex[54].move4 = movedex[58];
pokedex[56].name = "Primeape";
pokedex[56].basehp = 65;
pokedex[56].baseatk = 105;
pokedex[56].basedef = 60;
pokedex[56].basespatk = 60;
pokedex[56].basespdef = 70;
pokedex[56].basespeed = 95;
pokedex[56].growthmod = 11;
pokedex[56].expyield = 11;
pokedex[56].evolveat = 11;
pokedex[56].evolveto = 11;
pokedex[56].type1 = "Fighting";
pokedex[56].type2 = "None";
pokedex[56].typeint1 = 7;
pokedex[56].typeint2 = 0;
pokedex[56].move1 = movedex[59];
pokedex[56].move2 = movedex[51];
pokedex[56].move3 = movedex[16];
pokedex[56].move4 = movedex[60];
pokedex[58].name = "Arcanine";
pokedex[58].basehp = 90;
pokedex[58].baseatk = 110;
pokedex[58].basedef = 80;
pokedex[58].basespatk = 100;
pokedex[58].basespdef = 80;
pokedex[58].basespeed = 95;
pokedex[58].growthmod = 11;
pokedex[58].expyield = 11;
pokedex[58].evolveat = 11;
pokedex[58].evolveto = 11;
pokedex[58].type1 = "Fire";
pokedex[58].type2 = "None";
pokedex[58].typeint1 = 2;
pokedex[58].typeint2 = 0;
pokedex[58].move1 = movedex[61];
pokedex[58].move2 = movedex[26];
pokedex[58].move3 = movedex[16];
pokedex[58].move4 = movedex[47];
pokedex[61].name = "Poliwrath";
pokedex[61].basehp = 90;
pokedex[61].baseatk = 85;
pokedex[61].basedef = 95;
pokedex[61].basespatk = 70;
pokedex[61].basespdef = 90;
pokedex[61].basespeed = 70;
pokedex[61].growthmod = 11;
pokedex[61].expyield = 11;
pokedex[61].evolveat = 11;
pokedex[61].evolveto = 11;
pokedex[61].type1 = "Water";
pokedex[61].type2 = "Fighting";
pokedex[61].typeint1 = 3;
pokedex[61].typeint2 = 7;
pokedex[61].move1 = movedex[59];
pokedex[61].move2 = movedex[27];
pokedex[61].move3 = movedex[51];
pokedex[61].move4 = movedex[16];
pokedex[64].name = "Alakazam";
pokedex[64].basehp = 55;
pokedex[64].baseatk = 50;
pokedex[64].basedef = 45;
pokedex[64].basespatk = 135;
pokedex[64].basespdef = 85;
pokedex[64].basespeed = 120;
pokedex[64].growthmod = 11;
pokedex[64].expyield = 11;
pokedex[64].evolveat = 11;
pokedex[64].evolveto = 11;
pokedex[64].type1 = "Psychic";
pokedex[64].type2 = "None";
pokedex[64].typeint1 = 11;
pokedex[64].typeint2 = 0;
pokedex[64].move1 = movedex[58];
pokedex[64].move2 = movedex[36];
pokedex[64].move3 = movedex[62];
pokedex[64].move4 = movedex[63];
pokedex[67].name = "Machamp";
pokedex[67].basehp = 90;
pokedex[67].baseatk = 130;
pokedex[67].basedef = 80;
pokedex[67].basespatk = 65;
pokedex[67].basespdef = 85;
pokedex[67].basespeed = 55;
pokedex[67].growthmod = 11;
pokedex[67].expyield = 11;
pokedex[67].evolveat = 11;
pokedex[67].evolveto = 11;
pokedex[67].type1 = "Fighting";
pokedex[67].type2 = "None";
pokedex[67].typeint1 = 7;
pokedex[67].typeint2 = 0;
pokedex[67].move1 = movedex[59];
pokedex[67].move2 = movedex[51];
pokedex[67].move3 = movedex[16];
pokedex[67].move4 = movedex[30];
pokedex[70].name = "Victreebel";
pokedex[70].basehp = 80;
pokedex[70].baseatk = 105;
pokedex[70].basedef = 65;
pokedex[70].basespatk = 100;
pokedex[70].basespdef = 60;
pokedex[70].basespeed = 70;
pokedex[70].growthmod = 11;
pokedex[70].expyield = 11;
pokedex[70].evolveat = 11;
pokedex[70].evolveto = 11;
pokedex[70].type1 = "Grass";
pokedex[70].type2 = "Poison";
pokedex[70].typeint1 = 5;
pokedex[70].typeint2 = 8;
pokedex[70].move1 = movedex[29];
pokedex[70].move2 = movedex[52];
pokedex[70].move3 = movedex[31];
pokedex[70].move4 = movedex[64];
pokedex[72].name = "Tentacruel";
pokedex[72].basehp = 80;
pokedex[72].baseatk = 70;
pokedex[72].basedef = 65;
pokedex[72].basespatk = 80;
pokedex[72].basespdef = 120;
pokedex[72].basespeed = 100;
pokedex[72].growthmod = 11;
pokedex[72].expyield = 11;
pokedex[72].evolveat = 11;
pokedex[72].evolveto = 11;
pokedex[72].type1 = "Water";
pokedex[72].type2 = "Poison";
pokedex[72].typeint1 = 3;
pokedex[72].typeint2 = 8;
pokedex[72].move1 = movedex[27];
pokedex[72].move2 = movedex[34];
pokedex[72].move3 = movedex[29];
pokedex[72].move4 = movedex[19];
pokedex[75].name = "Golem";
pokedex[75].basehp = 80;
pokedex[75].baseatk = 110;
pokedex[75].basedef = 130;
pokedex[75].basespatk = 55;
pokedex[75].basespdef = 65;
pokedex[75].basespeed = 45;
pokedex[75].growthmod = 11;
pokedex[75].expyield = 11;
pokedex[75].evolveat = 11;
pokedex[75].evolveto = 11;
pokedex[75].type1 = "Rock";
pokedex[75].type2 = "Ground";
pokedex[75].typeint1 = 13;
pokedex[75].typeint2 = 9;
pokedex[75].move1 = movedex[30];
pokedex[75].move2 = movedex[55];
pokedex[75].move3 = movedex[60];
pokedex[75].move4 = movedex[65];
pokedex[77].name = "Rapidash";
pokedex[77].basehp = 65;
pokedex[77].baseatk = 100;
pokedex[77].basedef = 70;
pokedex[77].basespatk = 80;
pokedex[77].basespdef = 80;
pokedex[77].basespeed = 105;
pokedex[77].growthmod = 11;
pokedex[77].expyield = 11;
pokedex[77].evolveat = 11;
pokedex[77].evolveto = 11;
pokedex[77].type1 = "Fire";
pokedex[77].type2 = "None";
pokedex[77].typeint1 = 2;
pokedex[77].typeint2 = 0;
pokedex[77].move1 = movedex[33];
pokedex[77].move2 = movedex[66];
pokedex[77].move3 = movedex[25];
pokedex[77].move4 = movedex[67];
pokedex[79].name = "Slowbro";
pokedex[79].basehp = 95;
pokedex[79].baseatk = 75;
pokedex[79].basedef = 110;
pokedex[79].basespatk = 100;
pokedex[79].basespdef = 80;
pokedex[79].basespeed = 30;
pokedex[79].growthmod = 11;
pokedex[79].expyield = 11;
pokedex[79].evolveat = 11;
pokedex[79].evolveto = 11;
pokedex[79].type1 = "Water";
pokedex[79].type2 = "Psychic";
pokedex[79].typeint1 = 3;
pokedex[79].typeint2 = 11;
pokedex[79].move1 = movedex[58];
pokedex[79].move2 = movedex[27];
pokedex[79].move3 = movedex[36];
pokedex[79].move4 = movedex[33];
pokedex[81].name = "Magneton";
pokedex[81].basehp = 50;
pokedex[81].baseatk = 60;
pokedex[81].basedef = 95;
pokedex[81].basespatk = 120;
pokedex[81].basespdef = 70;
pokedex[81].basespeed = 70;
pokedex[81].growthmod = 11;
pokedex[81].expyield = 11;
pokedex[81].evolveat = 11;
pokedex[81].evolveto = 11;
pokedex[81].type1 = "Electric";
pokedex[81].type2 = "Steel";
pokedex[81].typeint1 = 4;
pokedex[81].typeint2 = 17;
pokedex[81].move1 = movedex[43];
pokedex[81].move2 = movedex[68];
pokedex[81].move3 = movedex[44];
pokedex[81].move4 = movedex[69];
pokedex[82].name = "Farfetch'd";
pokedex[82].basehp = 52;
pokedex[82].baseatk = 65;
pokedex[82].basedef = 55;
pokedex[82].basespatk = 58;
pokedex[82].basespdef = 62;
pokedex[82].basespeed = 60;
pokedex[82].growthmod = 11;
pokedex[82].expyield = 11;
pokedex[82].evolveat = 11;
pokedex[82].evolveto = 11;
pokedex[82].type1 = "Normal";
pokedex[82].type2 = "Flying";
pokedex[82].typeint1 = 1;
pokedex[82].typeint2 = 10;
pokedex[82].move1 = movedex[50];
pokedex[82].move2 = movedex[42];
pokedex[82].move3 = movedex[16];
pokedex[82].move4 = movedex[70];
pokedex[84].name = "Dodrio";
pokedex[84].basehp = 60;
pokedex[84].baseatk = 110;
pokedex[84].basedef = 70;
pokedex[84].basespatk = 60;
pokedex[84].basespdef = 60;
pokedex[84].basespeed = 100;
pokedex[84].growthmod = 11;
pokedex[84].expyield = 11;
pokedex[84].evolveat = 11;
pokedex[84].evolveto = 11;
pokedex[84].type1 = "Normal";
pokedex[84].type2 = "flying";
pokedex[84].typeint1 = 1;
pokedex[84].typeint2 = 10;
pokedex[84].move1 = movedex[45];
pokedex[84].move2 = movedex[25];
pokedex[84].move3 = movedex[42];
pokedex[84].move4 = movedex[71];
pokedex[86].name = "Dewgong";
pokedex[86].basehp = 90;
pokedex[86].baseatk = 70;
pokedex[86].basedef = 80;
pokedex[86].basespatk = 70;
pokedex[86].basespdef = 95;
pokedex[86].basespeed = 70;
pokedex[86].growthmod = 11;
pokedex[86].expyield = 11;
pokedex[86].evolveat = 11;
pokedex[86].evolveto = 11;
pokedex[86].type1 = "Ice";
pokedex[86].type2 = "Water";
pokedex[86].typeint1 = 6;
pokedex[86].typeint2 = 3;
pokedex[86].move1 = movedex[27];
pokedex[86].move2 = movedex[34];
pokedex[86].move3 = movedex[72];
pokedex[86].move4 = movedex[73];
pokedex[88].name = "Muk";
pokedex[88].basehp = 105;
pokedex[88].baseatk = 105;
pokedex[88].basedef = 75;
pokedex[88].basespatk = 65;
pokedex[88].basespdef = 100;
pokedex[88].basespeed = 50;
pokedex[88].growthmod = 11;
pokedex[88].expyield = 11;
pokedex[88].evolveat = 11;
pokedex[88].evolveto = 11;
pokedex[88].type1 = "Poison";
pokedex[88].type2 = "None";
pokedex[88].typeint1 = 8;
pokedex[88].typeint2 = 0;
pokedex[88].move1 = movedex[29];
pokedex[88].move2 = movedex[33];
pokedex[88].move3 = movedex[31];
pokedex[88].move4 = movedex[51];
pokedex[90].name = "Cloyster";
pokedex[90].basehp = 50;
pokedex[90].baseatk = 95;
pokedex[90].basedef = 180;
pokedex[90].basespatk = 85;
pokedex[90].basespdef = 45;
pokedex[90].basespeed = 70;
pokedex[90].growthmod = 11;
pokedex[90].expyield = 11;
pokedex[90].evolveat = 11;
pokedex[90].evolveto = 11;
pokedex[90].type1 = "Water";
pokedex[90].type2 = "Ice";
pokedex[90].typeint1 = 3;
pokedex[90].typeint2 = 6;
pokedex[90].move1 = movedex[34];
pokedex[90].move2 = movedex[27];
pokedex[90].move3 = movedex[73];
pokedex[90].move4 = movedex[15];
pokedex[93].name = "Gengar";
pokedex[93].basehp = 60;
pokedex[93].baseatk = 65;
pokedex[93].basedef = 60;
pokedex[93].basespatk = 130;
pokedex[93].basespdef = 75;
pokedex[93].basespeed = 110;
pokedex[93].growthmod = 11;
pokedex[93].expyield = 11;
pokedex[93].evolveat = 11;
pokedex[93].evolveto = 11;
pokedex[93].type1 = "Ghost";
pokedex[93].type2 = "Poison";
pokedex[93].typeint1 = 14;
pokedex[93].typeint2 = 8;
pokedex[93].move1 = movedex[62];
pokedex[93].move2 = movedex[29];
pokedex[93].move3 = movedex[43];
pokedex[93].move4 = movedex[36];
pokedex[94].name = "Onix";
pokedex[94].basehp = 35;
pokedex[94].baseatk = 45;
pokedex[94].basedef = 160;
pokedex[94].basespatk = 30;
pokedex[94].basespdef = 45;
pokedex[94].basespeed = 70;
pokedex[94].growthmod = 11;
pokedex[94].expyield = 11;
pokedex[94].evolveat = 11;
pokedex[94].evolveto = 11;
pokedex[94].type1 = "Rock";
pokedex[94].type2 = "Ground";
pokedex[94].typeint1 = 13;
pokedex[94].typeint2 = 9;
pokedex[94].move1 = movedex[30];
pokedex[94].move2 = movedex[74];
pokedex[94].move3 = movedex[75];
pokedex[94].move4 = movedex[76];
pokedex[96].name = "Hypno";
pokedex[96].basehp = 85;
pokedex[96].baseatk = 73;
pokedex[96].basedef = 70;
pokedex[96].basespatk = 73;
pokedex[96].basespdef = 115;
pokedex[96].basespeed = 67;
pokedex[96].growthmod = 11;
pokedex[96].expyield = 11;
pokedex[96].evolveat = 11;
pokedex[96].evolveto = 11;
pokedex[96].type1 = "Psychic";
pokedex[96].type2 = "None";
pokedex[96].typeint1 = 11;
pokedex[96].typeint2 = 0;
pokedex[96].move1 = movedex[36];
pokedex[96].move2 = movedex[58];
pokedex[96].move3 = movedex[62];
pokedex[96].move4 = movedex[44];
pokedex[98].name = "Kingler";
pokedex[98].basehp = 55;
pokedex[98].baseatk = 130;
pokedex[98].basedef = 115;
pokedex[98].basespatk = 50;
pokedex[98].basespdef = 50;
pokedex[98].basespeed = 75;
pokedex[98].growthmod = 11;
pokedex[98].expyield = 11;
pokedex[98].evolveat = 11;
pokedex[98].evolveto = 11;
pokedex[98].type1 = "Water";
pokedex[98].type2 = "None";
pokedex[98].typeint1 = 3;
pokedex[98].typeint2 = 0;
pokedex[98].move1 = movedex[21];
pokedex[98].move2 = movedex[7];
pokedex[98].move3 = movedex[40];
pokedex[98].move4 = movedex[50];
pokedex[100].name = "Electrode";
pokedex[100].basehp = 60;
pokedex[100].baseatk = 50;
pokedex[100].basedef = 70;
pokedex[100].basespatk = 80;
pokedex[100].basespdef = 80;
pokedex[100].basespeed = 140;
pokedex[100].growthmod = 11;
pokedex[100].expyield = 11;
pokedex[100].evolveat = 11;
pokedex[100].evolveto = 11;
pokedex[100].type1 = "Electric";
pokedex[100].type2 = "None";
pokedex[100].typeint1 = 4;
pokedex[100].typeint2 = 0;
pokedex[100].move1 = movedex[44];
pokedex[100].move2 = movedex[43];
pokedex[100].move3 = movedex[48];
pokedex[100].move4 = movedex[77];
pokedex[102].name = "Exeggutor";
pokedex[102].basehp = 95;
pokedex[102].baseatk = 95;
pokedex[102].basedef = 85;
pokedex[102].basespatk = 125;
pokedex[102].basespdef = 65;
pokedex[102].basespeed = 55;
pokedex[102].growthmod = 11;
pokedex[102].expyield = 11;
pokedex[102].evolveat = 11;
pokedex[102].evolveto = 11;
pokedex[102].type1 = "Grass";
pokedex[102].type2 = "Psychic";
pokedex[102].typeint1 = 5;
pokedex[102].typeint2 = 11;
pokedex[102].move1 = movedex[36];
pokedex[102].move2 = movedex[52];
pokedex[102].move3 = movedex[37];
pokedex[102].move4 = movedex[29];
pokedex[104].name = "Marowak";
pokedex[104].basehp = 60;
pokedex[104].baseatk = 80;
pokedex[104].basedef = 110;
pokedex[104].basespatk = 50;
pokedex[104].basespdef = 80;
pokedex[104].basespeed = 45;
pokedex[104].growthmod = 11;
pokedex[104].expyield = 11;
pokedex[104].evolveat = 11;
pokedex[104].evolveto = 11;
pokedex[104].type1 = "Ground";
pokedex[104].type2 = "None";
pokedex[104].typeint1 = 9;
pokedex[104].typeint2 = 0;
pokedex[104].move1 = movedex[25];
pokedex[104].move2 = movedex[30];
pokedex[104].move3 = movedex[50];
pokedex[104].move4 = movedex[65];
pokedex[105].name = "Hitmonlee";
pokedex[105].basehp = 50;
pokedex[105].baseatk = 120;
pokedex[105].basedef = 53;
pokedex[105].basespatk = 35;
pokedex[105].basespdef = 110;
pokedex[105].basespeed = 87;
pokedex[105].growthmod = 11;
pokedex[105].expyield = 11;
pokedex[105].evolveat = 11;
pokedex[105].evolveto = 11;
pokedex[105].type1 = "Fighting";
pokedex[105].type2 = "None";
pokedex[105].typeint1 = 7;
pokedex[105].typeint2 = 0;
pokedex[105].move1 = movedex[59];
pokedex[105].move2 = movedex[30];
pokedex[105].move3 = movedex[78];
pokedex[105].move4 = movedex[51];
pokedex[106].name = "Hitmonchan";
pokedex[106].basehp = 50;
pokedex[106].baseatk = 105;
pokedex[106].basedef = 79;
pokedex[106].basespatk = 35;
pokedex[106].basespdef = 110;
pokedex[106].basespeed = 76;
pokedex[106].growthmod = 11;
pokedex[106].expyield = 11;
pokedex[106].evolveat = 11;
pokedex[106].evolveto = 11;
pokedex[106].type1 = "Fighting";
pokedex[106].type2 = "None";
pokedex[106].typeint1 = 7;
pokedex[106].typeint2 = 0;
pokedex[106].move1 = movedex[59];
pokedex[106].move2 = movedex[65];
pokedex[106].move3 = movedex[79];
pokedex[106].move4 = movedex[80];
pokedex[107].name = "Lickitung";
pokedex[107].basehp = 90;
pokedex[107].baseatk = 55;
pokedex[107].basedef = 75;
pokedex[107].basespatk = 60;
pokedex[107].basespdef = 75;
pokedex[107].basespeed = 30;
pokedex[107].growthmod = 11;
pokedex[107].expyield = 11;
pokedex[107].evolveat = 11;
pokedex[107].evolveto = 11;
pokedex[107].type1 = "Normal";
pokedex[107].type2 = "None";
pokedex[107].typeint1 = 1;
pokedex[107].typeint2 = 0;
pokedex[107].move1 = movedex[25];
pokedex[107].move2 = movedex[30];
pokedex[107].move3 = movedex[16];
pokedex[107].move4 = movedex[33];
pokedex[109].name = "Weezing";
pokedex[109].basehp = 65;
pokedex[109].baseatk = 90;
pokedex[109].basedef = 120;
pokedex[109].basespatk = 85;
pokedex[109].basespdef = 70;
pokedex[109].basespeed = 60;
pokedex[109].growthmod = 11;
pokedex[109].expyield = 11;
pokedex[109].evolveat = 11;
pokedex[109].evolveto = 11;
pokedex[109].type1 = "Poison";
pokedex[109].type2 = "None";
pokedex[109].typeint1 = 8;
pokedex[109].typeint2 = 0;
pokedex[109].move1 = movedex[29];
pokedex[109].move2 = movedex[33];
pokedex[109].move3 = movedex[31];
pokedex[109].move4 = movedex[81];
pokedex[111].name = "Rhydon";
pokedex[111].basehp = 105;
pokedex[111].baseatk = 130;
pokedex[111].basedef = 120;
pokedex[111].basespatk = 45;
pokedex[111].basespdef = 45;
pokedex[111].basespeed = 40;
pokedex[111].growthmod = 11;
pokedex[111].expyield = 11;
pokedex[111].evolveat = 11;
pokedex[111].evolveto = 11;
pokedex[111].type1 = "Rock";
pokedex[111].type2 = "Ground";
pokedex[111].typeint1 = 13;
pokedex[111].typeint2 = 9;
pokedex[111].move1 = movedex[30];
pokedex[111].move2 = movedex[74];
pokedex[111].move3 = movedex[75];
pokedex[111].move4 = movedex[79];
pokedex[112].name = "Chansey";
pokedex[112].basehp = 250;
pokedex[112].baseatk = 5;
pokedex[112].basedef = 5;
pokedex[112].basespatk = 35;
pokedex[112].basespdef = 105;
pokedex[112].basespeed = 50;
pokedex[112].growthmod = 11;
pokedex[112].expyield = 11;
pokedex[112].evolveat = 11;
pokedex[112].evolveto = 11;
pokedex[112].type1 = "Normal";
pokedex[112].type2 = "None";
pokedex[112].typeint1 = 1;
pokedex[112].typeint2 = 0;
pokedex[112].move1 = movedex[82];
pokedex[112].move2 = movedex[33];
pokedex[112].move3 = movedex[31];
pokedex[112].move4 = movedex[43];
pokedex[113].name = "Tangela";
pokedex[113].basehp = 65;
pokedex[113].baseatk = 55;
pokedex[113].basedef = 115;
pokedex[113].basespatk = 100;
pokedex[113].basespdef = 40;
pokedex[113].basespeed = 60;
pokedex[113].growthmod = 11;
pokedex[113].expyield = 11;
pokedex[113].evolveat = 11;
pokedex[113].evolveto = 11;
pokedex[113].type1 = "Grass";
pokedex[113].type2 = "None";
pokedex[113].typeint1 = 5;
pokedex[113].typeint2 = 0;
pokedex[113].move1 = movedex[28];
pokedex[113].move2 = movedex[29];
pokedex[113].move3 = movedex[37];
pokedex[113].move4 = movedex[83];
pokedex[114].name = "Kangaskhan";
pokedex[114].basehp = 105;
pokedex[114].baseatk = 95;
pokedex[114].basedef = 80;
pokedex[114].basespatk = 40;
pokedex[114].basespdef = 80;
pokedex[114].basespeed = 90;
pokedex[114].growthmod = 11;
pokedex[114].expyield = 11;
pokedex[114].evolveat = 11;
pokedex[114].evolveto = 11;
pokedex[114].type1 = "Normal";
pokedex[114].type2 = "None";
pokedex[114].typeint1 = 1;
pokedex[114].typeint2 = 0;
pokedex[114].move1 = movedex[25];
pokedex[114].move2 = movedex[30];
pokedex[114].move3 = movedex[60];
pokedex[114].move4 = movedex[65];
pokedex[116].name = "Seadra";
pokedex[116].basehp = 55;
pokedex[116].baseatk = 65;
pokedex[116].basedef = 95;
pokedex[116].basespatk = 95;
pokedex[116].basespdef = 45;
pokedex[116].basespeed = 85;
pokedex[116].growthmod = 11;
pokedex[116].expyield = 11;
pokedex[116].evolveat = 11;
pokedex[116].evolveto = 11;
pokedex[116].type1 = "Water";
pokedex[116].type2 = "None";
pokedex[116].typeint1 = 3;
pokedex[116].typeint2 = 0;
pokedex[116].move1 = movedex[84];
pokedex[116].move2 = movedex[85];
pokedex[116].move3 = movedex[25];
pokedex[116].move4 = movedex[27];
pokedex[118].name = "Seaking";
pokedex[118].basehp = 80;
pokedex[118].baseatk = 92;
pokedex[118].basedef = 65;
pokedex[118].basespatk = 65;
pokedex[118].basespdef = 80;
pokedex[118].basespeed = 68;
pokedex[118].growthmod = 11;
pokedex[118].expyield = 11;
pokedex[118].evolveat = 11;
pokedex[118].evolveto = 11;
pokedex[118].type1 = "Water";
pokedex[118].type2 = "None";
pokedex[118].typeint1 = 3;
pokedex[118].typeint2 = 0;
pokedex[118].move1 = movedex[85];
pokedex[118].move2 = movedex[25];
pokedex[118].move3 = movedex[46];
pokedex[118].move4 = movedex[66];
pokedex[120].name = "Starmie";
pokedex[120].basehp = 60;
pokedex[120].baseatk = 75;
pokedex[120].basedef = 85;
pokedex[120].basespatk = 100;
pokedex[120].basespdef = 85;
pokedex[120].basespeed = 115;
pokedex[120].growthmod = 11;
pokedex[120].expyield = 11;
pokedex[120].evolveat = 11;
pokedex[120].evolveto = 11;
pokedex[120].type1 = "Water";
pokedex[120].type2 = "Psychic";
pokedex[120].typeint1 = 3;
pokedex[120].typeint2 = 11;
pokedex[120].move1 = movedex[36];
pokedex[120].move2 = movedex[27];
pokedex[120].move3 = movedex[43];
pokedex[120].move4 = movedex[34];
pokedex[121].name = "Mr. Mime";
pokedex[121].basehp = 40;
pokedex[121].baseatk = 45;
pokedex[121].basedef = 65;
pokedex[121].basespatk = 100;
pokedex[121].basespdef = 120;
pokedex[121].basespeed = 90;
pokedex[121].growthmod = 11;
pokedex[121].expyield = 11;
pokedex[121].evolveat = 11;
pokedex[121].evolveto = 11;
pokedex[121].type1 = "Psychic";
pokedex[121].type2 = "None";
pokedex[121].typeint1 = 11;
pokedex[121].typeint2 = 0;
pokedex[121].move1 = movedex[36];
pokedex[121].move2 = movedex[11];
pokedex[121].move3 = movedex[58];
pokedex[121].move4 = movedex[43];
pokedex[122].name = "Scyther";
pokedex[122].basehp = 70;
pokedex[122].baseatk = 110;
pokedex[122].basedef = 80;
pokedex[122].basespatk = 55;
pokedex[122].basespdef = 80;
pokedex[122].basespeed = 105;
pokedex[122].growthmod = 11;
pokedex[122].expyield = 11;
pokedex[122].evolveat = 11;
pokedex[122].evolveto = 11;
pokedex[122].type1 = "Bug";
pokedex[122].type2 = "Flying";
pokedex[122].typeint1 = 12;
pokedex[122].typeint2 = 10;
pokedex[122].move1 = movedex[50];
pokedex[122].move2 = movedex[46];
pokedex[122].move3 = movedex[40];
pokedex[122].move4 = movedex[25];
pokedex[123].name = "Jynx";
pokedex[123].basehp = 65;
pokedex[123].baseatk = 50;
pokedex[123].basedef = 35;
pokedex[123].basespatk = 115;
pokedex[123].basespdef = 95;
pokedex[123].basespeed = 95;
pokedex[123].growthmod = 11;
pokedex[123].expyield = 11;
pokedex[123].evolveat = 11;
pokedex[123].evolveto = 11;
pokedex[123].type1 = "Psychic";
pokedex[123].type2 = "Ice";
pokedex[123].typeint1 = 11;
pokedex[123].typeint2 = 6;
pokedex[123].move1 = movedex[36];
pokedex[123].move2 = movedex[34];
pokedex[123].move3 = movedex[49];
pokedex[123].move4 = movedex[62];
pokedex[124].name = "Electabuzz";
pokedex[124].basehp = 65;
pokedex[124].baseatk = 83;
pokedex[124].basedef = 57;
pokedex[124].basespatk = 95;
pokedex[124].basespdef = 85;
pokedex[124].basespeed = 105;
pokedex[124].growthmod = 11;
pokedex[124].expyield = 11;
pokedex[124].evolveat = 11;
pokedex[124].evolveto = 11;
pokedex[124].type1 = "Electric";
pokedex[124].type2 = "None";
pokedex[124].typeint1 = 4;
pokedex[124].typeint2 = 0;
pokedex[124].move1 = movedex[65];
pokedex[124].move2 = movedex[43];
pokedex[124].move3 = movedex[16];
pokedex[124].move4 = movedex[86];
pokedex[125].name = "Magmar";
pokedex[125].basehp = 65;
pokedex[125].baseatk = 95;
pokedex[125].basedef = 57;
pokedex[125].basespatk = 100;
pokedex[125].basespdef = 85;
pokedex[125].basespeed = 93;
pokedex[125].growthmod = 11;
pokedex[125].expyield = 11;
pokedex[125].evolveat = 11;
pokedex[125].evolveto = 11;
pokedex[125].type1 = "Fire";
pokedex[125].type2 = "None";
pokedex[125].typeint1 = 2;
pokedex[125].typeint2 = 0;
pokedex[125].move1 = movedex[33];
pokedex[125].move2 = movedex[16];
pokedex[125].move3 = movedex[65];
pokedex[125].move4 = movedex[87];
pokedex[126].name = "Pinsir";
pokedex[126].basehp = 65;
pokedex[126].baseatk = 125;
pokedex[126].basedef = 100;
pokedex[126].basespatk = 55;
pokedex[126].basespdef = 70;
pokedex[126].basespeed = 85;
pokedex[126].growthmod = 11;
pokedex[126].expyield = 11;
pokedex[126].evolveat = 11;
pokedex[126].evolveto = 11;
pokedex[126].type1 = "Bug";
pokedex[126].type2 = "None";
pokedex[126].typeint1 = 12;
pokedex[126].typeint2 = 0;
pokedex[126].move1 = movedex[40];
pokedex[126].move2 = movedex[50];
pokedex[126].move3 = movedex[30];
pokedex[126].move4 = movedex[25];
pokedex[127].name = "Tauros";
pokedex[127].basehp = 75;
pokedex[127].baseatk = 100;
pokedex[127].basedef = 95;
pokedex[127].basespatk = 40;
pokedex[127].basespdef = 70;
pokedex[127].basespeed = 110;
pokedex[127].growthmod = 11;
pokedex[127].expyield = 11;
pokedex[127].evolveat = 11;
pokedex[127].evolveto = 11;
pokedex[127].type1 = "Normal";
pokedex[127].type2 = "None";
pokedex[127].typeint1 = 1;
pokedex[127].typeint2 = 0;
pokedex[127].move1 = movedex[25];
pokedex[127].move2 = movedex[30];
pokedex[127].move3 = movedex[34];
pokedex[127].move4 = movedex[74];
pokedex[129].name = "Gyarados";
pokedex[129].basehp = 95;
pokedex[129].baseatk = 125;
pokedex[129].basedef = 79;
pokedex[129].basespatk = 60;
pokedex[129].basespdef = 100;
pokedex[129].basespeed = 81;
pokedex[129].growthmod = 11;
pokedex[129].expyield = 11;
pokedex[129].evolveat = 11;
pokedex[129].evolveto = 11;
pokedex[129].type1 = "Water";
pokedex[129].type2 = "Flying";
pokedex[129].typeint1 = 3;
pokedex[129].typeint2 = 10;
pokedex[129].move1 = movedex[27];
pokedex[129].move2 = movedex[34];
pokedex[129].move3 = movedex[47];
pokedex[129].move4 = movedex[30];
pokedex[130].name = "Lapras";
pokedex[130].basehp = 130;
pokedex[130].baseatk = 85;
pokedex[130].basedef = 80;
pokedex[130].basespatk = 85;
pokedex[130].basespdef = 95;
pokedex[130].basespeed = 60;
pokedex[130].growthmod = 11;
pokedex[130].expyield = 11;
pokedex[130].evolveat = 11;
pokedex[130].evolveto = 11;
pokedex[130].type1 = "Water";
pokedex[130].type2 = "Ice";
pokedex[130].typeint1 = 3;
pokedex[130].typeint2 = 6;
pokedex[130].move1 = movedex[27];
pokedex[130].move2 = movedex[34];
pokedex[130].move3 = movedex[36];
pokedex[130].move4 = movedex[43];
pokedex[133].name = "Vaporeon";
pokedex[133].basehp = 130;
pokedex[133].baseatk = 65;
pokedex[133].basedef = 60;
pokedex[133].basespatk = 110;
pokedex[133].basespdef = 95;
pokedex[133].basespeed = 65;
pokedex[133].growthmod = 11;
pokedex[133].expyield = 11;
pokedex[133].evolveat = 11;
pokedex[133].evolveto = 11;
pokedex[133].type1 = "Water";
pokedex[133].type2 = "None";
pokedex[133].typeint1 = 3;
pokedex[133].typeint2 = 0;
pokedex[133].move1 = movedex[27];
pokedex[133].move2 = movedex[34];
pokedex[133].move3 = movedex[6];
pokedex[133].move4 = movedex[72];
pokedex[134].name = "Jolteon";
pokedex[134].basehp = 65;
pokedex[134].baseatk = 65;
pokedex[134].basedef = 60;
pokedex[134].basespatk = 110;
pokedex[134].basespdef = 95;
pokedex[134].basespeed = 130;
pokedex[134].growthmod = 11;
pokedex[134].expyield = 11;
pokedex[134].evolveat = 11;
pokedex[134].evolveto = 11;
pokedex[134].type1 = "Electric";
pokedex[134].type2 = "None";
pokedex[134].typeint1 = 4;
pokedex[134].typeint2 = 0;
pokedex[134].move1 = movedex[43];
pokedex[134].move2 = movedex[44];
pokedex[134].move3 = movedex[48];
pokedex[134].move4 = movedex[62];
pokedex[135].name = "Flareon";
pokedex[135].basehp = 65;
pokedex[135].baseatk = 130;
pokedex[135].basedef = 60;
pokedex[135].basespatk = 95;
pokedex[135].basespdef = 110;
pokedex[135].basespeed = 65;
pokedex[135].growthmod = 11;
pokedex[135].expyield = 11;
pokedex[135].evolveat = 11;
pokedex[135].evolveto = 11;
pokedex[135].type1 = "Fire";
pokedex[135].type2 = "None";
pokedex[135].typeint1 = 2;
pokedex[135].typeint2 = 0;
pokedex[135].move1 = movedex[87];
pokedex[135].move2 = movedex[25];
pokedex[135].move3 = movedex[81];
pokedex[135].move4 = movedex[33];
pokedex[136].name = "Porygon";
pokedex[136].basehp = 65;
pokedex[136].baseatk = 60;
pokedex[136].basedef = 70;
pokedex[136].basespatk = 85;
pokedex[136].basespdef = 75;
pokedex[136].basespeed = 40;
pokedex[136].growthmod = 11;
pokedex[136].expyield = 11;
pokedex[136].evolveat = 11;
pokedex[136].evolveto = 11;
pokedex[136].type1 = "Normal";
pokedex[136].type2 = "None";
pokedex[136].typeint1 = 1;
pokedex[136].typeint2 = 0;
pokedex[136].move1 = movedex[15];
pokedex[136].move2 = movedex[48];
pokedex[136].move3 = movedex[25];
pokedex[136].move4 = movedex[36];
pokedex[138].name = "Omastar";
pokedex[138].basehp = 70;
pokedex[138].baseatk = 60;
pokedex[138].basedef = 125;
pokedex[138].basespatk = 115;
pokedex[138].basespdef = 70;
pokedex[138].basespeed = 55;
pokedex[138].growthmod = 11;
pokedex[138].expyield = 11;
pokedex[138].evolveat = 11;
pokedex[138].evolveto = 11;
pokedex[138].type1 = "Water";
pokedex[138].type2 = "Rock";
pokedex[138].typeint1 = 3;
pokedex[138].typeint2 = 13;
pokedex[138].move1 = movedex[27];
pokedex[138].move2 = movedex[74];
pokedex[138].move3 = movedex[15];
pokedex[138].move4 = movedex[75];
pokedex[140].name = "Kabutops";
pokedex[140].basehp = 60;
pokedex[140].baseatk = 115;
pokedex[140].basedef = 105;
pokedex[140].basespatk = 65;
pokedex[140].basespdef = 70;
pokedex[140].basespeed = 80;
pokedex[140].growthmod = 11;
pokedex[140].expyield = 11;
pokedex[140].evolveat = 11;
pokedex[140].evolveto = 11;
pokedex[140].type1 = "Water";
pokedex[140].type2 = "Rock";
pokedex[140].typeint1 = 3;
pokedex[140].typeint2 = 13;
pokedex[140].move1 = movedex[85];
pokedex[140].move2 = movedex[74];
pokedex[140].move3 = movedex[50];
pokedex[140].move4 = movedex[75];
pokedex[141].name = "Aerodactyl";
pokedex[141].basehp = 80;
pokedex[141].baseatk = 105;
pokedex[141].basedef = 65;
pokedex[141].basespatk = 60;
pokedex[141].basespdef = 75;
pokedex[141].basespeed = 130;
pokedex[141].growthmod = 11;
pokedex[141].expyield = 11;
pokedex[141].evolveat = 11;
pokedex[141].evolveto = 11;
pokedex[141].type1 = "Rock";
pokedex[141].type2 = "Flying";
pokedex[141].typeint1 = 13;
pokedex[141].typeint2 = 10;
pokedex[141].move1 = movedex[74];
pokedex[141].move2 = movedex[30];
pokedex[141].move3 = movedex[88];
pokedex[141].move4 = movedex[47];
pokedex[142].name = "Snorlax";
pokedex[142].basehp = 160;
pokedex[142].baseatk = 110;
pokedex[142].basedef = 65;
pokedex[142].basespatk = 65;
pokedex[142].basespdef = 110;
pokedex[142].basespeed = 30;
pokedex[142].growthmod = 11;
pokedex[142].expyield = 11;
pokedex[142].evolveat = 11;
pokedex[142].evolveto = 11;
pokedex[142].type1 = "Normal";
pokedex[142].type2 = "None";
pokedex[142].typeint1 = 1;
pokedex[142].typeint2 = 0;
pokedex[142].move1 = movedex[16];
pokedex[142].move2 = movedex[89];
pokedex[142].move3 = movedex[72];
pokedex[142].move4 = movedex[47];
pokedex[143].name = "Articuno";
pokedex[143].basehp = 90;
pokedex[143].baseatk = 85;
pokedex[143].basedef = 100;
pokedex[143].basespatk = 95;
pokedex[143].basespdef = 125;
pokedex[143].basespeed = 85;
pokedex[143].growthmod = 11;
pokedex[143].expyield = 11;
pokedex[143].evolveat = 11;
pokedex[143].evolveto = 11;
pokedex[143].type1 = "Ice";
pokedex[143].type2 = "Flying";
pokedex[143].typeint1 = 6;
pokedex[143].typeint2 = 10;
pokedex[143].move1 = movedex[15];
pokedex[143].move2 = movedex[73];
pokedex[143].move3 = movedex[42];
pokedex[143].move4 = movedex[31];
pokedex[144].name = "Zapdos";
pokedex[144].basehp = 90;
pokedex[144].baseatk = 90;
pokedex[144].basedef = 85;
pokedex[144].basespatk = 125;
pokedex[144].basespdef = 90;
pokedex[144].basespeed = 100;
pokedex[144].growthmod = 11;
pokedex[144].expyield = 11;
pokedex[144].evolveat = 11;
pokedex[144].evolveto = 11;
pokedex[144].type1 = "Electric";
pokedex[144].type2 = "Flying";
pokedex[144].typeint1 = 4;
pokedex[144].typeint2 = 10;
pokedex[144].move1 = movedex[45];
pokedex[144].move2 = movedex[43];
pokedex[144].move3 = movedex[42];
pokedex[144].move4 = movedex[90];
pokedex[145].name = "Moltres";
pokedex[145].basehp = 90;
pokedex[145].baseatk = 100;
pokedex[145].basedef = 90;
pokedex[145].basespatk = 125;
pokedex[145].basespdef = 85;
pokedex[145].basespeed = 90;
pokedex[145].growthmod = 11;
pokedex[145].expyield = 11;
pokedex[145].evolveat = 11;
pokedex[145].evolveto = 11;
pokedex[145].type1 = "Fire";
pokedex[145].type2 = "Flying";
pokedex[145].typeint1 = 2;
pokedex[145].typeint2 = 10;
pokedex[145].move1 = movedex[33];
pokedex[145].move2 = movedex[42];
pokedex[145].move3 = movedex[32];
pokedex[145].move4 = movedex[81];
pokedex[148].name = "Dragonite";
pokedex[148].basehp = 91;
pokedex[148].baseatk = 134;
pokedex[148].basedef = 95;
pokedex[148].basespatk = 100;
pokedex[148].basespdef = 100;
pokedex[148].basespeed = 80;
pokedex[148].growthmod = 11;
pokedex[148].expyield = 11;
pokedex[148].evolveat = 11;
pokedex[148].evolveto = 11;
pokedex[148].type1 = "Dragon";
pokedex[148].type2 = "Flying";
pokedex[148].typeint1 = 15;
pokedex[148].typeint2 = 10;
pokedex[148].move1 = movedex[84];
pokedex[148].move2 = movedex[88];
pokedex[148].move3 = movedex[30];
pokedex[148].move4 = movedex[60];
pokedex[149].name = "Mewtwo";
pokedex[149].basehp = 106;
pokedex[149].baseatk = 110;
pokedex[149].basedef = 90;
pokedex[149].basespatk = 154;
pokedex[149].basespdef = 90;
pokedex[149].basespeed = 130;
pokedex[149].growthmod = 11;
pokedex[149].expyield = 11;
pokedex[149].evolveat = 11;
pokedex[149].evolveto = 11;
pokedex[149].type1 = "Psychic";
pokedex[149].type2 = "None";
pokedex[149].typeint1 = 11;
pokedex[149].typeint2 = 0;
pokedex[149].move1 = movedex[58];
pokedex[149].move2 = movedex[36];
pokedex[149].move3 = movedex[43];
pokedex[149].move4 = movedex[34];
pokedex[150].name = "Mew";
pokedex[150].basehp = 100;
pokedex[150].baseatk = 100;
pokedex[150].basedef = 100;
pokedex[150].basespatk = 100;
pokedex[150].basespdef = 100;
pokedex[150].basespeed = 100;
pokedex[150].growthmod = 11;
pokedex[150].expyield = 11;
pokedex[150].evolveat = 11;
pokedex[150].evolveto = 11;
pokedex[150].type1 = "Psychic";
pokedex[150].type2 = "None";
pokedex[150].typeint1 = 11;
pokedex[150].typeint2 = 0;
pokedex[150].move1 = movedex[49];
pokedex[150].move2 = movedex[63];
pokedex[150].move3 = movedex[36];
pokedex[150].move4 = movedex[33];
//assign type strings to integers, then initialize typechart doublearray int typeeffectiveness[17][17]---------------------------------------------------------------------------------------------
//no type 0
//normal 1
//fire 2
//water 3
//electric 4
//grass 5
//ice 6
//fighting 7
//poison 8
//ground 9
//flying 10
//psychic 11
//bug 12
//rock 13
//ghost 14
//dragon 15
//dark 16
//steel 17
//typechart[attackingtype][defendingtype] is how this works
//format for typechart will be integer from 0 thru 4. 0 is no effect, 1 not very effective, 2 normal, 4 super effective
// int typechart[18][18]; //seventeen types plus null type at 0
typechart[0][0] = 2;
typechart[0][1] = 2;
typechart[0][2] = 2;
typechart[0][3] = 2;
typechart[0][4] = 2;
typechart[0][4] = 2;
typechart[0][5] = 2;
typechart[0][6] = 2;
typechart[0][7] = 2;
typechart[0][8] = 2;
typechart[0][9] = 2;
typechart[0][10] = 2;
typechart[0][11] = 2;
typechart[0][12] = 2;
typechart[0][13] = 2;
typechart[0][14] = 2;
typechart[0][15] = 2;
typechart[0][16] = 2;
typechart[0][17] = 2;
typechart[1][0] = 2;
typechart[2][0] = 2;
typechart[3][0] = 2;
typechart[4][0] = 2;
typechart[5][0] = 2;
typechart[6][0] = 2;
typechart[7][0] = 2;
typechart[8][0] = 2;
typechart[9][0] = 2;
typechart[10][0] = 2;
typechart[11][0] = 2;
typechart[12][0] = 2;
typechart[13][0] = 2;
typechart[14][0] = 2;
typechart[15][0] = 2;
typechart[16][0] = 2;
typechart[17][0] = 2;
typechart[1][1] = 2;
typechart[1][2] = 2;
typechart[1][3] = 2;
typechart[1][4] = 2;
typechart[1][5] = 2;
typechart[1][6] = 2;
typechart[1][7] = 2;
typechart[1][8] = 2;
typechart[1][9] = 2;
typechart[1][10] = 2;
typechart[1][11] = 2;
typechart[1][12] = 2;
typechart[1][13] = 1;
typechart[1][14] = 0;
typechart[1][15] = 2;
typechart[1][16] = 2;
typechart[1][17] = 1;
typechart[2][1] = 2;
typechart[2][2] = 1;
typechart[2][3] = 1;
typechart[2][4] = 2;
typechart[2][5] = 4;
typechart[2][6] = 4;
typechart[2][7] = 2;
typechart[2][8] = 2;
typechart[2][9] = 2;
typechart[2][10] = 2;
typechart[2][11] = 2;
typechart[2][12] = 4;
typechart[2][13] = 1;
typechart[2][14] = 2;
typechart[2][15] = 1;
typechart[2][16] = 2;
typechart[2][17] = 4;
typechart[3][1] = 2;
typechart[3][2] = 4;
typechart[3][3] = 1;
typechart[3][4] = 2;
typechart[3][5] = 1;
typechart[3][6] = 2;
typechart[3][7] = 2;
typechart[3][8] = 2;
typechart[3][9] = 4;
typechart[3][10] = 2;
typechart[3][11] = 2;
typechart[3][12] = 2;
typechart[3][13] = 4;
typechart[3][14] = 2;
typechart[3][15] = 1;
typechart[3][16] = 2;
typechart[3][17] = 2;
typechart[4][1] = 2;
typechart[4][2] = 2;
typechart[4][3] = 4;
typechart[4][4] = 1;
typechart[4][5] = 1;
typechart[4][6] = 2;
typechart[4][7] = 2;
typechart[4][8] = 2;
typechart[4][9] = 0;
typechart[4][10] = 4;
typechart[4][11] = 2;
typechart[4][12] = 2;
typechart[4][13] = 2;
typechart[4][14] = 2;
typechart[4][15] = 1;
typechart[4][16] = 2;
typechart[4][17] = 2;
typechart[5][1] = 2;
typechart[5][2] = 1;
typechart[5][3] = 4;
typechart[5][4] = 2;
typechart[5][5] = 1;
typechart[5][6] = 2;
typechart[5][7] = 2;
typechart[5][8] = 1;
typechart[5][9] = 4;
typechart[5][10] = 1;
typechart[5][11] = 2;
typechart[5][12] = 1;
typechart[5][13] = 4;
typechart[5][14] = 2;
typechart[5][15] = 1;
typechart[5][16] = 2;
typechart[5][17] = 1;
typechart[6][1] = 2;
typechart[6][2] = 1;
typechart[6][3] = 1;
typechart[6][4] = 2;
typechart[6][5] = 4;
typechart[6][6] = 1;
typechart[6][7] = 2;
typechart[6][8] = 2;
typechart[6][9] = 4;
typechart[6][10] = 4;
typechart[6][11] = 2;
typechart[6][12] = 2;
typechart[6][13] = 2;
typechart[6][14] = 2;
typechart[6][15] = 4;
typechart[6][16] = 2;
typechart[6][17] = 1;
typechart[7][1] = 4;
typechart[7][2] = 2;
typechart[7][3] = 2;
typechart[7][4] = 2;
typechart[7][5] = 2;
typechart[7][6] = 4;
typechart[7][7] = 2;
typechart[7][8] = 1;
typechart[7][9] = 2;
typechart[7][10] = 1;
typechart[7][11] = 1;
typechart[7][12] = 1;
typechart[7][13] = 4;
typechart[7][14] = 0;
typechart[7][15] = 2;
typechart[7][16] = 4;
typechart[7][17] = 4;
typechart[8][1] = 2;
typechart[8][2] = 2;
typechart[8][3] = 2;
typechart[8][4] = 2;
typechart[8][5] = 4;
typechart[8][6] = 2;
typechart[8][7] = 2;
typechart[8][8] = 1;
typechart[8][9] = 1;
typechart[8][10] = 2;
typechart[8][11] = 2;
typechart[8][12] = 2;
typechart[8][13] = 1;
typechart[8][14] = 1;
typechart[8][15] = 2;
typechart[8][16] = 2;
typechart[8][17] = 0;
typechart[9][1] = 2;
typechart[9][2] = 4;
typechart[9][3] = 2;
typechart[9][4] = 4;
typechart[9][5] = 1;
typechart[9][6] = 2;
typechart[9][7] = 2;
typechart[9][8] = 4;
typechart[9][9] = 2;
typechart[9][10] = 0;
typechart[9][11] = 2;
typechart[9][12] = 1;
typechart[9][13] = 4;
typechart[9][14] = 2;
typechart[9][15] = 2;
typechart[9][16] = 2;
typechart[9][17] = 4;
typechart[10][1] = 2;
typechart[10][2] = 2;
typechart[10][3] = 2;
typechart[10][4] = 1;
typechart[10][5] = 4;
typechart[10][6] = 2;
typechart[10][7] = 4;
typechart[10][8] = 2;
typechart[10][9] = 2;
typechart[10][10] = 2;
typechart[10][11] = 2;
typechart[10][12] = 4;
typechart[10][13] = 1;
typechart[10][14] = 2;
typechart[10][15] = 2;
typechart[10][16] = 2;
typechart[10][17] = 1;
typechart[11][1] = 2;
typechart[11][2] = 2;
typechart[11][3] = 2;
typechart[11][4] = 2;
typechart[11][5] = 2;
typechart[11][6] = 2;
typechart[11][7] = 4;
typechart[11][8] = 4;
typechart[11][9] = 2;
typechart[11][10] = 2;
typechart[11][11] = 1;
typechart[11][12] = 2;
typechart[11][13] = 2;
typechart[11][14] = 2;
typechart[11][15] = 2;
typechart[11][16] = 0;
typechart[11][17] = 1;
typechart[12][1] = 2;
typechart[12][2] = 1;
typechart[12][3] = 2;
typechart[12][4] = 2;
typechart[12][5] = 4;
typechart[12][6] = 2;
typechart[12][7] = 1;
typechart[12][8] = 1;
typechart[12][9] = 2;
typechart[12][10] = 1;
typechart[12][11] = 4;
typechart[12][12] = 2;
typechart[12][13] = 2;
typechart[12][14] = 1;
typechart[12][15] = 2;
typechart[12][16] = 4;
typechart[12][17] = 1;
typechart[13][1] = 2;
typechart[13][2] = 4;
typechart[13][3] = 2;
typechart[13][4] = 2;
typechart[13][5] = 2;
typechart[13][6] = 4;
typechart[13][7] = 1;
typechart[13][8] = 2;
typechart[13][9] = 1;
typechart[13][10] = 4;
typechart[13][11] = 2;
typechart[13][12] = 4;
typechart[13][13] = 2;
typechart[13][14] = 2;
typechart[13][15] = 2;
typechart[13][16] = 2;
typechart[13][17] = 1;
typechart[14][1] = 0;
typechart[14][2] = 2;
typechart[14][3] = 2;
typechart[14][4] = 2;
typechart[14][5] = 2;
typechart[14][6] = 2;
typechart[14][7] = 2;
typechart[14][8] = 2;
typechart[14][9] = 2;
typechart[14][10] = 2;
typechart[14][11] = 4;
typechart[14][12] = 2;
typechart[14][13] = 2;
typechart[14][14] = 4;
typechart[14][15] = 2;
typechart[14][16] = 1;
typechart[14][17] = 1;
typechart[15][1] = 2;
typechart[15][2] = 2;
typechart[15][3] = 2;
typechart[15][4] = 2;
typechart[15][5] = 2;
typechart[15][6] = 2;
typechart[15][7] = 2;
typechart[15][8] = 2;
typechart[15][9] = 2;
typechart[15][10] = 2;
typechart[15][11] = 2;
typechart[15][12] = 2;
typechart[15][13] = 2;
typechart[15][14] = 2;
typechart[15][15] = 4;
typechart[15][16] = 2;
typechart[15][17] = 1;
typechart[16][1] = 2;
typechart[16][2] = 2;
typechart[16][3] = 2;
typechart[16][4] = 2;
typechart[16][5] = 2;
typechart[16][6] = 2;
typechart[16][7] = 1;
typechart[16][8] = 2;
typechart[16][9] = 2;
typechart[16][10] = 2;
typechart[16][11] = 4;
typechart[16][12] = 2;
typechart[16][13] = 2;
typechart[16][14] = 4;
typechart[16][15] = 2;
typechart[16][16] = 1;
typechart[16][17] = 1;
typechart[17][1] = 2;
typechart[17][2] = 1;
typechart[17][3] = 1;
typechart[17][4] = 1;
typechart[17][5] = 2;
typechart[17][6] = 4;
typechart[17][7] = 2;
typechart[17][8] = 2;
typechart[17][9] = 2;
typechart[17][10] = 2;
typechart[17][11] = 2;
typechart[17][12] = 2;
typechart[17][13] = 4;
typechart[17][14] = 2;
typechart[17][15] = 2;
typechart[17][16] = 2;
typechart[17][17] = 1;
//user has choice of pokemon-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//allow user to select 3 dex numbers of mons they'd like to battle with--------------------------------------------------------------------------
printf("Please pick 3 Pokemon to use by entering their names.\n");
userselection1();
userselection2();
userselection3();
///string pickurmon1 = get_string("1st mon");
///for i=0 i<151; i++
/// if (pickurmon == pokedex[i].name)
int urmons[3];
urmons[0] = *urmon1ptr; //minus 1 cuz index starts at 0. bulba is 0, if they enter 1, they get bulba
urmons[1] = *urmon2ptr;
urmons[2] = *urmon3ptr;
for (int i = 0; i < 3; i++) //party initialization!!!!!
{
party[i].dexno = urmons[i]; //inherits minus 1, dexno should be correct
party[i].name = pokedex[party[i].dexno].name;
//nickname
party[i].xp = 100;
party[i].growthmod = 4;
party[i].lvl = 50; //all lvl 50 here, use formula based off xp for a responsive lvl
//party[i].maxhp = pokedex[party[i].dexno].basehp * party[i].lvl / 10; //hp
party[i].maxhp = ( (31 + 2 * pokedex[party[i].dexno].basehp) * party[i].lvl / 100) + 10 + party[i].lvl; //formulae for stats in formulas.txt
party[i].currenthp = party[i].maxhp; //all stats assume 31 ivs, no evs, no nature.
//party[i].atk = pokedex[party[i].dexno].baseatk * party[i].lvl; //atk
party[i].atk = (((31 + 2 * pokedex[party[i].dexno].baseatk ) * party[i].lvl / 100 ) + 5 ); //atk
party[i].def = (((31 + 2 * pokedex[party[i].dexno].basedef ) * party[i].lvl / 100 ) + 5 ); //def
party[i].spatk = (((31 + 2 * pokedex[party[i].dexno].basespatk ) * party[i].lvl / 100 ) + 5 ); //spatk
party[i].spdef = (((31 + 2 * pokedex[party[i].dexno].basespdef ) * party[i].lvl / 100 ) + 5 ); //spdef
party[i].speed = (((31 + 2 * pokedex[party[i].dexno].basespeed ) * party[i].lvl / 100 ) + 5 ); //speed
party[i].typeint1 = pokedex[party[i].dexno].typeint1;
party[i].typeint2 = pokedex[party[i].dexno].typeint2;
party[i].status = "Healthy";
party[i].statusint = 0;
party[i].statusintpointer = &party[i].statusint;
party[i].move1 = pokedex[party[i].dexno].move1;
party[i].move2 = pokedex[party[i].dexno].move2;
party[i].move3 = pokedex[party[i].dexno].move3;
party[i].move4 = pokedex[party[i].dexno].move4;
}
//allow user to pick 3 opposing monsters---------------------------------------------------------------------------------------------------------
printf("\nPlease pick three Pokemon to fight against by entering their names.\n");
foeselection1();
foeselection2();
foeselection3();
int theirmons[3];
theirmons[0] = *theirmon1ptr;
theirmons[1] = *theirmon2ptr;
theirmons[2] = *theirmon3ptr;
for (int i = 0; i < 3; i++) //opposing party initialization!!!
{
foeparty[i].dexno = theirmons[i];
foeparty[i].name = pokedex[foeparty[i].dexno].name;
//nickname
foeparty[i].xp = 100;
foeparty[i].growthmod = 4;
foeparty[i].lvl = 50; //use better leveling function
//foeparty[i].maxhp = pokedex[foeparty[i].dexno].basehp * foeparty[i].lvl / 10; //we need better stat calcs overall. hp
foeparty[i].maxhp = ( (31 + 2 * pokedex[foeparty[i].dexno].basehp) * foeparty[i].lvl / 100) + 10 + foeparty[i].lvl;
foeparty[i].currenthp = foeparty[i].maxhp;
foeparty[i].atk = (((31 + 2 * pokedex[foeparty[i].dexno].baseatk ) * foeparty[i].lvl / 100 ) + 5 ); //atk
foeparty[i].def = (((31 + 2 * pokedex[foeparty[i].dexno].basedef ) * foeparty[i].lvl / 100 ) + 5 ); //def
foeparty[i].spatk = (((31 + 2 * pokedex[foeparty[i].dexno].basespatk ) * foeparty[i].lvl / 100 ) + 5 ); //spatk
foeparty[i].spdef = (((31 + 2 * pokedex[foeparty[i].dexno].basespdef ) * foeparty[i].lvl / 100 ) + 5 ); //spdef
foeparty[i].speed = (((31 + 2 * pokedex[foeparty[i].dexno].basespeed ) * foeparty[i].lvl / 100 ) + 5 ); //speed
foeparty[i].typeint1 = pokedex[foeparty[i].dexno].typeint1;
foeparty[i].typeint2 = pokedex[foeparty[i].dexno].typeint2;
foeparty[i].status = "Healthy";
foeparty[i].statusint = 0;
foeparty[i].statusintpointer = &foeparty[i].statusint;
foeparty[i].move1 = pokedex[foeparty[i].dexno].move1;
foeparty[i].move2 = pokedex[foeparty[i].dexno].move2;
foeparty[i].move3 = pokedex[foeparty[i].dexno].move3;
foeparty[i].move4 = pokedex[foeparty[i].dexno].move4;
}
//now set combatants[2] as the first monsters in the player's and foe's parties-----------------------------------------------------------------------------------------------------------------------
//first our guy----------------------------------------------------------------------------------------------------------------------------------
combatants[0].individualdata = party[0];
combatants[0].dexnumber = party[0].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[0].nickname;
combatants[0].atkmod = 0; // combatants[0].hp = combatants[0].individualdata.currenthp
combatants[0].defmod = 0; //combatants[0].type1 = pokedex[ dexnumber ].type1
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = "Healthy";
combatants[0].statusint = 0;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None"; //if this is hyperbeam, cant move. if this is sky attack or skull bash, cant move. same with dig and fly
combatants[0].invulnerable = 0; //protect, fly, dig
combatants[0].caughtinwrap = 0; //if theyre being wrapped or fire spun. subtract 1/16 hp and print "user is caught in foe's attack!"
combatants[0].cursed = 0;
combatants[0].biding = 0; //0 if not biding, 1 if biding
combatants[0].bidedamagetracker = 0; // if pokemon is biding, track damage it recieves
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0; //set to 2 or 3 when poke uses thrash or petal dance. decrease each turn. when it hits 0, confuse the user
combatants[0].whichpartymemberami = 0;
*combatspeedpointer = party[combatants[0].whichpartymemberami].speed;
moveset[0] = combatants[0].individualdata.move1;
moveset[1] = combatants[0].individualdata.move2;
moveset[2] = combatants[0].individualdata.move3;
moveset[3] = combatants[0].individualdata.move4;
//next their guy---------------------------------------------------------------------------------------------------------------------------------
combatants[1].individualdata = foeparty[0];
combatants[1].dexnumber = foeparty[0].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[1].nickname = foeparty[0].nickname;
combatants[1].atkmod = 0; // combatants[0].hp = combatants[0].individualdata.currenthp
combatants[1].defmod = 0; //combatants[0].type1 = pokedex[ dexnumber ].type1
combatants[1].spatkmod = 0;
combatants[1].spdefmod = 0;
combatants[1].speedmod = 0;
combatants[1].evasionmod = 0;
combatants[1].accuracymod = 0;
combatants[1].protectcounter = 0;
combatants[1].status = "Healthy";
combatants[1].statusint = 0;
combatants[1].confused = 0;
combatants[1].disabled = 0;
combatants[1].toxiccounter = 0;
combatants[1].leechseeded = 0;
combatants[1].flinched = 0;
combatants[1].substitute = 0;
combatants[1].substitutehp = 0;
combatants[1].hyperskyskull = "None"; //if this is hyperbeam, cant move. if this is sky attack or skull bash, cant move. same with dig and fly
combatants[1].invulnerable = 0; //protect, fly, dig
combatants[1].caughtinwrap = 0; //if theyre being wrapped or fire spun. subtract 1/16 hp and print "user is caught in foe's attack!"
combatants[1].cursed = 0;
combatants[1].biding = 0; //0 if not biding, 1 if biding one turn 2 if bidin 2
combatants[1].bidedamagetracker = 0; // if pokemon is biding, track damage it recieves
combatants[1].countering = 0;
combatants[1].counterdamagetracker = 0;
combatants[1].thrashcounter = 0; //set to 2 or 3 when poke uses thrash or petal dance. decrease each turn. when it hits 0, confuse the user
combatants[1].whichpartymemberami = 0;
*foecombatspeedpointer = foeparty[combatants[1].whichpartymemberami].speed;
foemoveset[0] = combatants[1].individualdata.move1;
foemoveset[1] = combatants[1].individualdata.move2;
foemoveset[2] = combatants[1].individualdata.move3;
foemoveset[3] = combatants[1].individualdata.move4;
//ok below here is the main battle loop----------------------------------------------------------------------------------------------------------------------------------------------------------------
//*****************************************************************************************************************************************************************************************************
//*****************************************************************************************************************************************************************************************************
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
printf("\n\nBATTLE START! \n%s, LV %i vs %s, LV %i \n", pokedex[ party[0].dexno ].name, party[0].lvl, pokedex[ foeparty[0].dexno ].name, foeparty[0].lvl);
while (*isoverpointer == 0) //while the "is the battle over?" integer hasn't been flipped to 1...
{
string option = get_string("\nEnter:\nA to attack\nE to escape\nS to switch\nP for party stats\n"); //this is where string option comes from
//we aren't swtching. query will change this is we choose to switch
if (*loopcountpointer == 0)
{
*userswitchpointer = 0;
}
*loopcountpointer = *loopcountpointer + 1;
query(option, combatants[0]); //query() calls fight(), which calls attack() and deplate(). attack returns int d, damage, deplete manipulates the hp stat of defending pokemon according to damage and prevents from dropping below zero, fight calls deplete and attack to deal damage, and if hp is zero fight ends the battle
//printf("DEBUGDEBUGDEBUG\n");
if (*runpointer == 1) //if u ran away, end encounter
return 0;
if (*isoverpointer == 1) //if all pkmn has hit 0 hp, end encounter
//get exp
//level recalc. stat recalc. end battle
return 0;
foequery(combatants[1]); //asks opposition what they want (they always attack for now)
*foefaint = 0; //reset these
*userfaint = 0;
if (*runpointer == 1) //same as above but this time check durign the opponents turn
return 0;
if (*isoverpointer == 1)
//get exp
//level recalc. stat recalc. end battle
return 0;
//now SPEED AND PRIORITY CHECK---------------------------------------------------------------------------------------------------------------
if (bothmoves[0].movechoice.priority > bothmoves[1].movechoice.priority) //IF USER PRIORITY GREATR--
{
//printf("priority user@@@@@@@\n");
if (*userswitchpointer == 0) //if we havent switched:
{
int kill = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
//now check foe hp. if 0, switch foe mon, return 0
if (*foefaint == 1)
{
//do end of turn stuff
//load combatants[1]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
int srvv = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
}
}
else if (bothmoves[0].movechoice.priority < bothmoves[1].movechoice.priority) //IF FOE PRIORITY GREATER--
{
//printf("priority ai@@@@@@@@\n");
int kill = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
//now check foe hp. if 0, switch foe mon, return 0
if (*userfaint == 1)
{
//do end of turn stuff
//load combatants[0]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
if (*userswitchpointer == 0)
{
int srvv = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
int fiiilllll = 0;
}
}
else //IF PRIORITY IS TIED:::--------------------------------------------------------------
{ //IF USER FASTER:----------------------------------------------------------------------
if ( (*combatspeedpointer * speedchange(bothmoves[0].attacker.speedmod, bothmoves[0].attacker.statusint) ) > (*foecombatspeedpointer * speedchange(bothmoves[0].defender.speedmod, bothmoves[0].defender.statusint) ))
{
//printf("speed user@@@@@@@\n");
if (*userswitchpointer == 0)
{
int kill = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
//problem! if kill, other mon is sent in and kill resets to 1, so other mon moves
if (*foefaint == 1)
{
//do end of turn stuff
//load combatants[1]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
int srvv = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
}
}
//ELSE IF FOE IS FASTER
else if ( (*combatspeedpointer * speedchange(bothmoves[0].attacker.speedmod, bothmoves[0].attacker.statusint) ) < (*foecombatspeedpointer * speedchange(bothmoves[0].defender.speedmod, bothmoves[0].defender.statusint) ))
{
int kill = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
//now check foe hp. if 0, switch foe mon, return 0
if (*userfaint == 1)
{
//do end of turn stuff
//load combatants[0]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
if (*userswitchpointer == 0)
{
int srvv = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
int fiiilllll = 0;
}
}
////
else //ELSE IF SPEED TIE----------------------------------
{
//printf("speed ai@@@@@@@@@");
int movefirst = 1 + rand() % 100;
if (movefirst > 50) //if heads, they move first
{
int kill = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
//now check foe hp. if 0, switch foe mon, return 0
if (*userfaint == 1)
{
//do end of turn stuff
//load combatants[0]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
if (*userswitchpointer == 0)
{
int srvv = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
}
}
else //else if tails u move first
{
if (*userswitchpointer == 0) //if u didnt use this turn to switch u get to fight
{
int kill = fight(bothmoves[0].movechoice, bothmoves[0].STAB, bothmoves[0].attacker, bothmoves[0].defender);
}
if (*foefaint == 1)
{
//do end of turn stuff
//load combatants[1]
int fillll = 0;
}
else //if foe hp didn't hit zero, they get to fight
{
int srvv = foefight(bothmoves[1].movechoice, bothmoves[1].STAB, bothmoves[1].attacker, bothmoves[1].defender);
}
}
}
}
*userswitchpointer = 0;
// end of turn stuff-------------------------------------------------------------------------------------------------------------------------
int healthymons = 0; //check if the foe's pokemon are still alive--------------------------
for (int i = 0; i < 3; i ++)
{
if (foeparty[i].currenthp != 0)
{
healthymons++;
}
}
if (healthymons == 0) //if they aint, it's all over kid
{
*isoverpointer = 1;
printf("\nYou won the battle!\n");
return 0;
}
healthymons = 0; //check if your pokemon are still alive-----------------------------------
for (int i = 0; i < 3; i ++)
{
if (party[i].currenthp != 0)
{
healthymons++;
}
}
if (healthymons == 0) //if they aint, it's all over kid
{
*isoverpointer = 1;
printf("You lost the battle!\n");
return 0;
}
//now specific stuff, first BURN DAMAGE----------------------------------------------------
if (party[ combatants[0].whichpartymemberami ].statusint == 1) //if you are burned
{
printf("\n%s is hurt by it's burn!\n", party[ combatants[0].whichpartymemberami ].name);
int burndamage = (party[ combatants[0].whichpartymemberami ].maxhp / 8);
int finhp = foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, burndamage, party[ combatants[0].whichpartymemberami ]);
}
if (foeparty[ combatants[1].whichpartymemberami ].statusint == 1) //if foe is burned. this check doesnt work????
{
printf("\n%s is hurt by it's burn!\n", foeparty[ combatants[1].whichpartymemberami ].name);
int burndamage = (foeparty[ combatants[1].whichpartymemberami ].maxhp / 8);
int finhp = deplete(&foeparty[ combatants[1].whichpartymemberami ].currenthp, burndamage, foeparty[ combatants[1].whichpartymemberami ]);
}
//-----------------------------------------------------------------------------------------
if (party[ combatants[0].whichpartymemberami ].statusint == 4) //if ur poisoned or toxicd
{
printf("\n%s is hurt by poison!\n", party[ combatants[0].whichpartymemberami ].name);
int psndamage = ((1 + combatants[0].toxiccounter) * party[ combatants[0].whichpartymemberami ].maxhp / 16);
int finhp = foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, psndamage, party[ combatants[0].whichpartymemberami ]);
}
if (foeparty[ combatants[1].whichpartymemberami ].statusint == 4) //if theyre poisoned or toxicd
{
printf("\n%s is hurt by poison!\n", foeparty[ combatants[1].whichpartymemberami ].name);
int psndamage = ((1 + combatants[1].toxiccounter) * foeparty[ combatants[1].whichpartymemberami ].maxhp / 16);
int finhp = deplete(&foeparty[ combatants[1].whichpartymemberami ].currenthp, psndamage, foeparty[ combatants[1].whichpartymemberami ]);
}
if (combatants[1].toxiccounter > 0) //increase toxic counter if toxicd
{
combatants[1].toxiccounter += 1;
}
if (combatants[0].toxiccounter > 0)
{
combatants[0].toxiccounter += 1;
}
//----------------------------
if (combatants[0].flinched == 1) //resolves flinch
{
combatants[0].flinched = 0;
}
if (combatants[1].flinched == 1)
{
combatants[1].flinched = 0;
}
//////////////////
//if either finhp has reached zero cuz of burns or whatever, wee neeeed to send out a new mon.
//if (foeparty[ combatants[1].whichpartymemberami ].currenthp <= 0)
//if (party[combatants[0].whichpartymemberami].currenthp <= 0) //THIS ONE IS BUGGY. evenwhen hp not zero it goes into this block. maybe the info isnt getting updated in between battle cycles? maybe combatants[0] isnt updated properly?
//int please = combatants[0].individualdata.currenthp;
//if (combatants[0].individualdata.currenthp <= 0)
if (party[combatants[0].whichpartymemberami].statusint == 1 || party[combatants[0].whichpartymemberami].statusint == 4 )
{
if (*combathppointer <= 0) //this death check is for deaths due to toxic and burning
{
*userfaint = 1;
printf("\nYour Pokemon fainted!\n");
party[ combatants[0].whichpartymemberami ].status = "Fainted";
party[ combatants[0].whichpartymemberami ].statusint = 6;
healthymons = 0; //counts number of non-fainted monsters
for (int i = 0; i < 3; i ++)
{
if (party[i].currenthp != 0)
{
healthymons++;
}
}
if (healthymons == 0) //if they're all fainted, it's all over kid
{
*isoverpointer = 1;
printf("You've been defeated!\n");
return 2;
}
else //if theyre not all fainted, pick from one that's not
{
*isoverpointer = 0; //battle isnt over
printf("\nWhich party member woud you like to switch to?\n");
for (int i = 0; i < 3; i++) //list party members that aren't on the field
{
if (combatants[0].whichpartymemberami != i && party[i].currenthp != 0) //if not mon thats out and not mon that has 0hp
{
printf("Press %i to switch to %s, lv%i\n", i, party[i].name, party[i].lvl);
}
else
{
int filllerrr = 32;
}
}
int whichmem = combatants[0].whichpartymemberami; //just a contraction
int choice; //declaration for a do while
do //ask player which party member to switch to
{
choice = get_int("Type choice and press enter:\n");
}while(choice == combatants[0].whichpartymemberami || choice < 0 || choice > 3);
//ok here i need to keep status. currenthp uses pointers to party/foeparty so should already be updated
party[whichmem].status = combatants[0].status;
party[whichmem].statusint = combatants[0].statusint;
//alright now i need to load party[choice] into combatants[0]
combatants[0].individualdata = party[choice];
combatants[0].dexnumber = party[choice].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[choice].nickname;
combatants[0].atkmod = 0;
combatants[0].defmod = 0;
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = party[choice].status;
combatants[0].statusint = party[choice].statusint;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None";
combatants[0].invulnerable = 0;
combatants[0].caughtinwrap = 0;
combatants[0].cursed = 0;
combatants[0].biding = 0;
combatants[0].bidedamagetracker = 0;
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0;
combatants[0].whichpartymemberami = choice;
party[combatants[0].whichpartymemberami].currenthp = party[choice].currenthp;
*combathppointer = party[choice].currenthp;
*combatspeedpointer = party[choice].speed;
//no userswitchpointer here, this is end of turn switching cuz of toxic or burn
*userfaint = 0;
printf("\nCome back, %s. Go, %s!\n", party[whichmem].name, party[choice].name);
}
}
}
if (foeparty[combatants[1].whichpartymemberami].statusint == 1 || foeparty[combatants[1].whichpartymemberami].statusint == 4)
{
if (*foecombathppointer <= 0)
{
printf("\nThe opposing Pokemon fainted!\n");
foeparty[ combatants[1].whichpartymemberami ].status = "Fainted";
foeparty[ combatants[1].whichpartymemberami ].statusint = 6;
*foefaint = 1;
//check if all opposing mons are fainted
int airandomswitch = -1;
healthymons = 0;
for (int i = 0; i < 3; i ++)
{
if (foeparty[i].statusint != 6)
{
healthymons++;
}
}
if (healthymons == 0) //if they are, it's all over kid
{
*isoverpointer = 1;
printf("\nYou defeated all enemy Pokemon!");
return 0;
}
else //if not all fainted, ai sends out random not-fainted mon
{
*isoverpointer = 0;
do
{
airandomswitch = rand() % 3;
}while(foeparty[ airandomswitch ].statusint == 6);
}
//fill out combatants with new mon
combatants[1].individualdata = foeparty[airandomswitch];
combatants[1].dexnumber = foeparty[airandomswitch].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[1].nickname = foeparty[airandomswitch].nickname;
combatants[1].atkmod = 0;
combatants[1].defmod = 0;
combatants[1].spatkmod = 0;
combatants[1].spdefmod = 0;
combatants[1].speedmod = 0;
combatants[1].evasionmod = 0;
combatants[1].accuracymod = 0;
combatants[1].protectcounter = 0;
combatants[1].status = foeparty[airandomswitch].status;
combatants[1].statusint = foeparty[airandomswitch].statusint;
combatants[1].confused = 0;
combatants[1].disabled = 0;
combatants[1].toxiccounter = 0;
combatants[1].leechseeded = 0;
combatants[1].flinched = 0;
combatants[1].substitute = 0;
combatants[1].substitutehp = 0;
combatants[1].hyperskyskull = "None";
combatants[1].invulnerable = 0;
combatants[1].caughtinwrap = 0;
combatants[1].cursed = 0;
combatants[1].biding = 0;
combatants[1].bidedamagetracker = 0;
combatants[1].countering = 0;
combatants[1].counterdamagetracker = 0;
combatants[1].thrashcounter = 0;
combatants[1].whichpartymemberami = airandomswitch;
printf("Foe sent out %s!\n\n", foeparty[airandomswitch].name);
*foecombathppointer = foeparty[airandomswitch].currenthp;
*foecombatspeedpointer = foeparty[airandomswitch].speed;
}
}
//////////////
//do end of turn stuff
}
}
//end of battle loop-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//*****************************************************************************************************************************************************************************************************
//*****************************************************************************************************************************************************************************************************
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//down here function definitions-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
int query(string option, struct combatmon ourfighter)
{
if (strcmp(option, "A") == 0) //if u pressed a for fight
{
int whichmove = 1;
int STAB = 2;
printf("\nPress:\n");
printf("1 for %s\n", ourfighter.individualdata.move1.name);
printf("2 for %s\n", ourfighter.individualdata.move2.name);
printf("3 for %s\n", ourfighter.individualdata.move3.name);
printf("4 for %s\n", ourfighter.individualdata.move4.name);
do{
whichmove = get_int("Enter move selection and press return.\n");
}while(whichmove > 4 || whichmove < 1);
struct move ourset[4];
ourset[0] = ourfighter.individualdata.move1;
ourset[1] = ourfighter.individualdata.move2;
ourset[2] = ourfighter.individualdata.move3;
ourset[3] = ourfighter.individualdata.move4;
struct move chosenmove = ourset[ whichmove - 1];
if (ourfighter.individualdata.typeint1 == chosenmove.typeint)
STAB = 3;
else if (ourfighter.individualdata.typeint2 == chosenmove.typeint)
STAB = 3;
else
STAB = 2;
// printf("\n\n%s used %s!\n", combatants[0].individualdata.name, chosenmove.name);
bothmoves[0].movechoice = chosenmove; //here is the moveselection struct
bothmoves[0].STAB = STAB;
bothmoves[0].attacker = combatants[0];
bothmoves[0].defender = combatants[1];
// fight(chosenmove, STAB, combatants[0], combatants[1]); //add as argument movestruct //############# take fight out of query so u can do speed checks then decide who fights first
return 1;
}
else if (strcmp(option, "a") == 0) //if u pressed a for fight
{
int whichmove = 1;
int STAB = 2;
printf("\nPress:\n");
printf("1 for %s\n", ourfighter.individualdata.move1.name);
printf("2 for %s\n", ourfighter.individualdata.move2.name);
printf("3 for %s\n", ourfighter.individualdata.move3.name);
printf("4 for %s\n", ourfighter.individualdata.move4.name);
do{
whichmove = get_int("Enter move selection and press return.\n");
}while(whichmove > 4 || whichmove < 1);
struct move ourset[4];
ourset[0] = ourfighter.individualdata.move1;
ourset[1] = ourfighter.individualdata.move2;
ourset[2] = ourfighter.individualdata.move3;
ourset[3] = ourfighter.individualdata.move4;
struct move chosenmove = ourset[ whichmove - 1];
if (ourfighter.individualdata.typeint1 == chosenmove.typeint)
STAB = 3;
else if (ourfighter.individualdata.typeint2 == chosenmove.typeint)
STAB = 3;
else
STAB = 2;
// printf("\n\n%s used %s!\n", combatants[0].individualdata.name, chosenmove.name);
bothmoves[0].movechoice = chosenmove; //here is the moveselection struct
bothmoves[0].STAB = STAB;
bothmoves[0].attacker = combatants[0];
bothmoves[0].defender = combatants[1];
// fight(chosenmove, STAB, combatants[0], combatants[1]); //add as argument movestruct //############# take fight out of query so u can do speed checks then decide who fights first
return 1;
}
else if (strcmp(option, "E") == 0) //else if u pressed e for escape
{
printf("\nYou got away safely!\n");
*runpointer = 1;
return 2;
}
else if (strcmp(option, "e") == 0) //else if u pressed e for escape
{
printf("\nYou got away safely!\n");
*runpointer = 1;
return 2;
}
else if (strcmp(option, "S") == 0) //else if u pressed s to switch
{
printf("\nWhich party member woud you like to switch to?\n");
for (int i = 0; i < 3; i++) //list party members that aren't on the field
{
if (combatants[0].whichpartymemberami != i && party[i].currenthp != 0) //if not mon thats out and not mon that has 0hp
{
printf("Press %i to switch to %s, lv%i\n", i, party[i].name, party[i].lvl);
}
else
{
int filllerrr = 32;
}
}
int whichmem = combatants[0].whichpartymemberami; //just a contraction
int choice; //declaration for a do while
do //ask player which party member to switch to
{
choice = get_int("Type choice and press enter:\n");
}while(choice == combatants[0].whichpartymemberami || choice < 0 || choice > 3);
//ok here i need to keep status. currenthp uses pointers to party/foeparty so should already be updated
party[whichmem].status = combatants[0].status;
party[whichmem].statusint = combatants[0].statusint;
//alright now i need to load party[choice] into combatants[0]
combatants[0].individualdata = party[choice];
combatants[0].dexnumber = party[choice].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[choice].nickname;
combatants[0].atkmod = 0;
combatants[0].defmod = 0;
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = party[choice].status;
combatants[0].statusint = party[choice].statusint;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None";
combatants[0].invulnerable = 0;
combatants[0].caughtinwrap = 0;
combatants[0].cursed = 0;
combatants[0].biding = 0;
combatants[0].bidedamagetracker = 0;
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0;
combatants[0].whichpartymemberami = choice;
//printf("choice is %i\n", choice);
//printf("combatants[0].whichpartymemberami = %i\n", combatants[0].whichpartymemberami);
party[combatants[0].whichpartymemberami].currenthp = party[choice].currenthp;
*combathppointer = party[choice].currenthp;
*combatspeedpointer = party[choice].speed;
//printf("current hp of party[choice] is %i\n", party[choice].currenthp);
//printf("party[combatants[0].whichpartymemberami].currenthp = %i\n", party[combatants[0].whichpartymemberami].currenthp);
*userswitchpointer = 1;
*userfaint = 0;
printf("\nCome back, %s. Go, %s!\n", party[whichmem].name, party[choice].name);
return 2;
}
else if (strcmp(option, "s") == 0) //else if u pressed s to switch
{
printf("\nWhich party member would you like to switch to?\n");
for (int i = 0; i < 3; i++) //list party members that aren't on the field
{
if (combatants[0].whichpartymemberami != i && party[i].currenthp != 0) //if not mon thats out and not mon that has 0hp
{
printf("Press %i to switch to %s, lv%i\n", i, party[i].name, party[i].lvl);
}
else
{
int filllerrr = 32;
}
}
int whichmem = combatants[0].whichpartymemberami; //just a contraction
int choice; //declaration for a do while
do //ask player which party member to switch to
{
choice = get_int("Type choice and press enter:\n");
}while(choice == combatants[0].whichpartymemberami || choice < 0 || choice > 3);
//ok here i need to keep status. currenthp uses pointers to party/foeparty so should already be updated
party[whichmem].status = combatants[0].status;
party[whichmem].statusint = combatants[0].statusint;
//alright now i need to load party[choice] into combatants[0]
combatants[0].individualdata = party[choice];
combatants[0].dexnumber = party[choice].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[choice].nickname;
combatants[0].atkmod = 0;
combatants[0].defmod = 0;
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = party[choice].status;
combatants[0].statusint = party[choice].statusint;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None";
combatants[0].invulnerable = 0;
combatants[0].caughtinwrap = 0;
combatants[0].cursed = 0;
combatants[0].biding = 0;
combatants[0].bidedamagetracker = 0;
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0;
combatants[0].whichpartymemberami = choice;
//printf("choice is %i\n", choice);
//printf("combatants[0].whichpartymemberami = %i\n", combatants[0].whichpartymemberami);
party[combatants[0].whichpartymemberami].currenthp = party[choice].currenthp;
*combathppointer = party[choice].currenthp;
*combatspeedpointer = party[choice].speed;
//printf("current hp of party[choice] is %i\n", party[choice].currenthp);
//printf("party[combatants[0].whichpartymemberami].currenthp = %i\n", party[combatants[0].whichpartymemberami].currenthp);
*userswitchpointer = 1;
*userfaint = 0;
printf("\nCome back, %s. Go, %s!\n", party[whichmem].name, party[choice].name);
return 2;
}
// else if stcmp optiooon is P then print out their party stats, moves, status
else if (strcmp(option, "P") == 0) //if u pressed P for party
{
printf("\n\n");
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[0].name, party[0].currenthp, party[0].maxhp, statinttostring(party[0].statusint), party[0].move1.name, party[0].move2.name, party[0].move3.name, party[0].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[0].atk, party[0].def, party[0].spatk, party[0].spdef, party[0].speed);
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[1].name, party[1].currenthp, party[1].maxhp, statinttostring(party[1].statusint), party[1].move1.name, party[1].move2.name, party[1].move3.name, party[1].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[1].atk, party[1].def, party[1].spatk, party[1].spdef, party[1].speed);
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[2].name, party[2].currenthp, party[2].maxhp, statinttostring(party[2].statusint), party[2].move1.name, party[2].move2.name, party[2].move3.name, party[2].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[2].atk, party[2].def, party[2].spatk, party[2].spdef, party[2].speed);
option = get_string("\nEnter:\nA to attack\nE to escape\nS to switch\nP for party stats\n\n");
query(option, ourfighter); //looooook its recursion B) if you request party stats, you query again
}
else if (strcmp(option, "p") == 0) //if u pressed P for party
{
printf("\n\n");
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[0].name, party[0].currenthp, party[0].maxhp, statinttostring(party[0].statusint), party[0].move1.name, party[0].move2.name, party[0].move3.name, party[0].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[0].atk, party[0].def, party[0].spatk, party[0].spdef, party[0].speed);
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[1].name, party[1].currenthp, party[1].maxhp, statinttostring(party[1].statusint), party[1].move1.name, party[1].move2.name, party[1].move3.name, party[1].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[1].atk, party[1].def, party[1].spatk, party[1].spdef, party[1].speed);
printf("%s Lv 50, HP: %i/%i, Status: %s\n%s, %s, %s, %s\n", party[2].name, party[2].currenthp, party[2].maxhp, statinttostring(party[2].statusint), party[2].move1.name, party[2].move2.name, party[2].move3.name, party[2].move4.name);
printf("ATTACK: %i, DEFENSE: %i, SPECIAL ATK: %i, SPECIAL DEF: %i, SPEED: %i\n\n", party[2].atk, party[2].def, party[2].spatk, party[2].spdef, party[2].speed);
option = get_string("\nEnter:\nA to attack\nE to escape\nS to switch\nP for party stats\n\n");
query(option, ourfighter); //looooook its recursion B) if you request party stats, you query again
}
else //note, if you don't input A or E or S then you return 3, but pikachu still attacks you that turn. use this to test ur own poke fainting
{
printf("Input not recognized.\n");
option = get_string("\nEnter:\nA to attack\nE to escape\nS to switch\nP for party stats\n");
query(option, ourfighter);
}
return 69;
}
int foequery(struct combatmon theirfighter)
{
int STAB = 2;
int randy = rand() % 4;
struct move theirset[4];
theirset[0] = theirfighter.individualdata.move1;
theirset[1] = theirfighter.individualdata.move2;
theirset[2] = theirfighter.individualdata.move3;
theirset[3] = theirfighter.individualdata.move4;
struct move chosenmove = theirset[ randy ];
if (theirfighter.individualdata.typeint1 == chosenmove.typeint)
STAB = 3;
else if (theirfighter.individualdata.typeint2 == chosenmove.typeint)
STAB = 3;
else
STAB = 2;
// printf("\n\n%s used %s!\n", theirfighter.individualdata.name, chosenmove.name);
bothmoves[1].movechoice = chosenmove; //heres the moveselection struct
bothmoves[1].STAB = STAB;
bothmoves[1].attacker = combatants[1];
bothmoves[1].defender = combatants[0];
// foefight(chosenmove, STAB, combatants[1], combatants[0]);
return 1;
}
int fight(struct move moveused, int STAB, struct combatmon attacker, struct combatmon defender) //ties attack and deplete functions together. u hurting foe
{
printf("\n\nYour %s used %s!\n", combatants[0].individualdata.name, moveused.name);
int dmg = attack(attacker, defender, moveused, STAB);
int eighth = dmg / 8;
//if attack is a status move,
// do statusmove(attacker, defender, moveused)
// return 1
// remember to check who the target of the move is!
/////////////////////////////////////////////////
if (moveused.attackorstatus == 1) //if its a status move
{
if (strcmp(moveused.effect, "Rest") == 0) //if it's rest
{
party[ combatants[0].whichpartymemberami].statusint = 3;
party[ combatants[0].whichpartymemberami].currenthp = party[ combatants[0].whichpartymemberami].maxhp;
deplete(&party[ combatants[0].whichpartymemberami].currenthp, -1000, party[combatants[0].whichpartymemberami]);
printf("%s went to sleep and became healthy!\n", party[ combatants[0].whichpartymemberami].name);
return 15;
}
else if (strcmp(moveused.effect, "Restore") == 0) //if its a recovery move
{
int half = -1 * party[ combatants[0].whichpartymemberami].maxhp / 2;
printf("HP was restored!\n");
deplete(&party[ combatants[0].whichpartymemberami].currenthp, half, party[combatants[0].whichpartymemberami]);
return 15;
}
else if (strcmp(moveused.effect, "Paralyze") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
foeparty[ combatants[1].whichpartymemberami].statusint = 5;
printf("The opposing Pokemon was paralyzed!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Poison") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
foeparty[ combatants[1].whichpartymemberami].statusint = 4;
printf("The opposing Pokemon was poisoned!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Toxic") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
foeparty[ combatants[1].whichpartymemberami].statusint = 4;
if (combatants[1].toxiccounter < 1)
{
combatants[1].toxiccounter = 1;
}
printf("The opposing Pokemon was badly poisoned!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Sleep") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
foeparty[ combatants[1].whichpartymemberami].statusint = 3;
printf("The opposing Pokemon fell asleep!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Confuse") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
combatants[1].confused = 1;
printf("The opposing Pokemon was confused!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "+atk+speed") == 0)
{
combatants[0].atkmod += 1;
combatants[0].speedmod += 1;
printf("Attack and speed rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+atk+def") == 0)
{
combatants[0].atkmod += 1;
combatants[0].defmod += 1;
printf("Attack and defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+spatk+spdef") == 0)
{
combatants[0].spatkmod += 1;
combatants[0].spdefmod += 1;
printf("Special attack and special defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2spdef") == 0)
{
combatants[0].spdefmod += 1;
combatants[0].spdefmod += 1;
printf("Special defense rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2spatk") == 0)
{
combatants[0].spatkmod += 1;
combatants[0].spatkmod += 1;
printf("Special attack rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2speed") == 0)
{
combatants[0].speedmod += 1;
combatants[0].speedmod += 1;
printf("Speed rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+def") == 0)
{
combatants[0].defmod += 1;
printf("Defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2def") == 0)
{
combatants[0].defmod += 1;
combatants[0].defmod += 1;
printf("Defense rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2atk") == 0)
{
combatants[0].atkmod += 1;
combatants[0].atkmod += 1;
printf("Attack rose sharply!\n");
return 17;
}
else
{
printf("The move failed!\n");
return 18;
}
}
/////////////////////////////////////////////////////
//add conditional here that checks for confuse, flinch, sleep, freeze, paralyze, etc to see if you get to move
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (party[combatants[0].whichpartymemberami].statusint == 2) //if you're frozen, roll 30%chancce of unfreezing
{
int unfreeze = 1 + rand() % 10;
if (unfreeze > 7) //if they unfreeze
{
printf("%s was unfrozen!\n", combatants[0].individualdata.name);
attacker.individualdata.statusint = 0;
party[combatants[0].whichpartymemberami].statusint = 0;
}
else //if they dont
{
printf("%s is frozen solid!\n", combatants[0].individualdata.name);
return 11;
}
}
if (combatants[0].confused == 1) //if confused
{
printf("%s is confused!\n", combatants[0].individualdata.name);
int hiturself = 1 + rand() % 10;
int unconfuse = 1 + rand() % 10;
if (unconfuse >= 6) //if they snap out of confusion
{
attacker.confused = 0;
printf("%s snapped out of confusion!\n", combatants[0].individualdata.name);
hiturself = 1;
}
if (hiturself >= 7) //if hit self in confusion, return
{
printf("%s hurt itself in confusion!\n", combatants[0].individualdata.name);
foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, eighth, attacker.individualdata);
return 12;
} //else, just continue function
}
if (combatants[0].flinched == 1) //if flinched
{
printf("... unfortunately, %s flinched and it's attack failed!\n", combatants[0].individualdata.name);
attacker.flinched = 0;
return 13;
}
if (party[combatants[0].whichpartymemberami].statusint == 3) //if you're asleep, roll 30% chancce of waking up
{
int unfreeze = 1 + rand() % 10;
if (unfreeze > 7) //if they wake up
{
printf("%s woke up!\n", combatants[0].individualdata.name);
attacker.individualdata.statusint = 0;
party[combatants[0].whichpartymemberami].statusint = 0;
}
else //if they dont
{
printf("... but %s is fast asleep!\n", combatants[0].individualdata.name);
return 11;
}
}
if (party[combatants[0].whichpartymemberami].statusint == 5) //if you're paralyzed, roll 30% chancce of no move
{
//printf("%s is paralyzed!\n", combatants[0].individualdata.name);
int unfreeze = 1 + rand() % 10; //if they paralyzed
if (unfreeze > 7)
{
printf("%s can't move because of paralysis!\n", combatants[0].individualdata.name);
return 14;
}//if not, continue with turn as usual
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int recorsucc = (-1 * moveused.recoilordrain * dmg / 8);
if (moveused.recoilordrain != 0) //if recoil like double edge or absorption like giga drain
{
int urhp = foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, recorsucc, attacker.individualdata);
if (*combathppointer <= 0)
{
*userfaint = 1;
printf("\nYour Pokemon fainted!\n");
party[ combatants[0].whichpartymemberami ].status = "Fainted";
party[ combatants[0].whichpartymemberami ].statusint = 6;
int healthymons = 0; //counts number of non-fainted monsters
for (int i = 0; i < 3; i ++)
{
if (party[i].currenthp != 0)
{
healthymons++;
}
}
if (healthymons == 0) //if they're all fainted, it's all over kid
{
*isoverpointer = 1;
printf("You've been defeated!\n");
return 2;
}
else //if theyre not all fainted, pick from one that's not
{
*isoverpointer = 0; //battle isnt over
printf("\nWhich party member woud you like to switch to?\n");
for (int i = 0; i < 3; i++) //list party members that aren't on the field
{
if (combatants[0].whichpartymemberami != i && party[i].currenthp != 0) //if not mon thats out and not mon that has 0hp
{
printf("Press %i to switch to %s, lv%i\n", i, party[i].name, party[i].lvl);
}
else
{
int filllerrr = 32;
}
}
int whichmem = combatants[0].whichpartymemberami; //just a contraction
int choice; //declaration for a do while
do //ask player which party member to switch to
{
choice = get_int("Type choice and press enter:\n");
}while(choice == combatants[0].whichpartymemberami || choice < 0 || choice > 3);
//ok here i need to keep status. currenthp uses pointers to party/foeparty so should already be updated
party[whichmem].status = combatants[0].status;
party[whichmem].statusint = combatants[0].statusint;
//alright now i need to load party[choice] into combatants[0]
combatants[0].individualdata = party[choice];
combatants[0].dexnumber = party[choice].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[choice].nickname;
combatants[0].atkmod = 0;
combatants[0].defmod = 0;
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = party[choice].status;
combatants[0].statusint = party[choice].statusint;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None";
combatants[0].invulnerable = 0;
combatants[0].caughtinwrap = 0;
combatants[0].cursed = 0;
combatants[0].biding = 0;
combatants[0].bidedamagetracker = 0;
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0;
combatants[0].whichpartymemberami = choice;
party[combatants[0].whichpartymemberami].currenthp = party[choice].currenthp;
*combathppointer = party[choice].currenthp;
*combatspeedpointer = party[choice].speed;
*userswitchpointer = 1;
*userfaint = 0;
printf("\nCome back, %s. Go, %s!\n", party[whichmem].name, party[choice].name);
}
}
//if ur hp hits 0
}
//if moveused.attackorstatus == 0;
int finhp = deplete(&foeparty[ combatants[1].whichpartymemberami ].currenthp, dmg, defender.individualdata);
//else
//run status checks. strcmp if moveused.effect == "Burn" or if it == -spdef etc
//
//+2atk, +2def, +speed, +2speed, +2spatk, +2spdef, +spatk+spdef, +atk+def, +atk+speed, confuse, toxic, sleep, poison, paralyze, restore, rest,
////////////////////////////////////////////////////////////////////////
//below are secondary effect checks
if (moveused.effectchance != 0 && dmg > 0) //if theres an effect chance, and the attack dealt damage
{
if (strcmp(moveused.effect, "Burn") == 0) //if effect is burn
{
if (defender.individualdata.statusint == 0) //and theyre healthy
{
int rollchanceb = 1 + rand() % 100;
if (rollchanceb < moveused.effectchance)
{
defender.individualdata.statusint = 1; //burn them //THIS LINE DOESNT WORK
foeparty[ combatants[1].whichpartymemberami ].statusint = 1; //THIS LINE DOES IDK WHY
printf("%s was burned!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Poison") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancep = 1 + rand() % 100;
if (rollchancep < moveused.effectchance)
{
defender.individualdata.statusint = 4;
foeparty[ combatants[1].whichpartymemberami ].statusint = 4;
printf("%s was poisoned!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Toxic") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancet = 1 + rand() % 100;
if (rollchancet < moveused.effectchance)
{
defender.individualdata.statusint = 4;
foeparty[ combatants[1].whichpartymemberami ].statusint = 4;
printf("%s was badly poisoned!\n", defender.individualdata.name);
combatants[1].toxiccounter = 1;
defender.toxiccounter = 1;
}
}
}
else if (strcmp(moveused.effect, "Freeze") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancef = 1 + rand() % 100;
if (rollchancef < moveused.effectchance)
{
defender.individualdata.statusint = 2;
foeparty[ combatants[1].whichpartymemberami ].statusint = 2;
printf("%s was frozen solid!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Paralyze") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancepz = 1 + rand() % 100;
if (rollchancepz < moveused.effectchance)
{
defender.individualdata.statusint = 5;
foeparty[ combatants[1].whichpartymemberami ].statusint = 5;
printf("%s was paralyzed!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Sleep") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchances = 1 + rand() % 100;
if (rollchances < moveused.effectchance)
{
defender.individualdata.statusint = 3;
foeparty[ combatants[1].whichpartymemberami ].statusint = 3;
printf("%s fell asleep!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "-spdef") == 0)
{
int rollspdef = 1 + rand() % 100;
if (rollspdef < moveused.effectchance)
{
defender.spdefmod = defender.spdefmod - 1;
combatants[1].spdefmod = combatants[1].spdefmod - 1;
printf("%s had it's special defense lowered!\n", defender.individualdata.name);
if (defender.spdefmod < -6)
{
defender.spdefmod = -6;
}
}
}
else if (strcmp(moveused.effect, "-def") == 0)
{
int rolldef = 1 + rand() % 100;
if (rolldef < moveused.effectchance)
{
defender.defmod = defender.defmod - 1;
combatants[1].defmod = combatants[1].defmod - 1;
printf("%s had it's defense lowered!\n", defender.individualdata.name);
if (defender.defmod < -6)
{
defender.defmod = -6;
}
}
}
else if (strcmp(moveused.effect, "-atk") == 0)
{
int rollatk = 1 + rand() % 100;
if (rollatk < moveused.effectchance)
{
defender.atkmod = defender.atkmod - 1;
combatants[1].atkmod = combatants[1].atkmod - 1;
printf("%s had it's attack lowered!\n", defender.individualdata.name);
if (defender.atkmod < -6)
{
defender.atkmod = -6;
}
}
}
else if (strcmp(moveused.effect, "Flinch") == 0)
{
int rollflinch = 1 + rand() % 100;
if (rollflinch < moveused.effectchance)
{
defender.flinched = 1;
combatants[1].flinched = 1;
}
}
else if (strcmp(moveused.effect, "Confuse") == 0)
{
int rollcon = 1 + rand() % 100;
if (rollcon < moveused.effectchance)
{
defender.confused = 1;
combatants[1].confused = 1;
printf("%s became confused!\n", defender.individualdata.name);
}
}
}
//we're still inside the fight() function lol
////////////////////////////////////////////////////////
if (*foecombathppointer <= 0) //
{
printf("\nThe opposing Pokemon fainted!\n");
foeparty[ combatants[1].whichpartymemberami ].status = "Fainted";
foeparty[ combatants[1].whichpartymemberami ].statusint = 6;
*foefaint = 1;
//check if all opposing mons are fainted
int airandomswitch = -1;
int healthymons = 0;
for (int i = 0; i < 3; i ++)
{
if (foeparty[i].statusint != 6)
{
healthymons++;
}
}
if (healthymons == 0) //if they are, it's all over kid
{
*isoverpointer = 1;
printf("\nYou defeated all enemy Pokemon!");
return 0;
}
else //if not all fainted, ai sends out random not-fainted mon
{
*isoverpointer = 0;
do
{
airandomswitch = rand() % 3;
}while(foeparty[ airandomswitch ].statusint == 6);
}
//fill out combatants with new mon
combatants[1].individualdata = foeparty[airandomswitch];
combatants[1].dexnumber = foeparty[airandomswitch].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[1].nickname = foeparty[airandomswitch].nickname;
combatants[1].atkmod = 0;
combatants[1].defmod = 0;
combatants[1].spatkmod = 0;
combatants[1].spdefmod = 0;
combatants[1].speedmod = 0;
combatants[1].evasionmod = 0;
combatants[1].accuracymod = 0;
combatants[1].protectcounter = 0;
combatants[1].status = foeparty[airandomswitch].status;
combatants[1].statusint = foeparty[airandomswitch].statusint;
combatants[1].confused = 0;
combatants[1].disabled = 0;
combatants[1].toxiccounter = 0;
combatants[1].leechseeded = 0;
combatants[1].flinched = 0;
combatants[1].substitute = 0;
combatants[1].substitutehp = 0;
combatants[1].hyperskyskull = "None";
combatants[1].invulnerable = 0;
combatants[1].caughtinwrap = 0;
combatants[1].cursed = 0;
combatants[1].biding = 0;
combatants[1].bidedamagetracker = 0;
combatants[1].countering = 0;
combatants[1].counterdamagetracker = 0;
combatants[1].thrashcounter = 0;
combatants[1].whichpartymemberami = airandomswitch;
printf("Foe sent out %s!\n\n", foeparty[airandomswitch].name);
*foecombathppointer = foeparty[airandomswitch].currenthp;
*foecombatspeedpointer = foeparty[airandomswitch].speed;
}
//do checks for non-major status effect of moves.
//like -spdef, of confusion, or flinching
//endoffight() bookmark
return 1;
}
int foefight(struct move moveused, int STAB, struct combatmon attacker, struct combatmon defender) //ties attack and deplete functions together. foe hurting u
{ //add conditional here that checks for confuse, flinch, sleep, freeze, paralyze, etc to see if they get to move
printf("\n\nFoe's %s used %s!\n", attacker.individualdata.name, moveused.name);
int dmg = foeattack(attacker, defender, moveused, STAB);
int eighth = dmg / 8;
//if attack is a status move,
// do statusmove(attacker, defender, moveused)
// return 1
///////////////////////////////////////////////////////////////////////////////////////////////
if (moveused.attackorstatus == 1) //if its a status move
{
if (strcmp(moveused.effect, "Rest") == 0) //if it's rest
{
foeparty[ combatants[1].whichpartymemberami].statusint = 3;
foeparty[ combatants[1].whichpartymemberami].currenthp = foeparty[ combatants[1].whichpartymemberami].maxhp;
deplete(&foeparty[ combatants[1].whichpartymemberami].currenthp, -1000, foeparty[combatants[1].whichpartymemberami]);
printf("%s went to sleep and became healthy!\n", foeparty[ combatants[1].whichpartymemberami].name);
return 15;
}
else if (strcmp(moveused.effect, "Restore") == 0) //if its a recovery move
{
int half = -1 * foeparty[ combatants[1].whichpartymemberami].maxhp / 2;
printf("HP was restored!\n");
deplete(&foeparty[ combatants[1].whichpartymemberami].currenthp, half, foeparty[combatants[1].whichpartymemberami]);
return 15;
}
else if (strcmp(moveused.effect, "Paralyze") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
party[ combatants[0].whichpartymemberami].statusint = 5;
printf("Your Pokemon was paralyzed!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Poison") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
party[ combatants[0].whichpartymemberami].statusint = 4;
printf("Your Pokemon was poisoned!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Toxic") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
party[ combatants[0].whichpartymemberami].statusint = 4;
if (combatants[0].toxiccounter < 1)
{
combatants[0].toxiccounter = 1;
}
printf("Your Pokemon was badly poisoned!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Sleep") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
party[ combatants[0].whichpartymemberami].statusint = 3;
printf("Your Pokemon fell asleep!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "Confuse") == 0)
{
int didithit = 1 + rand() % 100;
if (didithit < moveused.acc)
{
combatants[0].confused = 1;
printf("Your Pokemon became confused!\n");
return 15;
}
else
{
printf("The attack missed!\n");
return 16;
}
}
else if (strcmp(moveused.effect, "+atk+speed") == 0)
{
combatants[1].atkmod += 1;
combatants[1].speedmod += 1;
printf("Attack and speed rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+atk+def") == 0)
{
combatants[1].atkmod += 1;
combatants[1].defmod += 1;
printf("Attack and defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+spatk+spdef") == 0)
{
combatants[1].spatkmod += 1;
combatants[1].spdefmod += 1;
printf("Special attack and special defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2spdef") == 0)
{
combatants[1].spdefmod += 1;
combatants[1].spdefmod += 1;
printf("Special defense rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2spatk") == 0)
{
combatants[1].spatkmod += 1;
combatants[1].spatkmod += 1;
printf("Special attack rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2speed") == 0)
{
combatants[1].speedmod += 1;
combatants[1].speedmod += 1;
printf("Speed rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+def") == 0)
{
combatants[1].defmod += 1;
printf("Defense rose!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2def") == 0)
{
combatants[1].defmod += 1;
combatants[1].defmod += 1;
printf("Defense rose sharply!\n");
return 17;
}
else if (strcmp(moveused.effect, "+2atk") == 0)
{
combatants[1].atkmod += 1;
combatants[1].atkmod += 1;
printf("Attack rose sharply!\n");
return 17;
}
else
{
printf("The move failed!\n");
return 18;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//check for sleep, freeze, confuse, paralyze, flinch before letting mon move
if (foeparty[ combatants[1].whichpartymemberami ].statusint == 2) //if you're frozen, roll 30%chancce of unfreezing
{
int unfreeze = 1 + rand() % 10;
if (unfreeze > 7) //if they unfreeze
{
printf("%s was unfrozen!\n", combatants[1].individualdata.name);
attacker.individualdata.statusint = 0;
foeparty[ combatants[1].whichpartymemberami ].statusint = 0;
}
else //if they dont
{
printf("%s is frozen solid!\n", combatants[1].individualdata.name);
return 11;
}
}
if (combatants[1].confused == 1) //if confused
{
printf("%s is confused!\n", combatants[1].individualdata.name);
int hiturself = 1 + rand() % 10;
int unconfuse = 1 + rand() % 10;
if (unconfuse >= 6) //if they snap out of confusion
{
attacker.confused = 0;
printf("%s snapped out of confusion!\n", combatants[1].individualdata.name);
hiturself = 1;
}
if (hiturself >= 7) //if hit self in confusion, return
{
printf("%s hurt itself in confusion!\n", combatants[1].individualdata.name);
deplete(&foeparty[ combatants[1].whichpartymemberami ].currenthp, eighth, attacker.individualdata);
return 12;
} //else, just continue function
}
if (combatants[1].flinched == 1) //if flinched
{
printf("... unfortunately, %s flinched and it's attack failed!\n", combatants[1].individualdata.name);
attacker.flinched = 0;
return 13;
}
if (foeparty[ combatants[1].whichpartymemberami ].statusint == 3) //if you're asleep, roll 30% chancce of waking up
{
int unfreeze = 1 + rand() % 10;
if (unfreeze > 7) //if they wake up
{
printf("%s woke up!\n", combatants[1].individualdata.name);
attacker.individualdata.statusint = 0;
foeparty[ combatants[1].whichpartymemberami ].statusint = 0;
}
else //if they dont
{
printf("... but %s is fast asleep!\n", combatants[1].individualdata.name);
return 11;
}
}
if (foeparty[ combatants[1].whichpartymemberami ].statusint == 5) //if you're paralyzed, roll 30% chancce of no move
{
printf("%s is paralyzed!\n", combatants[1].individualdata.name);
int unfreeze = 1 + rand() % 10; //if they paralyzed
if (unfreeze > 7)
{
printf("%s can't move!\n", combatants[1].individualdata.name);
return 14;
}//if not, continue with turn as usual
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int recorsucc = (-1 * moveused.recoilordrain * dmg / 8); //calculates recoil or vampiring hp
if (moveused.recoilordrain != 0) //if the move has recoil or drain:::
{
int urhp = deplete(&foeparty[ combatants[0].whichpartymemberami ].currenthp, recorsucc, attacker.individualdata); //applies recoil or succ
if (*foecombathppointer <= 0)
{
printf("\nThe opposing Pokemon fainted!\n");
foeparty[ combatants[1].whichpartymemberami ].status = "Fainted";
foeparty[ combatants[1].whichpartymemberami ].statusint = 6;
*foefaint = 1;
//check if all opposing mons are fainted
int airandomswitch = -1;
int healthymons = 0;
for (int i = 0; i < 3; i ++)
{
if (foeparty[i].statusint != 6)
{
healthymons++;
}
}
if (healthymons == 0) //if they are, it's all over kid
{
*isoverpointer = 1;
printf("\nYou defeated all enemy Pokemon! You won the battle!");
return 0;
}
else //if not all fainted, ai sends out random not-fainted mon
{
*isoverpointer = 0;
do
{
airandomswitch = rand() % 3;
}while(foeparty[ airandomswitch ].statusint == 6);
}
//fill out combatants with new mon
combatants[1].individualdata = foeparty[airandomswitch];
combatants[1].dexnumber = foeparty[airandomswitch].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[1].nickname = foeparty[airandomswitch].nickname;
combatants[1].atkmod = 0;
combatants[1].defmod = 0;
combatants[1].spatkmod = 0;
combatants[1].spdefmod = 0;
combatants[1].speedmod = 0;
combatants[1].evasionmod = 0;
combatants[1].accuracymod = 0;
combatants[1].protectcounter = 0;
combatants[1].status = foeparty[airandomswitch].status;
combatants[1].statusint = foeparty[airandomswitch].statusint;
combatants[1].confused = 0;
combatants[1].disabled = 0;
combatants[1].toxiccounter = 0;
combatants[1].leechseeded = 0;
combatants[1].flinched = 0;
combatants[1].substitute = 0;
combatants[1].substitutehp = 0;
combatants[1].hyperskyskull = "None";
combatants[1].invulnerable = 0;
combatants[1].caughtinwrap = 0;
combatants[1].cursed = 0;
combatants[1].biding = 0;
combatants[1].bidedamagetracker = 0;
combatants[1].countering = 0;
combatants[1].counterdamagetracker = 0;
combatants[1].thrashcounter = 0;
combatants[1].whichpartymemberami = airandomswitch;
printf("Foe sent out %s!\n", foeparty[airandomswitch].name);
*foecombathppointer = foeparty[airandomswitch].currenthp;
*foecombatspeedpointer = foeparty[airandomswitch].speed;
}
//if ur hp hits 0
}
int finhp = foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, dmg, defender.individualdata);
//run status checks for secondary effects of moves
///////////////////////////////////////////////////////////////////////
if (moveused.effectchance != 0 && dmg > 0) //if theres an effect chance,
{
if (strcmp(moveused.effect, "Burn") == 0) //if effect is burn
{
if (defender.individualdata.statusint == 0) //and theyre healthy
{
int rollchanceb = 1 + rand() % 100;
if (rollchanceb < moveused.effectchance)
{
defender.individualdata.statusint = 1; //burn them //THIS LINE DOESNT WORK
party[ combatants[0].whichpartymemberami ].statusint = 1; //THIS LINE DOES IDK WHY
printf("%s was burned!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Poison") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancep = 1 + rand() % 100;
if (rollchancep < moveused.effectchance)
{
defender.individualdata.statusint = 4;
party[ combatants[0].whichpartymemberami ].statusint = 4;
printf("%s was poisoned!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Toxic") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancet = 1 + rand() % 100;
if (rollchancet < moveused.effectchance)
{
defender.individualdata.statusint = 4;
party[ combatants[0].whichpartymemberami ].statusint = 4;
printf("%s was badly poisoned!\n", defender.individualdata.name);
combatants[0].toxiccounter = 1;
defender.toxiccounter = 1;
}
}
}
else if (strcmp(moveused.effect, "Freeze") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancef = 1 + rand() % 100;
if (rollchancef < moveused.effectchance)
{
defender.individualdata.statusint = 2;
party[ combatants[0].whichpartymemberami ].statusint = 2;
printf("%s was frozen solid!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Paralyze") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchancepz = 1 + rand() % 100;
if (rollchancepz < moveused.effectchance)
{
defender.individualdata.statusint = 5;
party[ combatants[0].whichpartymemberami ].statusint = 5;
printf("%s was paralyzed!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "Sleep") == 0)
{
if (defender.individualdata.statusint == 0)
{
int rollchances = 1 + rand() % 100;
if (rollchances < moveused.effectchance)
{
defender.individualdata.statusint = 3;
party[ combatants[0].whichpartymemberami ].statusint = 3;
printf("%s fell asleep!\n", defender.individualdata.name);
}
}
}
else if (strcmp(moveused.effect, "-spdef") == 0)
{
int rollspdef = 1 + rand() % 100;
if (rollspdef < moveused.effectchance)
{
defender.spdefmod = defender.spdefmod - 1;
combatants[0].spdefmod = combatants[0].spdefmod - 1;
printf("%s had it's special defense lowered!\n", defender.individualdata.name);
if (defender.spdefmod < -6)
{
defender.spdefmod = -6;
}
}
}
else if (strcmp(moveused.effect, "-def") == 0)
{
int rolldef = 1 + rand() % 100;
if (rolldef < moveused.effectchance)
{
defender.defmod = defender.defmod - 1;
combatants[0].defmod = combatants[0].defmod - 1;
printf("%s had it's defense lowered!\n", defender.individualdata.name);
if (defender.defmod < -6)
{
defender.defmod = -6;
}
}
}
else if (strcmp(moveused.effect, "-atk") == 0)
{
int rollatk = 1 + rand() % 100;
if (rollatk < moveused.effectchance)
{
defender.atkmod = defender.atkmod - 1;
combatants[0].atkmod = combatants[0].atkmod - 1;
printf("%s had it's attack lowered!\n", defender.individualdata.name);
if (defender.atkmod < -6)
{
defender.atkmod = -6;
}
}
}
else if (strcmp(moveused.effect, "Flinch") == 0)
{
int rollflinch = 1 + rand() % 100;
if (rollflinch < moveused.effectchance)
{
defender.flinched = 1;
combatants[0].flinched = 1;
}
}
else if (strcmp(moveused.effect, "Confuse") == 0)
{
int rollcon = 1 + rand() % 100;
if (rollcon < moveused.effectchance)
{
defender.confused = 1;
combatants[0].confused = 1;
printf("%s became confused!\n", defender.individualdata.name);
}
}
}
/////////////////////////////////////////////////////////////////////////
//finhp = foedeplete(&party[ combatants[0].whichpartymemberami ].currenthp, dmg, defender.individualdata);
if (*combathppointer <= 0) //note in above line i don't use &defender.ichp but instead use &oppparty[0].ichp. when i use the former, pika's hp never ectually changes. it will say its hp went down, but then the next fight phase shows that the hp remains unchanged. otherwise i'd just use the former and have one function, not func() and oppfunc()
{
*userfaint = 1;
printf("\nYour Pokemon fainted!\n");
party[ combatants[0].whichpartymemberami ].status = "Fainted";
party[ combatants[0].whichpartymemberami ].statusint = 6;
int healthymons = 0; //counts number of non-fainted monsters
for (int i = 0; i < 3; i ++)
{
if (party[i].currenthp != 0)
{
healthymons++;
}
}
if (healthymons == 0) //if they're all fainted, it's all over kid
{
*isoverpointer = 1;
printf("You've been defeated!\n");
return 2;
}
else //if theyre not all fainted, pick from one that's not
{
*isoverpointer = 0; //battle isnt over
printf("\nWhich party member woud you like to switch to?\n");
for (int i = 0; i < 3; i++) //list party members that aren't on the field
{
if (combatants[0].whichpartymemberami != i && party[i].currenthp != 0) //if not mon thats out and not mon that has 0hp
{
printf("Press %i to switch to %s, lv%i\n", i, party[i].name, party[i].lvl);
}
else
{
int filllerrr = 32;
}
}
int whichmem = combatants[0].whichpartymemberami; //just a contraction
int choice; //declaration for a do while
int *choicepointer = &choice;
do //ask player which party member to switch to
{
choice = get_int("Type choice and press enter:\n");
*choicepointer = choice;
}while(choice == combatants[0].whichpartymemberami || choice < 0 || choice > 3);
//ok here i need to keep status. currenthp uses pointers to party/foeparty so should already be updated
party[whichmem].status = combatants[0].status;
party[whichmem].statusint = combatants[0].statusint;
//alright now i need to load party[choice] into combatants[0]
combatants[0].individualdata = party[choice];
combatants[0].dexnumber = party[choice].dexno; //inherit from pokemon struct. combatants[0].dexnumber = combatants[0].individualdata.dexno
combatants[0].nickname = party[choice].nickname;
combatants[0].atkmod = 0;
combatants[0].defmod = 0;
combatants[0].spatkmod = 0;
combatants[0].spdefmod = 0;
combatants[0].speedmod = 0;
combatants[0].evasionmod = 0;
combatants[0].accuracymod = 0;
combatants[0].protectcounter = 0;
combatants[0].status = party[choice].status;
combatants[0].statusint = party[choice].statusint;
combatants[0].confused = 0;
combatants[0].disabled = 0;
combatants[0].toxiccounter = 0;
combatants[0].leechseeded = 0;
combatants[0].flinched = 0;
combatants[0].substitute = 0;
combatants[0].substitutehp = 0;
combatants[0].hyperskyskull = "None";
combatants[0].invulnerable = 0;
combatants[0].caughtinwrap = 0;
combatants[0].cursed = 0;
combatants[0].biding = 0;
combatants[0].bidedamagetracker = 0;
combatants[0].countering = 0;
combatants[0].counterdamagetracker = 0;
combatants[0].thrashcounter = 0;
combatants[0].whichpartymemberami = choice;
//printf("choice is %i\n", choice);
//printf("combatants[0].whichpartymemberami = %i\n", combatants[0].whichpartymemberami);
party[combatants[0].whichpartymemberami].currenthp = party[choice].currenthp;
*combatspeedpointer = party[choice].speed;
//printf("current hp of party[choice] is %i\n", party[choice].currenthp);
//printf("party[combatants[0].whichpartymemberami].currenthp = %i\n", party[combatants[0].whichpartymemberami].currenthp);
*userswitchpointer = 1;
*userfaint = 0;
printf("\nCome back, %s. Go, %s!\n\n", party[whichmem].name, party[choice].name);
}
}
//implement secondary effects of moves
//endoffoefight() bookmark
return 1;
}
//for attack, below, we need to make a conditional that takes a whole other route if the move is a status move.
int attack(struct combatmon attacker, struct combatmon defender, struct move movestruct, int STAB) //attack needs to take type effectiveness as an arguement
{
//obv we need to take move type, user type 1 and type 2, opp types 1 and 2 as arguments for this function
//also, if move is special use special stats, if move is physical, use physical stats
float d = 0;
if (movestruct.physicalorspecial == 0)
{ //physical damage and atk mods
d = 0.7 * (3 * 7 / 20 * (movestruct.basepower / 40) * attackchange(combatants[0].atkmod, combatants[0].individualdata.statusint) * (((5 * combatants[0].individualdata.lvl + 2) * combatants[0].individualdata.atk / (combatants[1].individualdata.def * statchange(combatants[1].defmod)) / 10) + 2));
}
else
{
d = 0.7 * (3 * 7 / 20 * (movestruct.basepower / 40) * statchange(combatants[0].spatkmod) * (((5 * combatants[0].individualdata.lvl + 2) * combatants[0].individualdata.spatk / (combatants[1].individualdata.spdef * statchange(combatants[1].spdefmod)) / 10) + 2));
}
int d2 = (STAB * d) / 2;
//d2 = d2 * type effective * type effective2 divided by 4. if neutral effective, both typechart entries = 2, so we mult by 4. this is why i divde by 4 at end
d2 = d2 * typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] / 4;
//super effective messages
if ( typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] > 4 && movestruct.attackorstatus == 0)
{
printf("It's super effective!\n");
}
else if ( typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] < 4 && typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] != 0 && movestruct.attackorstatus == 0)
{
printf("It's not very effective.\n");
}
else if (typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] == 0 && movestruct.attackorstatus == 0)
{
printf("...but it had no effect!\n");
}
else
{
int fillerint = 69;
}
//accuracy check
int acccheck = 1 + rand() % 100;
if ( (movestruct.acc * statchange(attacker.accuracymod) < acccheck))
{
printf("The attack missed!\n");
d2 = 0;
}
else
{
int rollforeffect = 1 + rand() % 100; ////////////////////here is where status effect from moves happen. need to do one for status string not status int
if (movestruct.effectchance > rollforeffect)
{
//apply status to opponent
if (movestruct.effectint > 0 && movestruct.effectint < 6 && *defender.individualdata.statusintpointer == 0) //if they're inflicting major status, and the defender doesn't already have a status condition
{
defender.statusint = movestruct.effectint; //apply to combatmon for in-battle stuff
*defender.individualdata.statusintpointer = movestruct.effectint; //apply to individual struct so status stays on switch out
printf("The attack inflicted %s!\n", movestruct.effect);
}
}
}
//else if acccheck < movestruct.acc, roll for status
return d2;
}
int foeattack(struct combatmon attacker, struct combatmon defender, struct move movestruct, int STAB) //attack needs to take type effectiveness as an arguement
{
//obv we need to take move type, user type 1 and type 2, opp types 1 and 2 as arguments for this function
//also, if move is special use special stats, if move is physical, use physical stats
float d = 0;
if (movestruct.physicalorspecial == 0)
{ //physical damage and atk mods
d = 0.7 * (3 * 7 / 20 * (movestruct.basepower / 40) * attackchange(combatants[1].atkmod, combatants[1].individualdata.statusint) * (((5 * combatants[1].individualdata.lvl + 2) * combatants[1].individualdata.atk / (combatants[0].individualdata.def * statchange(combatants[0].defmod)) / 10) + 2));
}
else
{
d = 0.7 * (3 * 7 / 20 * (movestruct.basepower / 40) * statchange(combatants[1].spatkmod) * (((5 * combatants[1].individualdata.lvl + 2) * combatants[1].individualdata.spatk / (combatants[0].individualdata.spdef * statchange(combatants[0].spdefmod)) / 10) + 2));
}
int d2 = (STAB * d) / 2;
//d2 = d2 * type effective * type effective2 divided by 4. if neutral effective, both typechart entries = 2, so we mult by 4. this is why i divde by 4 at end
d2 = d2 * typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] / 4;
//super effective messages
if ( typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] > 4 && movestruct.attackorstatus == 0)
{
printf("It's super effective!\n");
}
else if ( typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] < 4 && typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] != 0 && movestruct.attackorstatus == 0)
{
printf("It's not very effective.\n");
}
else if (typechart[movestruct.typeint][defender.individualdata.typeint1] * typechart[movestruct.typeint][defender.individualdata.typeint2] == 0 && movestruct.attackorstatus == 0)
{
printf("...but it had no effect!\n");
}
else
{
int fillerint = 69;
}
//accuracy check
int acccheck = 1 + rand() % 100;
if ( (movestruct.acc * statchange(attacker.accuracymod) < acccheck) && movestruct.attackorstatus == 0)
{
printf("The attack missed!\n");
d2 = 0;
}
else
{
int rollforeffect = 1 + rand() % 100; ////////////////////here is where status effect from moves happen. need to do one for status string not status int
if (movestruct.effectchance > rollforeffect)
{
//apply status to opponent
if (movestruct.effectint > 0 && movestruct.effectint < 6 && *defender.individualdata.statusintpointer == 0) //if they're inflicting major status, and the defender doesn't already have a status condition
{
defender.statusint = movestruct.effectint; //apply to combatmon for in-battle stuff
*defender.individualdata.statusintpointer = movestruct.effectint; //apply to individual struct so status stays on switch out
printf("The attack inflicted %s!\n", movestruct.effect);
}
}
}
//else if acccheck < movestruct.acc, roll for status
return d2;
}
int deplete(int *hppoint, int damage, struct pokemon victim) //this is for when you are damaging opponent. their hp pointer will get passed in by fight()
{
if (damage < 0) //if healing
{
int intugor = damage * -1;
printf("%i HP was restored!\n", intugor);
}
if (damage >= 0)
{
printf("It did %i damage!\n", damage);
}
printf("%s's HP went from %i ", victim.name, *hppoint);
*hppoint = *hppoint - damage;
if (*hppoint <= 0) //preventss hp from going below 0
{
*hppoint = 0;
//status int pointer is 6 for faint?
}
if (*hppoint > victim.maxhp) //prevents hp from going over max
{
*hppoint = victim.maxhp;
}
printf("to %i!\n", *hppoint);
*foecombathppointer = *hppoint;
return *hppoint;
}
int foedeplete(int *hppoint, int damage, struct pokemon victim) //this is for when the foe is damaging u. ur hp pointer will get passed in by fight()
{
if (damage < 0)
{
int intugor = damage * -1;
printf("%i HP was restored!\n", intugor);
}
if (damage >= 0)
{
printf("It did %i damage!\n", damage);
}
printf("%s's HP went from %i ", victim.name, *hppoint);
*hppoint = *hppoint - damage;
if (*hppoint <= 0) //preventss hp from going below 0
{
*hppoint = 0;
//status pointer is faint?
}
if (*hppoint > victim.maxhp) //prevents hp from going over max
{
*hppoint = victim.maxhp;
}
printf("to %i!\n", *hppoint);
*combathppointer = *hppoint;
return *hppoint;
}
float speedchange(int statmod, int statusint)
{
float a = statmod;
if (statusint == 5) //if paralyzed
{
a = a / 2;
}
if (statmod == 0)
{
if (statusint == 5)
{
return 0.5;
}
else
{
return 1;
}
}
else if (statmod > 0)
{
return (1 + (a / 2));
}
else
{
return (3 / (3 - a));
}
}
float attackchange(int statmod, int statusint)
{
float mult = 1;
float a = statmod;
if (statusint == 1) //if burned
{
a = a / 2;
mult = mult/2;
}
if (statmod == 0)
{
if (statusint == 1)
{
return 0.5;
}
else
{
return 1;
}
}
else if (statmod > 0)
{
return (1 + (a / 2));
}
else //statmod < 0
{
return (3 / (3 - a));
}
}
float statchange(int statmod)
{
float a = statmod;
if (statmod == 0) //if no stat mods
{
return 1; //return 1x multiplier
}
else if (statmod > 0) //if positive
{
return (1 + (a / 2));
}
else if (statmod < 0)
{
return (3 / (3 - a));
}
else
{
return 1;
}
}
string statinttostring(int g)
{
string answer;
if (g == 1)
{
answer = "Burned";
}
else if (g == 2)
{
answer = "Frozen";
}
else if (g == 3)
{
answer = "Asleep";
}
else if (g == 4)
{
answer = "Poisoned";
}
else if (g == 5)
{
answer = "Paralyzed";
}
else
{
answer = "None";
}
return answer;
}
void userselection1(void)
{
string usermon1 = get_string("Type the name of your first party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, usermon1) == 0)
{
*urmon1ptr = i;
printf("\n%s has been added to your team!\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
userselection1();
}
}
}
void userselection2(void)
{
string usermon2 = get_string("Type the name of your second party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, usermon2) == 0)
{
*urmon2ptr = i;
printf("\n%s has been added to your team.\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
userselection2();
}
}
}
void userselection3(void)
{
string usermon3 = get_string("Type the name of your third party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, usermon3) == 0)
{
*urmon3ptr = i;
printf("\n%s has been added to your team.\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
userselection3();
}
}
}
void foeselection1(void)
{
string foemon1 = get_string("Type the name of your foe's first party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, foemon1) == 0)
{
*theirmon1ptr = i;
printf("\n%s has been added to foe's team.\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
foeselection1();
}
}
}
void foeselection2(void)
{
string foemon2 = get_string("Type the name of your foe's second party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, foemon2) == 0)
{
*theirmon2ptr = i;
printf("\n%s has been added to foe's team.\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
foeselection2();
}
}
}
void foeselection3(void)
{
string foemon3 = get_string("Type the name of your foe's third party member and hit Enter:\n");
for (int i = 0; i < 151; i++)
{
if (strcmp(pokedex[i].name, foemon3) == 0)
{
*theirmon3ptr = i;
printf("\n%s has been added to foe's team.\n", pokedex[i].name);
return;
}
else if (i >= 150)
{
printf("Pokemon not recognized. Please try again. \n--All fully-evolved Pokemon from the original 151 are available, minus Ditto, plus Pikachu.\n--Make sure only the first letter is capitalized!\n");
foeselection3();
}
}
}
<file_sep># level50
My final project for cs50 is "LEVEL50", a text-based command line Pokemon battle simulator written
entirely in C.
C is a really cool language, and the initial reason for beginning to write LEVEL50 was to learn
more about it. During the early weeks of cs50, I wrote some code that simulated a VERY stripped-
down Pokemon battle as a way for me to better understand the use of pointers in C. I continued.
adding bits and pieces to the sim to hone my skills, and eventually decided to expand the scope
of the simulator and work on it as my final project. For a while I believed I'd bitten off more
than I could chew, but I just kept debugging and adding features until I was satisfied. Maybe one
day I'll write a full Pokemon-style game, but I probably won't use C for it lol. This project
would likely have been a lot easier using Python alongside a database or file reader (instead of
initializing the entire Pokedex and every move at the beginning of the battle lol) but using C
has been amazing practice and is quite fulfilling.
MANY hours have gone into this course and this project, and I'm quite proud of my work on both.
At the beginning of cs50 I had never written a "Hello world" program, and had never taken any
sort of computer science class. Today, I have enough knowledge to create something like LEVEL50,
and I have experience using C, Python, SQL, HTTP, CSS, Javascript, and Flask. THANK YOU SO MUCH
to the cs50 team and to <NAME> for your amazing contribution to the world. You guys have
an incredible course model and you are all educators of the highest caliber.
LEVEL50 info dump:
LEVEL50 is text-based and can be played from a command line terminal.
You must be able to compile C to play the game.
Simply download LEVEL50.c, compile it, and run the compiled program.
All fully-evolved Pokemon from the orginal 151 are in the game, minus Ditto, plus Pikachu.
The game uses a mix of mechanics. The moves, types, and base stats are drawn from 5th gen.
No EVs, IVs all assumed to be 31.
Physical/Special split exists. Move priority exists. STAB exists. Super-effective etc. exists.
Status effects and stat mods exist.
There are no abilities (like gens 1 and 2), and no items.
Each Pokemon has a premade moveset (kind of like Pokemon Stadium).
The damage formula is my own tweak on the one from the games.
The battle format is 3v3 single battle. All Pokemon are set to Level 50.
User selects which Pokemon they want, and which ones they want to fight against.
The battle ends when either all user mons faint, all foe mons faint, or the user Escapes.
User may fight, switch Pokemon, escape, and view party stats.
Sleep/Freeze have a chance of ending every turn, even for Rest users.
No critical hits. Status moves don't check type (you can Poison Muk).
You can change a monster's status even if it already has a condition, but will lose the original status.
Roost doesnt remove flying type. Steel wing doesn't raise defense. Weather doesn't exist.
The code is 6000+ lines of the finest hand-coded megaspaghetti.
I hope LEVEL50 can be illuminating, entertaining, instructional, or otherwise beneficial.
Enjoy, download, and share as you like.
If you have any questions, you can email me at <EMAIL>.
//BRYSONCARTER2020
| c0ee422c47fbe2787c54b72d51042349615abe42 | [
"Markdown",
"C"
] | 2 | C | BRYSONCARTER/LEVEL50 | a09276012e71ab8be3bc3ec8a028bc4b9eb2f84e | 9795749b439e64cf3c63bd357192bb5b09660a0e |
refs/heads/master | <repo_name>aarushi2699/quiz.github.io<file_sep>/home.php
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con,'quiz');
?>
<html>
<body>
<link rel="stylesheet" type="text/css" href="bootstrap.css">
<div class="container">
<br>
<h1 class="text-center text-primary"> Welcome to Quiz </h1>
<div class="col-lg-8 m-auto d-block">
<div class="card">
<h3 class="text-center card-header">You have to select one out of four, BEST OF LUCK!!!</h3>
</div>
<br>
<form action="check.php" method="post">
<?php
for($i=1 ; $i < 16 ; $i++)
{
$q = "select * from questions where qid= $i";
$query = mysqli_query($con,$q);
while($rows = mysqli_fetch_array($query) )
{
?>
<div clas="card">
<h6 class="card-header"><?php echo $rows['question'] ?></h6>
<?php
$q = "select * from answers where ans_id= $i";
$query = mysqli_query($con,$q);
while($rows = mysqli_fetch_array($query) )
{
?>
<div class"class-body">
<input type="radio" name=" quizcheck[<?php echo $rows['ans_id'] ?>]" value="<?php echo $rows['aid']; ?>">
<?php echo $rows['answer']; ?>
</div>
<?php
}
}
}
?>
<input type="submit" name="submit" value="submit" class="btn btn-success m-auto d-block">
</form>
</div>
</div>
</div>
</body>
</html><file_sep>/check.php
<?php
session_start();
$con = mysqli_connect('localhost','root');
mysqli_select_db($con,'quiz');
?>
<!DOCTYPE html>
<html>
<body>
<link rel="stylesheet" type="text/css" href="bootstrap.css">
div class="container text-center" >
<br><br>
<h1 class="text-center text-success text-uppercase animateuse" > Quiz World</h1>
<br><br><br><br>
<table class="table text-center table-bordered table-hover">
<tr>
<th colspan="2" class="bg-dark"> <h1 class="text-white"> Results </h1></th>
</tr>
<tr>
<td>
Questions Attempted
</td>
<?php
$result=0;
if(isset($_POST['submit']))
{
if(!empty($_POST['quizcheck']))
{
$count = count($_POST['quizcheck']);
?>
<td>
<?php
echo "Out of 5, You have attempt ".$count." option."; ?>
</td>
<?php
// echo "You have selected ".$count." options";
$selected= $_POST['quizcheck'];
print_r($selected);
$q= "select * from questions";
$query= mysqli_query($con, $q);
$i = 1;
while ($rows = mysqli_fetch_array($query))
{
//print_r($rows['ans_id']);
$checked = $rows['ans_id'] == $selected[$i];
if($checked)
{
$result++;
}
$i++;
}
?>
<tr>
<td>
Your Total score
</td>
<td colspan="2">
<?php
echo " Your score is ". $result.".";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
</td>
</tr>
<?php
echo "<br> total score is".$result;
//$finalresult= "insert into user(totalques,answercorrect) values ('5','$result')";
//$queryresult= mysqli_query($conn,$finalresult);
?>
</table>
</div>
</body>
</html>
| b3c01e44da468f3aa1abaf18fa55ba2c1caed50e | [
"PHP"
] | 2 | PHP | aarushi2699/quiz.github.io | 209ce4ff7129e5d8153a6219d73dc59f4dc0836d | 70f22d11eaf394cbf18621e5a7d132587ebef47c |
refs/heads/master | <file_sep>// Listen for submit
document.querySelector('#loan-form').addEventListener('submit', function(e) {
document.querySelector('#results').style.display = 'none';
document.querySelector('#loading').style.display = 'block';
setTimeout(calculateResults, 2000);
e.preventDefault();
});
function calculateResults() {
let amount = document.querySelector('#amount');
let interest = document.querySelector('#interest');
let years = document.querySelector('#years');
let monthlyPayment = document.querySelector('#monthly-payment');
let totalPayment = document.querySelector('#total-payment');
let totalInterest = document.querySelector('#total-interest');
let principal = parseFloat(amount.value);
let calculatedInterest = parseFloat(interest.value) / 100 / 12;
let calculatedPayments = parseFloat(years.value) * 12;
let x = Math.pow(1 + calculatedInterest, calculatedPayments);
let monthly = (principal*x*calculatedInterest)/(x-1);
if(isFinite(monthly)) {
monthlyPayment.value = monthly.toFixed(2);
totalPayment.value = (monthly * calculatedPayments).toFixed(2);
totalInterest.value = ((monthly * calculatedPayments)-principal).toFixed(2);
document.querySelector('#results').style.display = 'block';
document.querySelector('#loading').style.display = 'none';
} else {
showError('Check your Numbers')
}
}
// Show Error
function showError(error) {
let errorDiv = document.createElement('div');
let card = document.querySelector('.card');
let heading = document.querySelector('.heading');
document.querySelector('#results').style.display = 'none';
document.querySelector('#loading').style.display = 'none';
errorDiv.className = 'alert alert-danger';
errorDiv.appendChild(document.createTextNode(error));
card.insertBefore(errorDiv, heading);
setTimeout(clearError, 1500);
}
function clearError(){
document.querySelector('.alert').remove();
}
| 74d78975f7bd0f897263f9e9f041d077f152c647 | [
"JavaScript"
] | 1 | JavaScript | DonCream/JavascriptProjects | ec26386a2f32f5594f0df48bbb0b40832ec1e833 | e1d7eda72010d1cad3370b60d95683c41a6fdf31 |
refs/heads/master | <file_sep>const ReferenceData = {
title: 'References',
info: [
{
id: 1,
name: '<NAME>',
profession: 'Professor, Chair of Software Systems Modelling',
organization: 'Univesity of Edinburgh',
info: '<NAME> has recently completed an MSc at the University of Edinburgh where I supervised his MSc dissertation entitled "Discrete SIR Game for Understanding Epidemics". This involved creating a game using the Unity platform to simulate the spread of an infectious disease through a population. Mateo took ownership of this problem and made it his own, teaching himself the skills necessary to create an effective simulation on the Unity platform.I was impressed by his level of engagement with the project, and his project management and technical skills and have no hesitation in recommending him to you as a very good hire.'
},
{
id: 2,
name: '<NAME>',
profession: 'Engineering Manager of Digital Process Automation',
organization: 'MUFG Union Bank N.A.',
info: 'I have the pleasure of working with Mateo Vargas at Union Bank as his manager. As a well-rounded RPA software engineer, Mateo can independently analyze requirements, research, develop, and deliver any complex robotic applications. His keen analysis combined with strong troubleshooting skills make him the go to person to quickly resolve any technical issues. What impresses me most about Mateo is his diligent and reliable work ethic, willingness to lead and help when it matters most, and always open to challenge and sharpen his technical skills. His professionalism and pleasant demeanor make him a great and impactful addition to any team.'
}
]
}
export default ReferenceData;<file_sep>import React, {useState} from 'react';
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import Card from 'react-bootstrap/Card';
import Footer from './Footer';
import NavComponent from './NavComponent';
import Title from './Title.js';
import ReferencesData from '../Data/ReferencesData.js';
const References = () => {
let [title, referencesList] = useState();
title = ReferencesData.title;
referencesList = ReferencesData.info;
return (
<div className="App">
<NavComponent></NavComponent>
<Container fluid>
<Title title={title}></Title>
{referencesList.map((references) => (
<Row key={references.id}>
<Col key={references.id}>
<Card key = {references.id}>
<Card.Body key = {references.id}>
<blockquote className="blockquote mb-0">
<p>
{' '}{ references.info }{' '}
</p>
</blockquote>
<footer className="blockquote-footer">
{ references.name }, { references.profession }, <cite title="Source Title">{ references.organization }</cite>
</footer>
</Card.Body>
</Card>
</Col>
</Row>
))}
<Footer></Footer>
</Container>
</div>
)
}
export default References
<file_sep>import React, {useState} from 'react';
import { Link } from 'react-router-dom';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import Image from 'react-bootstrap/Image';
import MyPhoto from '../Images/me.jpg';
import Footer from './Footer';
import NavComponent from './NavComponent';
import { BiLeftTopArrowCircle } from 'react-icons/bi';
import HomeData from '../Data/HomeData.js';
import Title from './Title.js';
const Home = () => {
let [title, textInfo] = useState();
title = HomeData.title;
textInfo = HomeData.info;
return (
<div className="App">
<NavComponent></NavComponent>
<Container fluid>
<Title title={title}></Title>
<Row>
<Col>
<Image src={ MyPhoto } alt="Portrait" roundedCircle fluid />
</Col>
<Col>
<p>
{textInfo}
</p>
</Col>
</Row>
</Container>
<Footer></Footer>
</div>
)
}
export default Home;
<file_sep>import './App.css';
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import { render } from 'react-dom';
import Home from './Components/Home';
import Projects from './Components/Projects';
import Contact from './Components/Contact';
import Links from './Components/Links';
import References from './Components/References';
import anime from 'animejs/lib/anime.es.js';
import MyPhoto from './Images/me.jpg';
class App extends Component {
componentDidMount(){
let textWrapper = document.querySelector('.ml9 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
anime.timeline({ loop: false })
.add({
targets: '.ml9 .letter',
scale: [0, 1],
duration: 3000,
elasticity: 600,
delay: (el, i) => 45 * (i + 1)
});
}
render(){
const App = () => (
<div>
<Switch>
<Route exact path='/' component={ Home }></Route>
<Route path='/projects' component={ Projects }></Route>
<Route path='/references' component={ References }></Route>
<Route path='/links' component={ Links }></Route>
</Switch>
</div>
)
return(
<Switch>
<App></App>
</Switch>
);
}
}
export default App;
<file_sep>import React from 'react';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
const Title = (props) => {
return (
<Row>
<Col>
<h1 className="ml9">
<span className="text-wrapper">
<span className="letters">{props.title}</span>
</span>
</h1>
</Col>
</Row>
)
}
export default Title
<file_sep>import React, { useState } from 'react';
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import Card from 'react-bootstrap/Card';
import Footer from './Footer';
import NavComponent from './NavComponent';
import Title from './Title.js';
import ProjectsData from '../Data/ProjectsData';
const Projects = () => {
let [title, projects, rowOne, rowTwo] = useState();
title = ProjectsData.title;
projects = ProjectsData.projects;
rowOne = [];
rowTwo = [];
for(let i = 0; i < projects.length; i++){
if(i < 3){
rowOne.push(projects[i]);
}
else if( i >= 3 && i < 6){
rowTwo.push(projects[i]);
}
}
console.log(rowOne);
console.log(rowTwo);
return (
<div className="App">
<NavComponent></NavComponent>
<Container fluid>
<Title title={title}></Title>
<Row>
{rowOne.map((projects) => (
<Col key={ projects.id }>
<Card style={{ width: '18rem' }} key={projects.id}>
<Card.Img variant="top" src={projects.image}/>
<Card.Body key={projects.id}>
<Card.Title key={projects.id}>{projects.title}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{projects.technology}</Card.Subtitle>
<Card.Text>
{projects.description}
</Card.Text>
<Card.Link href={projects.link} target='_blank'>Use It Here</Card.Link>
<Card.Link href={projects.github} target='_blank'>Github</Card.Link>
</Card.Body>
</Card>
</Col>
))}
</Row>
<Row>
{rowTwo.map((projects) => (
<Col key={projects.id}>
<Card style={{ width: '18rem' }} key={projects.id}>
<Card.Img variant="top" src={projects.image} />
<Card.Body key={projects.id}>
<Card.Title key={projects.id}>{projects.title}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{projects.technology}</Card.Subtitle>
<Card.Text>
{projects.description}
</Card.Text>
<Card.Link href={projects.link} target='_blank'>Use It Here</Card.Link>
<Card.Link href={projects.github} target='_blank'>Github</Card.Link>
</Card.Body>
</Card>
</Col>
))}
</Row>
<Footer></Footer>
</Container>
</div>
);
}
export default Projects
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import { BsCodeSlash } from 'react-icons/bs';
import { BiPen } from 'react-icons/bi';
import { AiOutlineLink, AiFillHome } from 'react-icons/ai';
const Footer = () => {
return (
<div>
<footer>
<Row>
<Col>
<Link to={'./'}>
<Button variant="outline-info">
<AiFillHome></AiFillHome>
Home
</Button>
</Link>
</Col>
<Col>
<Link to={'./projects'}>
<Button variant="outline-info">
<BsCodeSlash></BsCodeSlash>
Projects
</Button>
</Link>
</Col>
<Col>
<Link to={'./references'}>
<Button variant="outline-info">
<BiPen></BiPen>
References
</Button>
</Link>
</Col>
<Col>
<Link to={'./links'}>
<Button variant="outline-info">
<AiOutlineLink></AiOutlineLink>
Links
</Button>
</Link>
</Col>
</Row>
<Row><br></br></Row>
<Row>
<Col></Col>
<Col>
<a href='https://github.com/mateovargas' target='_blank'><NAME></a>
<p>Copyright © 2021</p>
</Col>
<Col></Col>
</Row>
</footer>
</div>
)
}
export default Footer
<file_sep>import PokedexImage from '../Images/Pokedex.png';
import Xeno from '../Images/game.png';
import SPAM from '../Images/SPAM-Store.png';
import WorkLifeBalance from '../Images/worklife.png';
import FriendFinder from '../Images/friendfinder.png';
import Burger from '../Images/burger.png';
const Projects = {
title: 'Projects',
projects: [
{
id: 1,
title: 'Pokédex',
image: PokedexImage,
technology: 'ReactJS',
description: 'A front-end application that allows you to search for a Pokemon using the PokeAPI.',
link: 'https://react-pokedex-mv.herokuapp.com/',
github: 'https://github.com/mateovargas/pokedex'
},
{
id: 2,
title: 'Xenoplague',
image: Xeno,
technology: 'Unity2D and C#',
description: "A game that simulates the spread of a disease, created and presented as Mateo's Masters thesis.",
link: 'https://mateovargas.itch.io/discrete-sir-games-for-understanding-epidemics',
github: 'https://github.com/mateovargas/dissertation'
},
{
id: 3,
title: 'SPAM-Store',
image: SPAM,
technology: 'MongoDB, ReactJS, ExpressJS, NodeJS',
description: 'This is a React boilerplate single page responsive portfolio app for store fronts.',
link: 'https://www.npmjs.com/package/spam-store',
github: 'https://github.com/React-BP/SPAM-store'
},
{
id: 4,
title: 'WorkLifeBalance',
image: WorkLifeBalance,
technology: 'MongoDB, ReactJS, ExpressJS, NodeJS',
description: 'Application that allows users to login and keep track of their hours spent.',
link: 'https://frozen-sierra-80656.herokuapp.com/',
github: 'https://github.com/mateovargas/workLife'
},
{
id: 5,
title: 'FriendFinder',
image: FriendFinder,
technology: 'ReactJS, ExpressJS, NodeJS',
description: 'Application that allows users pair themselves with their most likely match.',
link: 'https://floating-dawn-36930.herokuapp.com/',
github: 'https://github.com/mateovargas/friends-app'
},
{
id: 6,
title: "<NAME>",
image: Burger,
technology: 'ExpressJS, HandlebarsJS, NodeJS',
description: "Application that lets you feed Bob's friend and create new ones.",
link: 'https://aqueous-hamlet-72599.herokuapp.com/',
github: 'https://github.com/mateovargas/burger'
}
]
}
export default Projects; | b5189082153f6347bf1706dd29451fee787d1bf4 | [
"JavaScript"
] | 8 | JavaScript | mateovargas/personal-portfolio | 78ec3d9d8637c0ab210317a0ef4a48ee6ed9f743 | 7c088db0e40959b9f72f563be67c4db932bf747a |
refs/heads/master | <file_sep>// Constants
export const CREATE = "tasks/CREATE";
export const FETCH = "tasks/FETCH";
export const UPDATE = "tasks/UPDATE";
export const DELETE = "tasks/DELETE";
export const RECEIVED = "tasks/RECEIVED";
// Actions
export const createTask = ({ title, description }) => ({
type: CREATE,
title,
description,
});
export const fetchTasks = () => ({
type: FETCH,
});
export const updateTask = ({ id, title, description }) => ({
type: UPDATE,
id,
title,
description,
});
export const deleteTask = ({ id }) => ({
type: DELETE,
id,
});
// Reducers
export const defaultState = {
tasks: [],
loading: false,
};
const reducer = (state = defaultState, action) => {
switch (action.type) {
case CREATE:
case FETCH:
case UPDATE:
case DELETE:
return {
...state,
loading: true,
};
case RECEIVED:
return {
...state,
tasks: action.tasks,
loading: false,
};
default:
return state;
}
};
// Selectors
export const getTasks = state => state.tasks;
export const getTaskTitle = state => state.tasks.title;
export default reducer;
| 268be7ea7a2b936f8556113d3408a482f475c948 | [
"JavaScript"
] | 1 | JavaScript | DenisKrasnov/todo-list-reactJs | 641926f9fff36417301950bffed537a075b08cd1 | 9c8ffa8d4c2bd34dd0d21e02165fd41e8e899da5 |
refs/heads/master | <repo_name>leandrodalbo/DesignPatterns<file_sep>/src/main/java/strategy/FileCompressorManager.java
package strategy;
public class FileCompressorManager {
private static FileCompressorManager instance = null;
private CompressionStrategy strategy;
private FileCompressorManager() {
}
public static FileCompressorManager getInstance() {
if (instance == null) {
instance = new FileCompressorManager();
}
return instance;
}
public void setStrategy(CompressionStrategy strategy) {
this.strategy = strategy;
}
public void compress() {
this.strategy.compress();
}
}
<file_sep>/src/test/java/iterator/implementations/ProductCollectionTest.java
package iterator.implementations;
import iterator.AbstractCollection;
import iterator.AbstractIterator;
import org.junit.Test;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
public class ProductCollectionTest {
@Test
public void shouldBeAbleToIterateACollectionsOfProducts(){
AbstractCollection collection= new ProductsCollection();
AbstractIterator iterator = (DefaultIterator) collection.getIterator();
ProductsCollection.Product p =(ProductsCollection.Product) iterator.getNext();
while (p != null)
{
assertThat(p, instanceOf(ProductsCollection.Product.class));
p = (ProductsCollection.Product) iterator.getNext();
}
}
}
<file_sep>/src/main/java/factoryMethod/JpgFactory.java
package factoryMethod;
public class JpgFactory implements ImageFactory {
@Override
public LocalImage getImage() {
return new JPGImage();
}
}
<file_sep>/src/main/java/state/OpenDoor.java
package state;
public class OpenDoor extends DoorState {
@Override
public String getStateKey() {
return StateKeys.OPEN.getKey();
}
}
<file_sep>/src/main/java/singleton/Singleton.java
package singleton;
import java.util.Objects;
public class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
@Override
public int hashCode()
{
return Objects.hash(Singleton.class.getName());
}
}
<file_sep>/src/test/java/iterator/implementations/DefaultIteratorTest.java
package iterator.implementations;
import iterator.AbstractIterator;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
public class DefaultIteratorTest {
private final List collection = Arrays.asList("a", "b", "c");
@Test
public void shouldBeAbleToGetTheFirstElement() {
AbstractIterator iterator = new DefaultIterator<String>(collection);
assertThat(iterator.getFirst(), equalTo("a"));
}
@Test
public void shouldBeAbleToIterateThroughAllTheItems() {
StringBuilder builder = new StringBuilder();
AbstractIterator iterator = new DefaultIterator<String>(collection);
String next = (String) iterator.getNext();
while (next != null) {
builder.append(next);
next = (String) iterator.getNext();
}
assertThat(builder.toString(), equalTo("abc"));
}
}
<file_sep>/src/test/java/strategy/FileCompressorManagerTest.java
package strategy;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
public class FileCompressorManagerTest {
@Test
public void shouldGetASingletonInstance() {
FileCompressorManager manager = FileCompressorManager.getInstance();
FileCompressorManager manager1 = FileCompressorManager.getInstance();
assertTrue(manager.hashCode() == manager1.hashCode());
}
@Test
public void shouldBeAbleToUseZipOption() {
FileCompressorManager manager = FileCompressorManager.getInstance();
ZipCompression zipCompression = mock(ZipCompression.class);
manager.setStrategy(zipCompression);
manager.compress();
verify(zipCompression, times(1)).compress();
}
@Test
public void shouldBeAbleToUsRarOption() {
FileCompressorManager manager = FileCompressorManager.getInstance();
RarCompression rarCompression = mock(RarCompression.class);
manager.setStrategy(rarCompression);
manager.compress();
verify(rarCompression, times(1)).compress();
}
}
<file_sep>/src/test/java/state/StatefulDoorTest.java
package state;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class StatefulDoorTest {
@Test
public void theDoorShouldBeClosedWhenItIsCreated()
{
StatefulDoor door = new StatefulDoor();
assertTrue(door.isClosed());
}
@Test
public void theDoorCanBeOpened()
{
StatefulDoor door = new StatefulDoor();
door.open();
assertTrue(door.isOpen());
}
@Test
public void theDoorCanBeClosed()
{
StatefulDoor door = new StatefulDoor();
door.open();
door.close();
assertTrue(door.isClosed());
}
}
<file_sep>/src/main/java/factoryMethod/JPGImage.java
package factoryMethod;
public class JPGImage extends LocalImage {
}
<file_sep>/src/main/java/strategy/CompressionStrategy.java
package strategy;
public interface CompressionStrategy {
public void compress();
}
<file_sep>/src/main/java/iterator/AbstractCollection.java
package iterator;
public interface AbstractCollection<T> {
T getIterator();
}
<file_sep>/src/main/java/decorator/DecoratedComponent.java
package decorator;
public abstract class DecoratedComponent {
public abstract boolean performDefaultAction();
}
<file_sep>/src/main/java/strategy/ZipCompression.java
package strategy;
public class ZipCompression implements CompressionStrategy{
@Override
public void compress() {
System.out.println("zip compression");
}
}
<file_sep>/src/test/java/observer/ObserverSubjectTest.java
package observer;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
public class ObserverSubjectTest {
@Test
public void shouldAddAnObserver() {
ObserverSubject observerSubject = ObserverSubject.getInstance();
LocalObserver observer = new ConcreteObserver();
observerSubject.addObserver(observer);
assertTrue(observerSubject.containsObserver(observer));
}
@Test
public void shouldRemoveAnObserver() {
ObserverSubject observerSubject = ObserverSubject.getInstance();
LocalObserver observer = new ConcreteObserver();
observerSubject.addObserver(observer);
observerSubject.removeObserver(observer);
assertFalse(observerSubject.containsObserver(observer));
}
@Test
public void shouldNotifyAllObservers() {
ObserverSubject observerSubject = ObserverSubject.getInstance();
LocalObserver observer0 = mock(ConcreteObserver.class);
LocalObserver observer1 = mock(ConcreteObserver.class);
observerSubject.addObserver(observer0);
observerSubject.addObserver(observer1);
observerSubject.notifyObservers();
verify(observer0,times(1)).react();
verify(observer1,times(1)).react();
}
}
<file_sep>/src/main/java/factoryMethod/ImageFactory.java
package factoryMethod;
public interface ImageFactory {
LocalImage getImage();
}
<file_sep>/src/main/java/state/StateKeys.java
package state;
public enum StateKeys {
OPEN("open"),
CLOSED("closed");
private final String key;
StateKeys(String key) {
this.key = key;
}
public String getKey() {
return this.key;
}
}
<file_sep>/README.md
## Design Patterns Examples
Design Patterns implementation examples
***
<file_sep>/src/main/java/adapter/VGAPortService.java
package adapter;
public class VGAPortService implements PortService {
@Override
public boolean connect() {
return true;
}
}
<file_sep>/src/main/java/observer/ObserverSubject.java
package observer;
import java.util.ArrayList;
import java.util.Collection;
public class ObserverSubject {
private static ObserverSubject instance = null;
private Collection<LocalObserver> observerList = new ArrayList<>();
public static ObserverSubject getInstance() {
if (instance == null) {
instance = new ObserverSubject();
}
return instance;
}
public void addObserver(LocalObserver observer) {
this.observerList.add(observer);
}
public boolean containsObserver(LocalObserver observer) {
return this.observerList.contains(observer);
}
public void removeObserver(LocalObserver observer) {
this.observerList.remove(observer);
}
public void notifyObservers() {
this.observerList.stream()
.forEach(localObserver -> localObserver.react());
}
}
| fda699c28cd8910789265cd8b557cbb67538b748 | [
"Markdown",
"Java"
] | 19 | Java | leandrodalbo/DesignPatterns | fd81d8ee3405c31459c0370339bb6ec51a0409f4 | a21fee4032b4803594f08adf722dd76aa2a88964 |
refs/heads/master | <repo_name>gcjensen/code-dojo-may<file_sep>/README.md
# Tic Tac Toe with an AI that learns as you play.
~~Learning algorithm is currently broken, but will be fixed.~~
Algorithm fixed.
<file_sep>/script.js
board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
results = []
score = [0, 0, 0]
// still playing?
inGame = 1
function initGame()
{
setMsg("Welcome");
newGame();
}
function newGame()
{
resetBoard()
setMsg("Your turn");
inGame = 1
}
function setMsg(msg)
{
document.getElementById("msg").innerHTML = msg;
}
// 0 = Human won
// 1 = Computor won
// 2 = draw
// -1 = not finished
function isFinished() {
if(board[0] == board[3] && board[3] == board[6]) {
if(board[0] == "X") {
return 0;
}
if(board[0] == "O") {
return 1;
}
}
if(board[1] == board[4] && board[4] == board[7]) {
if(board[1] == "X") {
return 0;
}
if(board[1] == "O") {
return 1;
}
}
if(board[2] == board[5] && board[5] == board[8]) {
if(board[2] == "X") {
return 0;
}
if(board[2] == "O") {
return 1;
}
}
if(board[0] == board[1] && board[1] == board[2]) {
if(board[0] == "X") {
return 0;
}
if(board[0] == "O") {
return 1;
}
}
if(board[3] == board[4] && board[4] == board[5]) {
if(board[3] == "X") {
return 0;
}
if(board[3] == "O") {
return 1;
}
}
if(board[6] == board[7] && board[7] == board[8]) {
if(board[6] == "X") {
return 0;
}
if(board[6] == "O") {
return 1;
}
}
if(board[0] == board[4] && board[4] == board[8]) {
if(board[0] == "X") {
return 0;
}
if(board[0] == "O") {
return 1;
}
}
if(board[2] == board[4] && board[4] == board[6]) {
if(board[2] == "X") {
return 0;
}
if(board[2] == "O") {
return 1;
}
}
for(i = 0; i < 9; ++i) {
if(!board[i]) {
return -1
}
}
return 2
}
// 0 = Human won
// 1 = Computor won
// 2 = draw
// -1 = not finished
function finish(i) {
msg = ""
if(i == 0) {
msg = "You win, congrats!"
} else if(i == 1) {
msg = "I won!"
} else {
msg = "A draw!"
}
setMsg(msg)
recordScore()
inGame = 0
}
// 0 = Human
// 1 = PC
function flip(x, who) {
if(!isFree(x)) {
return false;
}
button = getButton(x);
if(who) {
button.value = "O"
button.style.background="#f6c8c9"
board[x-1] = "O"
} else {
button.value = "X"
button.style.background="#bdcfea"
board[x-1] = "X"
}
return true
}
function getButton(x) {
return document.getElementById(x);
}
function tileClicked(x) {
if (!inGame) {
return
}
if (flip(x, 0)) {
if(isFinished() != -1) {
finish(isFinished())
} else {
takeMove()
}
}
}
function isFree(num) {
if(board[num-1] == 0) {
return true;
}
return false;
}
function AIperformTurn() {
do {
num = Math.floor((Math.random() * 9) + 1);
} while(!flip(num, 1))
if(isFinished() != -1) {
finish(isFinished());
}
}
function recordScore() {
var outcome = isFinished()
var completeGame = [outcome, board]
results.push(completeGame)
score[outcome]++
document.getElementById("humanScore").innerHTML = score[0];
document.getElementById("pcScore").innerHTML = score[1];
document.getElementById("drawScore").innerHTML = score[2];
}
function resetBoard() {
board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for (var i = 0; i < 9; i++) {
getButton(i+1).value = " "
getButton(i+1).style.background="#E0E0E0"
}
}
function takeMove() {
tally = [0, 0, 0, 0, 0, 0, 0, 0, 0];
if(results.length == 0) {
AIperformTurn()
} else {
results.forEach(function(result) {
for (var i = 0; i < result[1].length; i++) {
if (result[0] == 1 && result[1][i] == "O") {
tally[i] += 1
}
else if (result[0] == 0 && result[1][i] == "X") {
tally[i] += 1
}
}
});
var max_value = 0
var max_index = 0
var i = 0
for (i = 0; i < board.length; i++) {
// || board[max_index] != 0 is to
// make sure max_index points to an empty field
if ((tally[i] > max_value || board[max_index] != 0) && board[i] == 0) {
max_index = i
max_value = tally[i]
}
}
var ret = flip(max_index+1, 1)
if(isFinished() != -1) {
finish(isFinished())
}
}
}
| 20e353f482f4cd4c3f9f8ff2052a891b2901f8dc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | gcjensen/code-dojo-may | f2af9dbf37af80590117d3249d846a1a3b1fb811 | 71c2d164236cde346e04a25c504e96833330b6d1 |
refs/heads/master | <repo_name>bphillips95/react-updating-state-dumbo-web-111819<file_sep>/src/components/ClickityClick.js
import React, { Component } from 'react'
export default class ClickityClick extends Component {
state = {
count: 0
}
handleClick = (prevState) => {
this.setState(prevState => {
return { count: prevState+1
}
})
}
render() {
return (
<div>
<p>I have {this.state.count} times been clicked!</p>
<button onClick={this.handleClick}>Click Me!</button>
</div>
)
}
}
| 2f64b83fba2056de84e878ca011204a632a9f97e | [
"JavaScript"
] | 1 | JavaScript | bphillips95/react-updating-state-dumbo-web-111819 | 810b767053635c0b63a1f40a7a86df252110eb74 | e33a6800e079401780dbeb6f5205eb4626396d5b |
refs/heads/production | <file_sep>forge 'https://forge.puppet.com'
# CD4PE
mod 'puppetlabs-cd4pe', :latest
# Requirements for cd4pe
mod 'puppetlabs-concat', '4.2.1'
mod 'puppetlabs-hocon', '1.0.1'
mod 'puppetlabs-puppet_authorization', '0.5.0'
mod 'puppetlabs-stdlib', '4.25.1'
mod 'puppetlabs-docker', '3.3.0'
mod 'puppetlabs-apt', '6.2.1'
mod 'puppetlabs-translate', '1.1.0'
mod 'gabe-ngrok', '1.1.1'
mod 'puppet-archive', '1.0.0'
| bd15bce448895531198b98e3baee2a15acccb412 | [
"Ruby"
] | 1 | Ruby | hsnodgrass/cd4pe-control-repo | f1e3a7b0321c6725ba823089793bf3f0e3272384 | f72fdee3171c5ea3a749d684eaacc8d6a36575b6 |
refs/heads/main | <file_sep># Assembly_Language_Interpreter-C-
Build an Assembly Language Interpreter (ALI) for a Simple Assembly Language (SAL) in C++
This project is about building an Assembly Language Interpreter (ALI) for a Simple Assembly Language (SAL).
Fortunately for you SAL has a limited set of instructions, described below, which makes it easier to write the ALI.
SAL programs are executed on a virtual (emulated) machine consisting of a memory, which stores program code
and program data, an accumulator register, an additional register and a Program Counter (PC), which keeps track
of the instruction being currently executed. Your ALI can execute SAL programs one line at a time (in a sort of
debug mode) or at once until a halt instruction is encountered.
The execution of a ALI consists of the following three steps:
1. Prompt the user for a file name in the current directory.
2. Read a SAL from the file. The program is stored in the memory starting at address 0.
3. Execute a command loop consisting of three commands:
l – Executes a line of code, starting from line 0, updates the PC, the registers and memory according to
the instruction and prints the values of the registers, the zero and overflow bits, and memory after the
line is executed.
a – Executes all the instructions until a halt instruction is encountered or there are no more instructions
to be executed.
q – Quits the command loop.
The computer hardware uses 32-bit words and consists of the following components:
1. Memory. A 32-bit, word-addressable memory (RAM) for data, holding 256 words. Words are addressed by
their location, starting from location 0 all the way up to location 255. Each location may either hold a signed
integer in 2’s complement notation or a SAL instruction.
2. Accumulator. A 32-bit register. It is also known as Register A or A for short.
3. Additional register. A 32-bit register also known as Register B or B for short.
4. Program counter (PC). An 8-bit program counter (PC). The PC holds the address (number in program
memory) of the next instruction to be executed. Before the program starts execution, the PC holds the value 0. It is subsequently updated as each instruction is executed.
5. A zero-result bit. This bit is set if the last ADD instruction produced a zero result. This bit is cleared if the
last ADD instruction produced a result different from zero. The initial value is zero. The bit is changed only
after ADD instructions are executed.
6. An overflow bit. This bit is set whenever an ADD instruction produces an overflow (i.e., a result that cannot
be stored in 2’s complement notation with 32 bits). It is cleared if the ADD instruction did not produce an
overflow. The initial value is zero.
1.DEC symbol - Declares a symbolic variable consisting of a single letter (e.g., X). The
variable is stored at the memory location of this instruction.
2.LDA symbol - Loads byte at data memory address of symbol into the accumulator.
3.LDB symbol - Loads byte at data memory address symbol into B.
4.LDI value - Loads the integer value into the accumulator register. The value could be negative.
5.STR symbol - Stores content of accumulator into data memory at address of symbol.
6.XCH Exchanges - the content registers A and B.
7.JMP number - Transfers control to instruction at address number in program memory.
8.JZS number - Transfers control to instruction at address number if the zero-result bit is set.
9.JVS number - Transfers control to instruction at address number if the overflow bit is set.
10.ADD Adds - the content of registers A and B. The sum is stored in A. The overflow and zero-result bits are set or cleared as needed.
11.HLT Terminates program execution.
Table 1: Instruction set of SAL.
The registers are used to hold data for arithmetic operations (i.e., additions). The program counter holds the
index value (starting at 0) of the next instruction to be executed. SAL has the instruction set shown in Table 1.
<file_sep>#include <dirent.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <array>
#include <map>
#include <string.h>
#include <stdio.h>
using namespace std;
class Registers{
public:
std::vector<std::string> memory;
int accumulator = 0;
int additional_register = 0;
int program_counter = 0;
int zero_result_bit = 0;
int overflow_bit = 0;
std::map<std::string, int> data;
};
class interpret: public Registers{
public:
int interpreter(const std::string& sal_per_line) {
std::string instruction = sal_per_line.substr(0, 3);
if (sal_per_line.length() > 3)
{
std::string symbol = sal_per_line.substr(4);
if (instruction == "DEC")
{
memory[program_counter] = symbol;
data.insert(pair<std::string, int>(symbol, 0));
std::cout <<"Variable "<< symbol<<" declares " << std::endl;
}
else if (instruction == "LDA")
{
accumulator = data[symbol];
std::cout <<"Byte at data at memory address of "<< symbol<<" loaded into the accumulator" << std::endl;
}
else if (instruction == "LDB")
{
additional_register = data[symbol];
std::cout <<symbol <<" loaded into additional_register " << std::endl;
}
else if (instruction == "LDI")
{
accumulator = std::stoi(symbol);
std::cout <<symbol <<" loaded into accumulator " << std::endl;
}
else if (instruction == "STR")
{
data[symbol] = accumulator;
std::cout <<accumulator <<" stored at " <<symbol << std::endl;
}
else if (instruction == "JMP")
{
program_counter = std::stoi(symbol);
std::cout <<"Transfered control to instruction at address " <<symbol << std::endl;
return 0;
}
else if (instruction == "JZS")
{
if (zero_result_bit == 1){
program_counter = std::stoi(symbol);
std::cout <<"Transfered control to instruction at address " <<symbol <<" as zero-result bit is set."<< std::endl;
return(0);
}
}
else if (instruction == "JVS")
{
if(overflow_bit == 1) {
program_counter = std::stoi(symbol);
std::cout <<"Transfered control to instruction at address " <<symbol<<" as overflow_bit is set."<< std::endl;
return (0);
}
}
}
else if (instruction=="HLT")
{
std::cout << "******Reached Halt******" << std::endl;
}
else if(instruction=="XCH") {
int temp = accumulator;
accumulator = additional_register;
additional_register = temp;
std::cout << "Content of accumulator and additional_register exchanged " << std::endl;
}
else if(instruction=="ADD")
{
int result=accumulator + additional_register;
if ((accumulator>0 && additional_register>0 && result<0) || (accumulator<0 && additional_register<0 && result>0))
{
overflow_bit = 1;
std::cout << "overflow_bit is set" << std::endl;
}
else
overflow_bit = 0;
std::cout << accumulator<<" and " << additional_register <<" added"<< std::endl;
accumulator = accumulator + additional_register;
if (accumulator == 0)
{
zero_result_bit = 1;
std::cout << "zero_result_bit is set" << std::endl;
}
}
else{
std::cout << "Incorrect SAL command." << std::endl;
}
program_counter++;
std::cout << "program_counter updated "<< program_counter<< std::endl;
return(0);
}
};
int main()
{
interpret intp;
//To run 'l' after 'a'
// std::vector<std::string> source_code;
std::vector<std::string> files;
DIR *d;
char *p1,*p2;
struct dirent *dir;
d = opendir(".");//Note: current working directory is cmake-build-debug,where Project4.exe exists with SAL.
if (d)
{
while ((dir = readdir(d)) != nullptr)
{
p1=strtok(dir->d_name,".");
p2=strtok(nullptr,".");
if(p2!=nullptr)
{
if(strcmp(p2,"txt")==0 && strcmp(p1, "CMakeCache") != 0)
{
std::cout << p1 << std::endl;
files.emplace_back(p1);
}
}
}
closedir(d);
}
std::cout <<"Please choose any SAL file above and enter it's name:"<< std::endl;
std::string input;
std::cin >> input;
if (std::find(files.begin(), files.end(), input) != files.end())
{
string line;
ifstream myfile (input+".txt");
int i=0;
while ( myfile.good() )
{
getline (myfile,line);
intp.memory.push_back(line);
i++;
if(i==256){
std::cout << "Memory is full" << std::endl;
break;
}
}
myfile.close();
//To run 'l' after 'a'
// source_code=intp.memory;
}
int f=1;
while(f)
{
std::cout <<
"\nEnter any of these command:\n"
"l : To execute a line of code.\n"
"a : To execute all instruction.\n"
"q : To quit."
<< std::endl;
char c;
std::cin >> c;
switch(c) {
case 'l' : {
ptrdiff_t pos = find(intp.memory.begin(), intp.memory.end(), "HLT") - intp.memory.begin();
if (std::count(intp.memory.begin(), intp.memory.end(), "HLT") && intp.program_counter == pos + 1 ) {
std::cout <<"You reached the HLT statement"<< std::endl;
}
else if(intp.program_counter == pos){
std::cout <<"You reached the end of instructions"<< std::endl;
}
else{
intp.interpreter(intp.memory[intp.program_counter]);
std::cout <<
"\n***All the instructions are executed***\n"
"Accumulator A="<< intp.accumulator<< "\n"<<
"Additional register B= "<< intp.additional_register<< "\n"<<
"Zero result bit ="<< intp.zero_result_bit<< "\n"<<
"Overflow bit = "<< intp.overflow_bit<< "\n"<<
"Program counter = "<< intp.program_counter
<< std::endl;
std::cout << "Memory:" <<", "; //print memory content
for (auto & i : intp.memory)
std::cout << i<<", ";
std::cout <<"\n"<< std::endl;
}
continue;
}
case 'a' : {
ptrdiff_t pos = find(intp.memory.begin(), intp.memory.end(), "HLT") - intp.memory.begin();
if (std::count(intp.memory.begin(), intp.memory.end(), "HLT")) {
while (intp.program_counter != pos + 1)
intp.interpreter(intp.memory[intp.program_counter]);
}
else{
while (intp.program_counter != pos)
intp.interpreter(intp.memory[intp.program_counter]);
}
std::cout <<
"\n***All the instructions are executed***\n"
"Accumulator A="<< intp.accumulator<< "\n"<<
"Additional register B= "<< intp.additional_register<< "\n"<<
"Zero result bit ="<< intp.zero_result_bit<< "\n"<<
"Overflow bit = "<< intp.overflow_bit<< "\n"<<
"Program counter = "<< intp.program_counter
<< std::endl;
std::cout << "Memory:" <<", "; //print memory content
for (auto & i : intp.memory)
std::cout << i<<", ";
//If we want to use 'l' after 'a' from address 0.
// intp.memory=source_code;
// intp.accumulator = 0;
// intp.additional_register = 0;
// intp.program_counter = 0;
// intp.zero_result_bit = 0;
// intp.overflow_bit = 0;
// intp.data.clear();
continue;
}
case 'q' :{
std::cout << "\nQuitting from command loop" << std::endl;
f = 0;
break;
}
default :
std::cout << "Command loop does not recognize " << c << std::endl;
continue;
}
}
return(0);
}
| 4ae6b8c8f36a061f7e187e4e351e8e4e2bbe897e | [
"Markdown",
"C++"
] | 2 | Markdown | Ankitmark/Assembly_Language_Interpreter-C- | a576fd9ca356a41d35d7edacd7f8f2b426ad519f | 2a268bdefddd1e492af039fa3fa39373368d7584 |
refs/heads/master | <repo_name>AIBrainOrganization/DialoGPT<file_sep>/bot.py
from interact import load, append_messages, generate_message
class Bot:
def __init__(self, vocab_path, model_path, reverse_model_path):
self.vocab, self.model, self.reverse_model, self.end_token = load(
vocab_path, model_path, reverse_model_path)
self.messages = {}
def reply(self, message, emotion, id):
if id not in self.messages:
self.messages[id] = []
append_messages(self.messages[id], [message], self.vocab, self.end_token)
response = generate_message(
self.messages[id], self.model, self.reverse_model, self.vocab, False)
append_messages(self.messages[id], [response], self.vocab, self.end_token)
return response, 'Neutral'
<file_sep>/interact.py
import torch
import argparse
from config import device_f, device_r, num_samples
from config import top_k, top_p, ALPHA
from kogpt2.pytorch_kogpt2 import get_kogpt2_model
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.utils import get_tokenizer
PADDING_TOKEN = 0
torch.set_grad_enabled(False)
# 토크나이저를 불러옵니다.
tok_path = get_tokenizer()
tokenizer = SentencepieceTokenizer(tok_path)
# 사전, 모델, 리버스 모델을 불러옵니다.
def load(vocab_path, model_path, reverse_path):
# 모델과 사전을 불러옵니다.
model, vocab = get_kogpt2_model(model_path, vocab_path, 0)
if device_f == 'cuda':
model.half()
model.to(device_f)
model.eval()
# 리버스 모델을 불러옵니다.
reverse_model, _ = get_kogpt2_model(reverse_path, vocab_path, 0)
if device_r == 'cuda':
reverse_model.half()
reverse_model.to(device_r)
reverse_model.eval()
end_token = torch.tensor([[vocab[vocab.eos_token]]], dtype=torch.long)
return vocab, model, reverse_model, end_token
# 각 답변의 점수를 계산합니다.
def _score_response(input, input_reversed, output, model, reverse_model):
# input, label, mask를 준비합니다.
output_reversed = output.to(device_r)
inputs = torch.cat((input, output[:, :-1]), dim=1)
inputs_reversed = torch.cat((output_reversed, input_reversed[:, :-1]), dim=1)
mask = torch.full_like(input[:, :-1], -1, dtype=torch.long)
labels = torch.cat((mask, output), dim=1)
mask_reversed = torch.full_like(output_reversed[:, :-1],
-1,
dtype=torch.long)
labels_reversed = torch.cat((mask_reversed, input_reversed), dim=1)
# 점수로 활용될 loss 값을 계산합니다.
loss, *_ = model(inputs, labels=labels)
reverse_loss, *_ = reverse_model(inputs_reversed, labels=labels_reversed)
# ALPHA 값으로 비중을 주고 loss를 점수로 변경하기 위해 -1을 곱해줍니다.
return -(ALPHA * loss.float() + (1 - ALPHA) * reverse_loss.float())
# 히스토리에 새 문장을 추가해줍니다.
def append_messages(old_list: list,
new_list: list,
vocab,
end_token,
truncate_length=64):
for message in new_list:
if message != '':
# 문장을 tokenizing합니다.
input_token = torch.tensor([vocab[tokenizer(message)]], dtype=torch.long)
input_token = torch.cat((input_token, end_token), dim=1)
old_list.append(input_token)
if len(old_list) == 0:
old_list.append(end_token)
# truncate
total_length = 0
for i, message in enumerate(reversed(old_list)):
total_length += message.shape[1]
if total_length > truncate_length:
old_list[:] = old_list[-i:]
# 생성된 token들을 문장으로 바꿔줍니다.
def decode(ids, vocab, skip_special_tokens=True):
gen = vocab.to_tokens(ids)
sent = ''
for word in gen:
word = word.replace('▁', ' ')
word = word.replace(' !', '!')
word = word.replace(' .', '.')
word = word.replace(' ?', '?')
word = word.replace(' ,', ',')
if skip_special_tokens:
word = word.replace('<unk>', '')
word = word.replace('<s>', '')
word = word.replace('</s>', '')
sent += word
return sent[1:]
# 답변 문장을 생성합니다.
def generate_message(message_list: list,
model,
reverse_model,
vocab,
focus_last_message=True):
total_input = torch.cat(message_list, dim=1).to(device_f)
if focus_last_message:
total_input_reversed = message_list[-1]
else:
total_input_reversed = torch.cat(list(reversed(message_list)), dim=1)
# https://huggingface.co/transformers/main_classes/model.html?highlight=generate#transformers.PreTrainedModel.generate
# 후보 답변 문장들을 생성합니다.
outputs = model.generate(input_ids=total_input,
min_length=total_input.shape[1] + 8,
max_length=total_input.shape[1] + 40,
num_return_sequences=num_samples,
top_k=top_k,
top_p=top_p,
do_sample=True,
repetition_penalty=1.2,
pad_token_id=PADDING_TOKEN,
eos_token_id=vocab[vocab.eos_token])
outputs = outputs[:, total_input.shape[1]:]
# 각 문장에 대해 점수를 계산합니다.
scores = []
for output in outputs:
output = output.unsqueeze(0).to(device_f)
try:
output = output[:, :output[0].tolist().index(vocab[vocab.eos_token]) + 1]
except Exception:
pass
scores.append(
_score_response(total_input, total_input_reversed.to(device_r), output,
model, reverse_model))
scores = torch.stack(scores, dim=0)
# 가장 점수가 높은 문장을 선택합니다.
winner = torch.argmax(scores).item()
out = outputs[winner]
return decode(out.tolist(), vocab)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Interact with the model.')
parser.add_argument('vocab_path',
metavar='vocab_path',
type=str,
help='Vocabulary path')
parser.add_argument('model_path',
metavar='model_path',
type=str,
help='Model path')
parser.add_argument('reverse_model_path',
metavar='reverse_model_path',
type=str,
help='Reverse model path')
args = parser.parse_args()
# 사전, 모델 파일 및 end_token을 불러옵니다.
vocab, model, reverse_model, end_token = load(args.vocab_path,
args.model_path,
args.reverse_model_path)
my_message_list = [] # 대화 히스토리 리스트
while True:
my_message = input('usr >> ')
# 대화 히스토리에 사용자가 입력한 내용을 추가합니다.
append_messages(my_message_list, [my_message], vocab, end_token)
# 대화 히스토리를 바탕으로 답변을 생성합니다.
my_response = generate_message(my_message_list, model, reverse_model,
vocab, False)
print('bot >>', my_response)
# 답변을 대화 히스토리에 추가합니다.
append_messages(my_message_list, [my_response], vocab, end_token)
<file_sep>/data/to_tsv.py
from openpyxl import load_workbook
from tqdm import tqdm
import pandas as pd
import argparse
import sys
sys.path.append('/home/calee/git/dcinside')
from filter import Comment
from filter import filter_rows
from filter import add_tags
from clean import clean_str
def create_rows(xlsxes):
train = []
valid = []
test = []
r = []
conv_id = 0
for xlsx in xlsxes:
firstSSeen = False
wb = load_workbook(xlsx)
ws = wb.active
for i, row in enumerate(tqdm(ws.rows)):
if not firstSSeen:
if row[0].value == 'S':
firstSSeen = True
else:
continue
if row[0].value == "S":
if r:
handle = train
if conv_id % 10 == 0:
handle = test
elif conv_id % 10 == 1:
handle = valid
handle.append(r)
conv_id += 1
r = []
c = Comment(clean_str(row[1].value))
add_tags(c)
r.append(c)
handle = train
if conv_id % 10 == 0:
handle = test
elif conv_id % 10 == 1:
handle = valid
handle.append(r)
conv_id += 1
r = []
return train, valid, test
def main():
xlsxes = ['/home/calee/git/cc/data/KoMulti20200320/'
'OpenSubwithemotion2018.xlsx',
'/home/calee/git/cc/data/KoMulti20200320/'
'acryl_korean_190226_unique.xlsx',
'/home/calee/git/cc/data/KoMulti20200320/'
'acryl_korean_180504.xlsx']
rows = create_rows(xlsxes)
filtered = [filter_rows(r) for r in rows]
df = [pd.DataFrame(f) for f in filtered]
names = ['train_bland.tsv', 'valid_bland.tsv', 'test_bland.tsv']
for i, d in enumerate(df):
d.to_csv(names[i], sep='\t', header=False, index=False)
if __name__ == '__main__':
main()
<file_sep>/data/README.md
## How to create a DB
1. Prepare a tsv file.
It has two columns.
First column is source sentences and the second column is a target sentence.
Source sentences are separated by EOS.
Each sentence has 0.0 or 1.0 before the sentence, which is a weight to indicate whether the sentence should be trained or not. (1.0 means the sentence needs to be learned.)
2. Run prepro.py
```bash
python prepro.py --corpus {path to the tsv} --max_seq_len 200
```
<file_sep>/docker/Dockerfile
FROM nvidia/cuda:10.1-base
WORKDIR /git/DialoGPT
RUN apt update
RUN apt install -y wget
RUN apt install -y gcc
RUN wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
RUN bash Anaconda3-2020.02-Linux-x86_64.sh -b -p ~/anaconda3
SHELL ["/bin/bash", "--login", "-c"]
RUN sed -i '1 i\. ~/anaconda3/etc/profile.d/conda.sh' ~/.bashrc
RUN echo ~/.bashrc
COPY DialoGPT/LSP-linux.yml /root/LSP-linux.yml
COPY KoGPT2/requirements.txt /root/requirements.txt
RUN conda env create -f /root/LSP-linux.yml -n LSP
RUN conda run -n LSP pip install -r /root/requirements.txt
RUN conda run -n LSP pip install flask
COPY KoGPT2 /git/KoGPT2
RUN conda run -n LSP pip install /git/KoGPT2
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
ENV FLASK_APP=server.py
<file_sep>/data/filter_bland.py
from tqdm import tqdm
import pandas as pd
import json
import argparse
import os
import re
from dcinside.filter import text_to_words
from dcinside.filter import Comment
from dcinside.filter import filter_rows
TRIGRAMS_PATH = 'trigrams'
FILE_PATHS = ['train_bland.tsv', 'valid_bland.tsv', 'test_bland.tsv']
SPLIT_PATTERN = re.compile(r' EOS (?=[01]\.0)')
def get_trigrams(s):
s = text_to_words(s)
return [s[i:i + 3] for i in range(len(s) - 2)]
def split(source):
return SPLIT_PATTERN.split(source)
def read_or_create_trigrams(path):
try:
with open(os.path.join(path, TRIGRAMS_PATH)) as f:
trigrams = json.load(f)
except IOError:
trigrams = {}
for file in FILE_PATHS:
df = pd.read_csv(os.path.join(path, file), sep='\t', header=None)
for _, line in tqdm(df.iterrows(), total=len(df.index), desc='create trigrams'):
source, target = line
source = split(source)
sentences = source
sentences.append(target)
sentences = [s[4:] for s in sentences if int(s[0])]
sentences = [[' '.join(t) for t in get_trigrams(s)] for s in sentences]
for s in sentences:
for t in s:
if t in trigrams:
trigrams[t] += 1
else:
trigrams[t] = 1
with open(os.path.join(path, TRIGRAMS_PATH), 'w') as f:
f.write(json.dumps(trigrams))
s = sorted(trigrams.items(), key=lambda k: -k[1])
global BLAND_THRESHOLD
BLAND_THRESHOLD = s[BLAND_TOP][1]
return trigrams
BLAND_TOP = 10000
BLAND_THRESHOLD = None
def check_bland(s, trigrams):
ts = [' '.join(t) for t in get_trigrams(s)]
n = 0
for t in ts:
if trigrams[t] > BLAND_THRESHOLD:
n += 1
try:
return n / len(ts) >= 0.9
except ZeroDivisionError:
return False
def create_rows(trigrams, path):
ret = []
for file in FILE_PATHS:
rows = []
df = pd.read_csv(os.path.join(path, file), sep='\t', header=None)
for _, line in tqdm(df.iterrows(), total=len(df.index), desc='create rows'):
source, target = line
sentences = split(source)
sentences.append(target)
sentences = [Comment(s[4:], [] if int(s[0]) else ['bad'])
for s in sentences]
for s in sentences:
if len(s.tags) == 0 and check_bland(s.comment, trigrams):
if len(text_to_words(s.comment)) > 3:
print(s.comment)
s.tags.append('bland')
rows.append(sentences)
ret.append(rows)
return ret
def main():
parser = argparse.ArgumentParser(description='Filter bland phrases.')
parser.add_argument('path', metavar='path', type=str, help='Directory path')
args = parser.parse_args()
trigrams = read_or_create_trigrams(args.path)
rowss = create_rows(trigrams, args.path)
filtered = [filter_rows(r) for r in rowss]
df = [pd.DataFrame(f) for f in filtered]
names = ['train.tsv', 'valid.tsv', 'test.tsv']
for i, d in enumerate(df):
d.to_csv(os.path.join(args.path, names[i]), sep='\t', header=False, index=False)
if __name__ == '__main__':
main()
<file_sep>/docker/docker-compose.yml
version: "2"
services:
app:
container_name: dialogue-system
build:
context: ../..
dockerfile: DialoGPT/docker/Dockerfile
ports:
- "5005:5000"
volumes:
- ..:/git/DialoGPT
<file_sep>/data/format.py
import argparse
import re
import os
def format_line(line):
line = re.sub(r'\\+"([^\n])', '""\\1', line)
line = re.sub(r'\\+\'', '\'', line)
line = re.sub(r'\\', '', line)
return line
def main():
parser = argparse.ArgumentParser(
description='Format csv files for pandas')
parser.add_argument('input', metavar='input', type=str,
help='Input path')
parser.add_argument('output', metavar='output', type=str, help='Save path')
args = parser.parse_args()
train = open(os.path.join(args.output, 'train.tsv'), 'w')
valid = open(os.path.join(args.output, 'valid.tsv'), 'w')
test = open(os.path.join(args.output, 'test.tsv'), 'w')
with open(args.input) as input:
for i, line in enumerate(input):
line = format_line(line)
output = train
if i % 10 == 0:
output = valid
elif i % 10 == 1:
output = test
output.write(line)
train.close()
valid.close()
test.close()
if __name__ == "__main__":
main()
<file_sep>/server.py
from flask import Flask, request
from bot import Bot
from config import vocab_path, model_path, reverse_model_path
import json
bot = Bot(vocab_path, model_path, reverse_model_path)
emotion_map = {10001: 'Happiness', 10002: 'Anger', 10003: 'Disgust',
10004: 'Fear', 10005: 'Neutral', 10006: 'Sadness',
10007: 'Surprise'}
app = Flask(__name__)
@app.route('/', methods=['GET'])
def server():
utext = request.args.get('utext')
emotion = request.args.get('emotion')
print(utext)
uid = request.args.get('uid')
ret_text, ret_emotion = bot.reply(utext, emotion_map[int(emotion)], uid)
for key, emotion in emotion_map.items():
if emotion == ret_emotion:
ret_emotion = key
break
ret = (ret_text, ret_emotion)
return json.dumps({'text': ret[0], 'emotion': ret[1]},
ensure_ascii=False).encode('utf8')
if __name__ == '__main__':
app.run(host="0.0.0.0")
<file_sep>/LSP_valid.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
* @Desc: train GPT2 from scratch/ fine tuning.
Modified based on Huggingface GPT-2 implementation
'''
import json
import os
import sys
import argparse
import logging
import datetime
import torch
import numpy as np
from os.path import join
from tqdm import tqdm
from torch.distributed import get_rank
from gpt2_training.train_utils import boolean_string
from gpt2_training.eval_utils import eval_model_loss
from data_loader import BucketingDataLoader
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.utils import get_tokenizer
from kogpt2.pytorch_kogpt2 import get_kogpt2_model
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
conf_logger = logging.getLogger('transformers.configuration_utils')
conf_logger.setLevel(logging.WARNING)
INF = 100000000
CACHE_EMPTY_STEP = 10000
EVAL_STEP = 100000
#########################################################################
# Prepare Parser
##########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path',
type=str,
help='pretrained model name or path to local checkpoint')
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--max_seq_length", type=int, default=128)
parser.add_argument("--skip_eval",
action='store_true',
help='If true, skip evaluation.')
parser.add_argument("--init_checkpoint", type=str)
parser.add_argument("--train_input_file", type=str)
parser.add_argument("--eval_input_file", type=str)
parser.add_argument("--continue_from", type=int, default=0)
parser.add_argument("--train_batch_size",
type=int,
default=4,
help="batch size now means per GPU per step")
parser.add_argument("--gradient_accumulation_steps",
type=int,
default=2,
help="to increase effective batch size "
"and reduce synchronization")
parser.add_argument("--eval_batch_size", type=int, default=4)
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--num_optim_steps",
type=int,
default=1000000,
help="new API specifies num update steps")
parser.add_argument("--valid_step",
type=int,
default=10000,
help="how many optim steps between validations")
parser.add_argument("--warmup_proportion", type=float, default=0.1)
parser.add_argument("--warmup_steps", type=int, default=16000)
parser.add_argument("--normalize_data", type=boolean_string, default=True)
parser.add_argument("--fp16", type=boolean_string, default=True)
parser.add_argument("--lr_schedule",
type=str,
choices=['noam', 'noamwd', 'BERT', 'None'],
default='noam')
parser.add_argument("--loss_scale", type=float, default=0)
parser.add_argument("--no_token_id", type=boolean_string, default=True)
parser.add_argument("--output_dir", type=str)
parser.add_argument("--log_dir", type=str)
parser.add_argument('--pbar',
type=boolean_string,
default=True,
help='turn on progress bar')
# distributed
parser.add_argument('--local_rank',
type=int,
default=-1,
help='for torch.distributed')
parser.add_argument('--config', help='JSON config file')
# do normal parsing
args = parser.parse_args()
if args.config is not None:
# override argparse defaults by config JSON
opts = json.load(open(args.config))
for k, v in opts.items():
if isinstance(v, str):
# PHILLY ENV special cases
if 'PHILLY_JOB_DIRECTORY' in v:
v = v.replace('PHILLY_JOB_DIRECTORY',
os.environ['PHILLY_JOB_DIRECTORY'])
elif 'PHILLY_LOG_DIRECTORY' in v:
v = v.replace('PHILLY_LOG_DIRECTORY',
os.environ['PHILLY_LOG_DIRECTORY'])
setattr(args, k, v)
# command line should override config JSON
argv = sys.argv[1:]
overrides, _ = parser.parse_known_args(argv)
for k, v in vars(overrides).items():
if f'--{k}' in argv:
setattr(args, k, v)
setattr(args, 'local_rank', overrides.local_rank)
assert args.train_batch_size % args.gradient_accumulation_steps == 0, \
'batch size % gradient accumulation steps != 0!'
args.train_batch_size = (args.train_batch_size //
args.gradient_accumulation_steps)
logger.info('train batch size = {}, '
'new train batch size (after gradient accumulation) = {}'.format(
args.train_batch_size * args.gradient_accumulation_steps,
args.train_batch_size))
if args.local_rank == -1:
logger.info('CUDA available? {}'.format(str(torch.cuda.is_available())))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
args.device, args.n_gpu = device, n_gpu
else:
# distributed training
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
# Initializes the distributed backend which will take care of
# sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
n_gpu = torch.distributed.get_world_size()
args.device, args.n_gpu = device, 1
logger.info("device: {} n_gpu: {}, distributed training: {}, "
"16-bits training: {}".format(device, n_gpu,
bool(args.local_rank != -1),
args.fp16))
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d%H%M%S')
output_dir = join(
args.output_dir,
'GPT2.{}.{}.{}gpu.{}'.format(args.learning_rate, args.train_batch_size,
n_gpu, timestamp))
log_dir = args.log_dir if args.log_dir is not None and len(
args.log_dir) > 0 else output_dir
if args.local_rank == -1 or get_rank() == 0:
os.makedirs(output_dir, exist_ok=True)
logger.info('Input Argument Information')
args_dict = vars(args)
for a in args_dict:
logger.info('%-28s %s' % (a, args_dict[a]))
#########################################################################
# Prepare Data Set
##########################################################################
# enc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
tok_path = get_tokenizer()
enc = SentencepieceTokenizer(tok_path)
VOCAB_PATH = '/home/calee/kogpt2/kogpt2_news_wiki_ko_cased_818bfa919d.spiece'
if args.local_rank == -1 or get_rank() == 0:
train_logger = open(join(log_dir, 'train_log.txt'), 'a+', buffering=1)
eval_logger = open(join(log_dir, 'eval_log.txt'), 'a+', buffering=1)
print(
'epoch,global_step,step,mean_loss,mean_ppl,n_token_real,'
'n_token_total,epoch_time',
file=train_logger)
print('epoch,global_step,step,eval_loss,eval_ppl', file=eval_logger)
filenames = os.listdir(args.init_checkpoint)
filenames = [f for f in filenames if f.endswith('.pkl')]
filenames = sorted(filenames, key=lambda x: int(x[18:x.index('.')]))
for filename in tqdm(filenames):
global_step = int(filename[18:filename.index('.')])
model_path = os.path.join(args.init_checkpoint, filename)
model, vocab = get_kogpt2_model(model_path, VOCAB_PATH, 0)
if args.fp16:
logger.info('in fp16, model.half() activated')
model.half()
if args.n_gpu > 1:
logging.info('data parallel because more than one gpu')
model = torch.nn.DataParallel(model)
eval_dataloader_loss = BucketingDataLoader(args.eval_input_file,
args.eval_batch_size,
args.max_seq_length)
if args.local_rank == -1 or get_rank() == 0:
eval_loss, eval_ppl = eval_model_loss(model, enc, eval_dataloader_loss,
args)
print(f'{global_step + 1},{eval_loss},{eval_ppl}', file=eval_logger)
if args.local_rank == -1 or get_rank() == 0:
train_logger.close()
eval_logger.close()
<file_sep>/sample.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
* @Desc: train GPT2 from scratch/ fine tuning.
Modified based on Huggingface GPT-2 implementation
'''
import json
import os
import sys
import argparse
import logging
import time
import datetime
import torch
import random
import numpy as np
from os.path import join
from tqdm import tqdm
from torch.distributed import get_rank, get_world_size
from interact import generate_message
from interact import decode
from lsp_model import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config, Adam
from gpt2_training.train_utils import load_model, boolean_string, set_lr, get_eval_list_same_length
from data_loader import BucketingDataLoader, DynamicBatchingLoader, DistributedBucketingDataLoader
from gpt2_training.distributed import all_reduce_and_rescale_tensors, all_gather_list
from kogpt2.pytorch_kogpt2 import get_pytorch_kogpt2_model
from kogpt2.pytorch_kogpt2 import kogpt2_config as config
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.utils import get_tokenizer
from pytorch_memlab import MemReporter
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
INF = 100000000
CACHE_EMPTY_STEP = 10000
EVAL_STEP = 100000
#########################################################################
# Prepare Parser
##########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path',
type=str,
help='pretrained model name or path to local checkpoint')
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--max_seq_length", type=int, default=128)
parser.add_argument("--skip_eval",
action='store_true',
help='If true, skip evaluation.')
parser.add_argument("--init_checkpoint", type=str)
parser.add_argument("--train_input_file", type=str)
parser.add_argument("--eval_input_file", type=str)
parser.add_argument("--continue_from", type=int, default=0)
parser.add_argument("--train_batch_size",
type=int,
default=4,
help="batch size now means per GPU per step")
parser.add_argument("--gradient_accumulation_steps",
type=int,
default=2,
help="to increase effective batch size "
"and reduce synchronization")
parser.add_argument("--eval_batch_size", type=int, default=4)
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--num_optim_steps",
type=int,
default=1000000,
help="new API specifies num update steps")
parser.add_argument("--valid_step",
type=int,
default=10000,
help="how many optim steps between validations")
parser.add_argument("--warmup_proportion", type=float, default=0.1)
parser.add_argument("--warmup_steps", type=int, default=16000)
parser.add_argument("--normalize_data", type=boolean_string, default=True)
parser.add_argument("--fp16", type=boolean_string, default=True)
parser.add_argument("--lr_schedule",
type=str,
choices=['noam', 'noamwd', 'BERT', 'None'],
default='noam')
parser.add_argument("--loss_scale", type=float, default=0)
parser.add_argument("--no_token_id", type=boolean_string, default=True)
parser.add_argument("--output_dir", type=str)
parser.add_argument("--log_dir", type=str)
parser.add_argument('--pbar',
type=boolean_string,
default=True,
help='turn on progress bar')
# distributed
parser.add_argument('--local_rank',
type=int,
default=-1,
help='for torch.distributed')
parser.add_argument('--config', help='JSON config file')
# do normal parsing
args = parser.parse_args()
if args.config is not None:
# override argparse defaults by config JSON
opts = json.load(open(args.config))
for k, v in opts.items():
if isinstance(v, str):
# PHILLY ENV special cases
if 'PHILLY_JOB_DIRECTORY' in v:
v = v.replace('PHILLY_JOB_DIRECTORY',
os.environ['PHILLY_JOB_DIRECTORY'])
elif 'PHILLY_LOG_DIRECTORY' in v:
v = v.replace('PHILLY_LOG_DIRECTORY',
os.environ['PHILLY_LOG_DIRECTORY'])
setattr(args, k, v)
# command line should override config JSON
argv = sys.argv[1:]
overrides, _ = parser.parse_known_args(argv)
for k, v in vars(overrides).items():
if f'--{k}' in argv:
setattr(args, k, v)
setattr(args, 'local_rank', overrides.local_rank)
assert args.train_batch_size % args.gradient_accumulation_steps == 0, \
'batch size % gradient accumulation steps != 0!'
args.train_batch_size = (args.train_batch_size //
args.gradient_accumulation_steps)
logger.info('train batch size = {}, '
'new train batch size (after gradient accumulation) = {}'.format(
args.train_batch_size * args.gradient_accumulation_steps,
args.train_batch_size))
if args.local_rank == -1:
logger.info('CUDA available? {}'.format(str(torch.cuda.is_available())))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
args.device, args.n_gpu = device, n_gpu
else:
# distributed training
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
# Initializes the distributed backend which will take care of
# sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
n_gpu = torch.distributed.get_world_size()
args.device, args.n_gpu = device, 1
logger.info("device: {} n_gpu: {}, distributed training: {}, "
"16-bits training: {}".format(device, n_gpu,
bool(args.local_rank != -1),
args.fp16))
random.seed(args.seed)
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d%H%M%S')
output_dir = join(
args.output_dir,
'GPT2.{}.{}.{}gpu.{}'.format(args.learning_rate, args.train_batch_size,
n_gpu, timestamp))
log_dir = args.log_dir if args.log_dir is not None and len(
args.log_dir) > 0 else output_dir
if args.local_rank == -1 or get_rank() == 0:
os.makedirs(output_dir, exist_ok=True)
logger.info('Input Argument Information')
args_dict = vars(args)
for a in args_dict:
logger.info('%-28s %s' % (a, args_dict[a]))
#########################################################################
# Prepare Data Set
##########################################################################
# enc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
eval_dataloader_loss = BucketingDataLoader(args.eval_input_file,
args.eval_batch_size,
args.max_seq_length,
shuffle=False)
data = []
for batch in eval_dataloader_loss:
data.append(batch)
EOS = 1
for step, batch in enumerate(tqdm(data[-30:])):
batch = tuple(t.to(args.device) for t in batch)
input_ids, *_ = batch
# input_ids = input_ids[:, :random.sample(
# (input_ids == 1).nonzero().tolist(), 1)[0][1] + 1]
indexes = (input_ids == 1).nonzero().tolist()
try:
input_ids = input_ids[:, :indexes[min(2, len(indexes) - 1)][1] + 1]
except:
import pdb
pdb.set_trace()
ids = [[]]
idx = 0
for id in input_ids.tolist()[0]:
ids[idx].append(id)
if id == EOS:
ids.append([])
idx += 1
ids = ids[:-1]
message = generate_message([torch.tensor([id]) for id in ids])
print(
f'{decode(input_ids[0].tolist(), skip_special_tokens=False)}\t{message}')
<file_sep>/docker/run.sh
#!/bin/bash
docker run --gpus 1 -v "$PWD/..":/git/DialoGPT -p 5000:5000 calee/dialogpt /bin/bash --login -c "conda activate LSP; python server.py"
<file_sep>/LSP_train.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
* @Desc: train GPT2 from scratch/ fine tuning.
Modified based on Huggingface GPT-2 implementation
'''
import json
import os
import sys
import argparse
import logging
import time
import tqdm
import datetime
import torch
import numpy as np
from os.path import join
from torch.distributed import get_rank, get_world_size
from lsp_model import Adam
from gpt2_training.train_utils import boolean_string, set_lr
from gpt2_training.eval_utils import eval_model_loss
from data_loader import BucketingDataLoader, DistributedBucketingDataLoader
from gpt2_training.distributed import (all_reduce_and_rescale_tensors,
all_gather_list)
from kogpt2.pytorch_kogpt2 import get_pytorch_kogpt2_model
from kogpt2.pytorch_kogpt2 import kogpt2_config as config
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.utils import get_tokenizer
# from pytorch_memlab import MemReporter
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
INF = 100000000
CACHE_EMPTY_STEP = 10000
EVAL_STEP = 100000
#########################################################################
# Prepare Parser
##########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path',
type=str,
help='pretrained model name or path to local checkpoint')
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--max_seq_length", type=int, default=128)
parser.add_argument("--skip_eval",
action='store_true',
help='If true, skip evaluation.')
parser.add_argument("--init_checkpoint", type=str)
parser.add_argument("--train_input_file", type=str)
parser.add_argument("--eval_input_file", type=str)
parser.add_argument("--continue_from", type=int, default=0)
parser.add_argument("--train_batch_size",
type=int,
default=4,
help="batch size now means per GPU per step")
parser.add_argument("--gradient_accumulation_steps",
type=int,
default=2,
help="to increase effective batch size "
"and reduce synchronization")
parser.add_argument("--eval_batch_size", type=int, default=4)
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--num_optim_steps",
type=int,
default=1000000,
help="new API specifies num update steps")
parser.add_argument("--valid_step",
type=int,
default=10000,
help="how many optim steps between validations")
parser.add_argument("--warmup_proportion", type=float, default=0.1)
parser.add_argument("--warmup_steps", type=int, default=16000)
parser.add_argument("--normalize_data", type=boolean_string, default=True)
parser.add_argument("--fp16", type=boolean_string, default=True)
parser.add_argument("--lr_schedule",
type=str,
choices=['noam', 'noamwd', 'BERT', 'None'],
default='noam')
parser.add_argument("--loss_scale", type=float, default=0)
parser.add_argument("--no_token_id", type=boolean_string, default=True)
parser.add_argument("--output_dir", type=str)
parser.add_argument("--log_dir", type=str)
parser.add_argument('--pbar',
type=boolean_string,
default=True,
help='turn on progress bar')
# distributed
parser.add_argument('--local_rank',
type=int,
default=-1,
help='for torch.distributed')
parser.add_argument('--config', help='JSON config file')
# do normal parsing
args = parser.parse_args()
if args.config is not None:
# override argparse defaults by config JSON
opts = json.load(open(args.config))
for k, v in opts.items():
if isinstance(v, str):
# PHILLY ENV special cases
if 'PHILLY_JOB_DIRECTORY' in v:
v = v.replace('PHILLY_JOB_DIRECTORY',
os.environ['PHILLY_JOB_DIRECTORY'])
elif 'PHILLY_LOG_DIRECTORY' in v:
v = v.replace('PHILLY_LOG_DIRECTORY',
os.environ['PHILLY_LOG_DIRECTORY'])
setattr(args, k, v)
# command line should override config JSON
argv = sys.argv[1:]
overrides, _ = parser.parse_known_args(argv)
for k, v in vars(overrides).items():
if f'--{k}' in argv:
setattr(args, k, v)
setattr(args, 'local_rank', overrides.local_rank)
assert args.train_batch_size % args.gradient_accumulation_steps == 0, \
'batch size % gradient accumulation steps != 0!'
args.train_batch_size = (args.train_batch_size //
args.gradient_accumulation_steps)
logger.info('train batch size = {}, '
'new train batch size (after gradient accumulation) = {}'.format(
args.train_batch_size * args.gradient_accumulation_steps,
args.train_batch_size))
if args.local_rank == -1:
logger.info('CUDA available? {}'.format(str(torch.cuda.is_available())))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
args.device, args.n_gpu = device, n_gpu
else:
# distributed training
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
# Initializes the distributed backend which will take care of
# sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
n_gpu = torch.distributed.get_world_size()
args.device, args.n_gpu = device, 1
logger.info("device: {} n_gpu: {}, distributed training: {}, "
"16-bits training: {}".format(device, n_gpu,
bool(args.local_rank != -1),
args.fp16))
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d%H%M%S')
output_dir = join(
args.output_dir,
'GPT2.{}.{}.{}gpu.{}'.format(args.learning_rate, args.train_batch_size,
n_gpu, timestamp))
log_dir = args.log_dir if args.log_dir is not None and len(
args.log_dir) > 0 else output_dir
if args.local_rank == -1 or get_rank() == 0:
os.makedirs(output_dir, exist_ok=True)
logger.info('Input Argument Information')
args_dict = vars(args)
for a in args_dict:
logger.info('%-28s %s' % (a, args_dict[a]))
#########################################################################
# Prepare Data Set
##########################################################################
# enc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
tok_path = get_tokenizer()
enc = SentencepieceTokenizer(tok_path)
if args.init_checkpoint is None:
model, vocab = get_pytorch_kogpt2_model(0)
else:
VOCAB_PATH = '/home/calee/kogpt2/kogpt2_news_wiki_ko_cased_818bfa919d.spiece'
model_path = args.init_checkpoint
from kogpt2.pytorch_kogpt2 import get_kogpt2_model
model, vocab = get_kogpt2_model(model_path, VOCAB_PATH, 0)
if args.fp16:
logger.info('in fp16, model.half() activated')
model.half()
if args.n_gpu > 1:
logging.info('data parallel because more than one gpu')
model = torch.nn.DataParallel(model)
# config = GPT2Config.from_json_file(
# join(args.model_name_or_path, 'config.json'))
if args.local_rank == -1:
train_dataloader = BucketingDataLoader(args.train_input_file,
args.train_batch_size,
args.max_seq_length)
else:
train_dataloader = DistributedBucketingDataLoader(get_rank(),
get_world_size(),
args.train_input_file,
args.train_batch_size,
args.max_seq_length)
eval_dataloader_loss = BucketingDataLoader(args.eval_input_file,
args.eval_batch_size,
args.max_seq_length)
# eval_dataloader_gen = get_eval_list_same_length(
# args.eval_input_file, enc, args.eval_batch_size, True)
#########################################################################
# Prepare Model and Optimizer
##########################################################################
# model = load_model(GPT2LMHeadModel(config), args.init_checkpoint,
# args, verbose=True)
if args.local_rank != -1:
# when from scratch make sure initial models are the same
params = [p.data for p in model.parameters()]
all_reduce_and_rescale_tensors(params,
float(torch.distributed.get_world_size()))
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
total_params = sum([np.prod(p.size()) for p in model_parameters])
logger.info('Number of parameter = {}'.format(total_params))
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'ln'] # no decay for bias and LayerNorm (ln)
optimizer_grouped_parameters = [{
'params':
[p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay':
0.01
}, {
'params':
[p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
'weight_decay':
0.0
}]
if args.fp16:
logger.info('in fp16, using FusedAdam')
try:
from apex.optimizers import FP16_Optimizer
from apex.optimizers import FusedAdam
except ImportError:
raise ImportError(
"Please install apex from https://www.github.com/nvidia/apex "
"to use distributed and fp16 training.")
optimizer = FusedAdam(optimizer_grouped_parameters,
lr=args.learning_rate,
bias_correction=False,
max_grad_norm=1.0)
if args.loss_scale == 0:
optimizer = FP16_Optimizer(optimizer,
dynamic_loss_scale=True,
verbose=False)
else:
optimizer = FP16_Optimizer(optimizer,
static_loss_scale=args.loss_scale,
verbose=False)
else:
optimizer = Adam(optimizer_grouped_parameters,
args.learning_rate,
max_grad_norm=1.0)
#########################################################################
# Training !
##########################################################################
if args.local_rank == -1 or get_rank() == 0:
train_logger = open(join(log_dir, 'train_log.txt'), 'a+', buffering=1)
eval_logger = open(join(log_dir, 'eval_log.txt'), 'a+', buffering=1)
print(
'epoch,global_step,step,mean_loss,mean_ppl,n_token_real,'
'n_token_total,epoch_time',
file=train_logger)
print('epoch,global_step,step,eval_loss,eval_ppl', file=eval_logger)
global_step = 0
step = 0
epoch = 0
if args.continue_from:
global_step = args.continue_from
step = global_step * 2 - 1
if args.local_rank != -1:
n_gpu = 1
if args.local_rank == -1 or get_rank() == 0:
if args.pbar:
pbar = tqdm.tqdm(initial=global_step,
total=args.num_optim_steps,
desc='training')
else:
pbar = None
# logger.info("pdb-attach")
# from pdb_clone import pdb
# rsock = pdb.set_trace_remote()
#
# if rsock.state != rsock.ST_CONNECTED:
# input()
while True:
model.train()
(tr_loss, tr_ppl, mean_ppl, nb_tr_examples,
nb_tr_steps) = 0.0, 0.0, 0.0, 0, 0
n_token_real, n_token_total = 0, 0
train_start_time_epoch = time.time()
for batch in train_dataloader:
# activate new training mode
seq_len = batch[0].shape[1]
batch = tuple(t.to(device) for t in batch)
input_ids, position_ids, token_ids, label_ids, *_ = batch
if args.no_token_id:
token_ids = None
loss, ppl, _ = model(input_ids,
position_ids=position_ids,
token_type_ids=token_ids,
labels=label_ids)
# loss, ppl = model(input_ids, labels=label_ids)
# reporter = MemReporter(model)
if n_gpu > 1:
loss = loss.mean()
ppl = ppl.mean()
loss = loss / (args.train_batch_size / input_ids.shape[0])
if args.fp16:
optimizer.backward(loss)
else:
loss.backward()
tr_loss += float(loss.item()) * \
(args.train_batch_size / input_ids.shape[0])
nb_tr_examples += input_ids.size(0)
nb_tr_steps += 1
mean_loss = tr_loss / nb_tr_steps
if ppl.item() < INF:
tr_ppl += ppl.item()
else:
tr_ppl += mean_ppl
mean_ppl = tr_ppl / nb_tr_steps
n_token_total += input_ids.shape[0] * input_ids.shape[1]
n_token_real += (input_ids != 0).sum().item()
# gradient update
step += 1
if step % args.gradient_accumulation_steps == 0:
set_lr(optimizer, global_step, args.lr_schedule, args.learning_rate,
args.warmup_steps, args.warmup_proportion, config['n_embd'],
args.num_optim_steps)
if args.local_rank != -1:
grads = [
p.grad.data for p in model.parameters()
if p.requires_grad and p.grad is not None
]
all_reduce_and_rescale_tensors(grads, float(1))
optimizer.step()
optimizer.zero_grad()
global_step += 1
# Print log info to file
if args.local_rank != -1:
mean_loss = sum(all_gather_list(mean_loss)) / get_world_size()
mean_ppl = sum(all_gather_list(mean_ppl)) / get_world_size()
n_token_real_all_proc = sum(all_gather_list(n_token_real))
n_token_total_all_proc = sum(all_gather_list(n_token_total))
else:
n_token_real_all_proc = n_token_real
n_token_total_all_proc = n_token_total
if args.local_rank == -1 or get_rank() == 0:
epoch_time = time.time() - train_start_time_epoch
if pbar is not None:
pbar.set_postfix_str(
f"tok/s: {n_token_real_all_proc//epoch_time//1000}k "
f"ppl: {mean_ppl:.2f} epoch: {epoch}")
pbar.update(1)
print('{},{},{},{},{},{},{},{}'.format(epoch + 1, global_step + 1,
step + 1, mean_loss, mean_ppl,
n_token_real_all_proc,
n_token_total_all_proc,
epoch_time),
file=train_logger)
if global_step % args.valid_step == 0:
if args.local_rank == -1 or get_rank() == 0:
# only rank 0 process evaluate
torch.save(
{
k:
(v.cpu() if v is not None else None) # save to cpu tensors
for k, v in model.state_dict().items()
},
join(output_dir, f'GP2-pretrain-step-{global_step}.pkl'))
eval_loss, eval_ppl = eval_model_loss(model, enc,
eval_dataloader_loss, args)
# enable generation step evaluation for now
# gen_response = eval_model_generation(
# model, enc, eval_dataloader_gen, epoch, args)
'''
# probably use beam search only for test set
if False:
gen_response_beam = eval_model_generation(
model, enc, eval_dataloader_gen, epoch, args,
use_beam_search=True, beam_width=3)
'''
print('{},{},{},{},{}'.format(epoch + 1, global_step + 1, step + 1,
eval_loss, eval_ppl),
file=eval_logger)
logger.info('current learning rate: ' +
str(optimizer.param_groups[0]['lr']))
model.train()
if global_step >= args.num_optim_steps:
break
if (step + 1) % CACHE_EMPTY_STEP == 0:
torch.cuda.empty_cache()
if global_step >= args.num_optim_steps:
break
epoch += 1
if args.local_rank == -1 or get_rank() == 0:
if pbar is not None:
pbar.close()
train_logger.close()
eval_logger.close()
<file_sep>/README.md
## Note
(2020/04/23) 감정 입력은 아직 반영 안 된 기본 대화 시스템입니다.
(2020/12/30) 디시인사이드 데이터 등 사전 학습 데이터로 사전 학습 후 추가 학습 진행할 수 있도록 업데이트하였습니다.
## System/SW Overview
* 개발 목표
감정과 대화를 입력으로 받아서 대화 히스토리에 대해 적절한 답변을 할 수 있는 시스템 개발
* 최종 결과물
감정과 대화를 입력으로 받아서 답변을 생성합니다.
* 시스템/SW 대표 그림

## How to Install
1. Clone DialoGPT
```bash
git clone http://EmoCA.kaist.ac.kr/calee/DialoGPT.git
```
2. Install Docker
3. Prepare vocab, and normal and reverse models
* Contact <EMAIL> to get files
4. Set paths from config.py file
* The paths should be relative to DialoGPT directory
5. Change directory to DialoGPT/docker
6. Run run.sh
```bash
bash run.sh
```
## Main requirement
* Docker
## Network Architecture and features

* **Model:**
* The model is able to do language modeling.
* **Masked Self-Attention:**
* Masks future tokens.
* Refer http://jalammar.github.io/illustrated-gpt2/ for more details about the model.
* **Metrics:**
* Perplexity
## Quick start
* See How to Install to install
* Use any http client to get a response
ex)
```bash
wget "localhost:5000/?utext=%EB%82%98%EB%8A%94%20%EC%95%BC%EA%B5%AC%EB%A5%BC%20%EC%A2%8B%EC%95%84%ED%95%B4.&emotion=10001&uid=1"
```
* Response
```
{"text": "야구를 정말 좋아하는 사람은 나야.", "emotion": 10005}
```
## Training Data
* Opensubtitles v2018 ko
- 총 3,324개의 대화 (영화)
- 총 1,048,575개의 턴
- 64MB
- 감정: 감정 분류기로 태깅
* 아크릴 텍스트 대화 데이터
- 총 26,200개의 대화
- 총 152, 896개의 턴
- 12MB
- 감정: 대화 작성자가 태깅
## Training Model (Fine-tuning the provided trained model)
### How to Install
1. Install Anaconda
```bash
cd ~
mkdir Downloads
cd ~/Downloads
wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
bash Anaconda3-2020.02-Linux-x86_64.sh
```
Follow instructions.
Answer 'yes' to prepend the Anaconda3 install location to PATH in your .bashrc.
Answer 'no' not to install Microsoft VSCode.
2. Install NVIDIA CUDA Toolkit
3. Clone DialoGPT
```bash
git clone http://EmoCA.kaist.ac.kr/calee/DialoGPT.git
```
4. Create and activate conda environment
```bash
cd DialoGPT
conda env create -f LSP-linux.yml -n LSP
conda activate LSP
```
5. Clone and install KoGPT2
```bash
git clone http://EmoCA.kaist.ac.kr/calee/KoGPT2.git
cd KoGPT2
pip install -r requirements.txt
pip install .
```
6. Copy files
data/train.200len.db
data/valid.200len.db
7. Train
```bash
bash run.sh
```
### Main requirement
You may be able to use the library without this requirements, but the library is tested only from the below environment.
- One or more Titan V or GeForce GTX 1080 Ti graphics cards (driver should be installed)
- Ubuntu 18.04.4 LTS or CentOS 7
### Speed Up
To speed up, install apex, and change the option fp16 to true and gradient_accumulation_steps to 8 on run.sh.
## Test
```bash
python interact.py {vocab_path} {model_path} {reverse_model_path}
```
## HTTP-server API description
* Path: /
* Port: 5000
* Method: get
|Parameter|Type|Description|
|---|---|---|
|utext|string|Input text|
|emotion|integer|Input emotion (Happiness: 10001, Anger: 10002, Disgust: 10003, Fear: 10004, Neutral: 10005, Sadness: 10006, Surprise: 10007)|
|uid|string|ID of the dialogue context (any unique string for each dialogue)|
* Response
```
{"text": "야구를 정말 좋아하는 사람은 나야.", "emotion": 10005}
```
## Repository overview
* configs/ - Configurations for each models
* data/ - Data preparation
* data/dummy_data.tsv - Dummy data
* data/filter_bland.py - Filters bland data
* data/prepare4db.sh - Change tsv files to db format
* data/to_tsv.py - Change xlsx files to tsv format
* data/train_raw.tsv - An example tsv file.
* docker/ - Docker related files
* gpt2_training/eval_utils.py - Validation code
* gpt2_training/train_utils.py - Training code
* img/ - Image directory for README.md
* lsp_model/modeling_gpt2.py - Model code
* lsp_model/optim.py - Optimizer code
* reddit_extractor/ - Reddit data preparation
* bot.py - Code for easier test.
* LSP_train.py - Main training code
* LSP_valid.py - Main validation code
* config.py - Configuration file
* data_loader.py - Loader from db
* demo.py - Demo script
* discord_bot.py - Discord bot
* interact.py - Test script
* prepro.py - Change a tsv file to db format
* run.sh - Training script
* run_eval.sh - Evaluation script
* run_sample.sh - Test script to test for a few sentences
* sample.py - Test code to test for a few sentences
<file_sep>/data/parquet_to_tsv.py
from tqdm import tqdm
import pandas as pd
import argparse
import json
import os
from dcinside import filter as dcinside_filter
from dcinside.filter import filter_rows
from dcinside.clean import clean
def create_rows(input_path):
train = []
valid = []
test = []
df = pd.read_parquet(input_path)
for index, row in tqdm(df.iterrows(),
total=len(df.index),
desc='create_rows'):
try:
doc = json.loads(row.contents)
cleaned = clean(doc)
handle = train
if index % 10 == 0:
handle = test
elif index % 10 == 1:
handle = valid
handle += dcinside_filter.create_rows(cleaned)
except TypeError:
pass
return train, valid, test
def main():
parser = argparse.ArgumentParser(description='Parquet files to tsv.')
parser.add_argument('input', metavar='input', type=str, help='Input path')
parser.add_argument('output', metavar='output', type=str, help='Output path')
args = parser.parse_args()
rows = create_rows(args.input)
filtered = [filter_rows(r) for r in rows]
df = [pd.DataFrame(f) for f in filtered]
names = ['train_bland.tsv', 'valid_bland.tsv', 'test_bland.tsv']
for i, d in enumerate(df):
d.to_csv(os.path.join(args.output, names[i]),
sep='\t',
header=False,
index=False)
if __name__ == '__main__':
main()
<file_sep>/config.py
# device for forward and backward model
device_f = 'cuda'
device_r = 'cpu'
# sampling parameters
top_k = 50
num_samples = 40
ALPHA = 0.5 # 1에 가까우면 기본 모델에 집중하고 0에 가까우면 reverse 모델에 집중합니다.
top_p = 0.9
# default paths
vocab_path = 'models/kogpt2_news_wiki_ko_cased_818bfa919d.spiece'
model_path = 'models/output_model/' \
'GPT2.1e-05.64.2gpu.2020-03-24160510/GP2-pretrain-step-20672.pkl'
reverse_model_path = 'models/output_model/' \
'GPT2.1e-05.64.2gpu.2020-03-26162233/GP2-pretrain-step-8704.pkl'
<file_sep>/data/K/to_tsv.py
from openpyxl import load_workbook
from tqdm import tqdm
import pandas as pd
import argparse
import os
import sys
sys.path.append('/home/calee/git/dcinside')
from filter import Comment
from filter import filter_rows
from filter import add_tags
from clean import clean_str
def create_rows(xlsxes):
train = []
valid = []
test = []
r = []
conv_id = 0
movie_id = 0
previous_movie = -1
previous_situation = -1
for xlsx in tqdm(xlsxes):
wb = load_workbook(xlsx)
ws = wb.active
for i, row in enumerate(tqdm(ws.rows, total=ws.max_row)):
if i == 0:
continue
movie = row[0].value
situation = row[3].value
sents = (row[1].value, row[2].value)
if movie != previous_movie:
movie_id += 1
if movie != previous_movie or situation != previous_situation:
if r:
handle = train
if movie_id % 10 == 0:
handle = test
elif movie_id % 10 == 1:
handle = valid
handle.append(r)
r = []
for sent_idx, sent in enumerate(sents):
if sent is not None:
try:
if type(sent) == int or row[sent_idx + 1].number_format == '@':
sent = str(sent)
c = Comment(clean_str(sent))
except:
import pdb
pdb.set_trace()
add_tags(c)
r.append(c)
previous_movie = movie
previous_situation = situation
handle = train
if movie_id % 10 == 0:
handle = test
elif movie_id % 10 == 1:
handle = valid
handle.append(r)
r = []
return train, valid, test
def main():
xlsxes = []
for root, _, files in os.walk('.'):
for name in files:
if 'line' in name and name.endswith('.xlsx'):
xlsxes.append(os.path.join(root, name))
rows = create_rows(xlsxes)
filtered = [filter_rows(r) for r in rows]
df = [pd.DataFrame(f) for f in filtered]
names = ['train_bland.tsv', 'valid_bland.tsv', 'test_bland.tsv']
for i, d in enumerate(df):
d.to_csv(names[i], sep='\t', header=False, index=False)
if __name__ == '__main__':
main()
| 4b6cf164c297c8b9cc1b7a031c41d32f73de4249 | [
"YAML",
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 17 | Python | AIBrainOrganization/DialoGPT | f6bdefed5e1ecfc7acd6759f1ba208d6e8f7f8b8 | d05d6351d5a06e3da0dc0bd68badc6bddacf5fee |
refs/heads/master | <file_sep>import axios from 'axios'
export default {
all () {
return axios.get('https://www.reddit.com/r/memexico.json')
}
}
| c40f256be5b3095414802cd8a4e7e3a181c55294 | [
"JavaScript"
] | 1 | JavaScript | daniel-tinoco/ionic-app-vue | e9a31fd46bb9756cd2093c205d53526b22aeb3c8 | eac3c081e959556525abf91ff35835aae4ff08bb |
refs/heads/master | <file_sep># Reversi-Coffee
Created for a school project exploring a language of our choice. Although it has a few small bugs, overall, it is clean and works well.
<file_sep>// Generated by CoffeeScript 1.9.1
(function() {
window.Rand = (function() {
function Rand(seed1) {
this.seed = seed1;
this.multiplier = 1664525;
this.modulo = 4294967296;
this.offset = 1013904223;
if (!((this.seed != null) && (0 <= seed && seed < this.modulo))) {
this.seed = (new Date().valueOf() * new Date().getMilliseconds()) % this.modulo;
}
}
Rand.prototype.seed = function(seed) {
return this.seed = seed;
};
Rand.prototype.randn = function() {
return this.seed = (this.multiplier * this.seed + this.offset) % this.modulo;
};
Rand.prototype.randf = function() {
return this.randn() / this.modulo;
};
Rand.prototype.rand2 = function(n) {
return Math.floor(this.randf() * n);
};
Rand.prototype.rand = function(min, max) {
return min + this.rand2(max - min);
};
return Rand;
})();
}).call(this);
<file_sep>// Generated by CoffeeScript 1.9.1
(function() {
window.Board = (function() {
Board.prototype.board = null;
Board.prototype.num_columns = 8;
Board.prototype.num_tiles = 0;
Board.prototype.over = false;
Board.prototype.context = null;
Board.prototype.canvas = null;
Board.prototype.winner = "";
Board.prototype.player = "black";
Board.prototype.line_width = 3;
Board.prototype.black_turn = true;
function Board(c, ctx) {
this.context = ctx;
this.canvas = c;
this.generate_new();
this.draw_board();
return this;
}
Board.prototype.generate_new = function() {
this.clear_board();
this.add_disc(this.real_index(3, 3), "white");
this.add_disc(this.real_index(4, 3), "black");
this.add_disc(this.real_index(3, 4), "black");
return this.add_disc(this.real_index(4, 4), "white");
};
Board.prototype.real_index = function(gridX, gridY) {
return (this.num_columns * gridY) + gridX;
};
Board.prototype.clear_board = function() {
var i, l, results;
this.board = [];
results = [];
for (i = l = 1; l <= 64; i = ++l) {
results.push(this.board.push(null));
}
return results;
};
Board.prototype.add_disc = function(position, color) {
var disc, xy;
disc = new Disc(color);
xy = this.index_to_real(position);
disc.set_xPos(xy[0]);
disc.set_yPos(xy[1]);
disc.set_color(color);
return this.insert_disc(disc, position);
};
Board.prototype.insert_disc = function(disc, position) {
return this.board[position] = disc;
};
Board.prototype.index_to_real = function(pos) {
var x, y;
x = pos % this.num_columns;
y = Math.floor(pos / this.num_columns);
return [x, y];
};
Board.prototype.valid_move = function(position) {
if (this.board[position] !== null) {
return false;
} else {
return this.check_valid(position, 0, -1) || this.check_valid(position, 0, 1) || this.check_valid(position, -1, -1) || this.check_valid(position, -1, 0) || this.check_valid(position, -1, 1) || this.check_valid(position, 1, -1) || this.check_valid(position, 1, 0) || this.check_valid(position, 1, 1);
}
};
Board.prototype.check_valid = function(position, x, y) {
var result;
result = this.get_distance(position, x, y) !== 0;
return result;
};
Board.prototype.get_distance = function(position, x, y) {
var color1, color2, k, m, xy;
if (this.black_turn) {
color1 = 'rgb(0, 0, 0)';
color2 = 'rgb(255, 255, 255)';
} else {
color1 = 'rgb(255, 255, 255)';
color2 = 'rgb(0, 0, 0)';
}
xy = this.index_to_real(position);
k = m = 0;
while (true) {
while (true) {
xy[0] += x;
xy[1] += y;
k++;
if ((xy[0] < 0) || (xy[0] >= this.num_columns) || (xy[1] < 0) || (xy[1] >= this.num_columns)) {
return 0;
}
if (this.board[this.real_index(xy[0], xy[1])] === null) {
return 0;
}
if (this.board[this.real_index(xy[0], xy[1])].color !== color2) {
break;
}
m = 1;
}
if (this.board[this.real_index(xy[0], xy[1])].color === color1) {
break;
}
}
if (m !== 0) {
return k;
}
return 0;
};
Board.prototype.flip_discs = function(position, x, y) {
var i, j, k, l, ref, results, xy;
xy = this.index_to_real(position);
results = [];
for (i = l = ref = this.get_distance(position, x, y) - 1; l >= 1; i = l += -1) {
j = xy[0] + i * x;
k = xy[1] + i * y;
results.push(this.flip_disc(this.real_index(j, k)));
}
return results;
};
Board.prototype.flip_disc = function(position) {
if (this.board[position].color === 'rgb(255, 255, 255)') {
return this.board[position].set_color("black");
} else if (this.board[position].color === 'rgb(0, 0, 0)') {
return this.board[position].set_color("white");
}
};
Board.prototype.make_move = function(e) {
var rect, x, xy, y;
rect = this.canvas.getBoundingClientRect();
x = e.clientX - rect.left;
y = e.clientY - rect.top;
xy = this.posToPair(x, y);
if (this.valid_move(this.real_index(xy[0], xy[1]))) {
this.move(this.real_index(xy[0], xy[1]));
}
this.check_game_over();
this.draw_board();
return this.new_turn();
};
Board.prototype.posToPair = function(x, y) {
var column, row;
column = Math.floor(x / (this.canvas.width / this.num_columns));
row = Math.floor(y / (this.canvas.height / this.num_columns));
return [column, row];
};
Board.prototype.move = function(position) {
if (this.black_turn) {
this.add_disc(position, "black");
} else {
this.add_disc(position, "white");
}
this.flip_discs(position, 0, -1);
this.flip_discs(position, 0, 1);
this.flip_discs(position, -1, -1);
this.flip_discs(position, -1, 0);
this.flip_discs(position, -1, 1);
this.flip_discs(position, 1, -1);
this.flip_discs(position, 1, 0);
this.flip_discs(position, 1, 1);
return this.black_turn = !this.black_turn;
};
Board.prototype.new_turn = function() {
if (this.black_turn) {
this.player = "black";
} else {
this.player = "white";
}
return document.getElementById('anchor').innerHTML = this.player;
};
Board.prototype.check_game_over = function() {
if (!this.move_exists) {
this.black_turn = !this.black_turn;
if (!this.move_exists) {
return this.game_over = true;
}
}
};
Board.prototype.move_exists = function() {
var i, l;
for (i = l = 1; l <= 64; i = ++l) {
if (this.valid_move(position)) {
return true;
}
}
};
Board.prototype.draw_board = function() {
var disc, l, len, n, o, ref, ref1, ref2, results, x, y;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.setStrokeStyle = 'rgb(255, 255, 255)';
for (x = l = 1, ref = this.num_columns - 1; 1 <= ref ? l <= ref : l >= ref; x = 1 <= ref ? ++l : --l) {
this.context.beginPath();
this.context.moveTo((this.canvas.width / this.num_columns) * x, 0);
this.context.lineTo((this.canvas.width / this.num_columns) * x, this.canvas.height);
this.context.lineWidth = this.line_width;
this.context.closePath();
this.context.stroke();
}
for (y = n = 1, ref1 = this.num_columns - 1; 1 <= ref1 ? n <= ref1 : n >= ref1; y = 1 <= ref1 ? ++n : --n) {
this.context.beginPath();
this.context.moveTo(0, (this.canvas.height / this.num_columns) * y);
this.context.lineTo(this.canvas.width, (this.canvas.height / this.num_columns) * y);
this.context.lineWidth = this.line_width;
this.context.closePath();
this.context.stroke();
}
ref2 = this.board;
results = [];
for (o = 0, len = ref2.length; o < len; o++) {
disc = ref2[o];
if (disc !== null) {
results.push(disc.draw(this.context));
} else {
results.push(void 0);
}
}
return results;
};
return Board;
})();
}).call(this);
<file_sep>// Generated by CoffeeScript 1.9.1
(function() {
window.Disc = (function() {
Disc.SIZE = 0;
Disc.prototype.color = 'rgb(0, 0, 0)';
Disc.prototype.xPos = 0;
Disc.prototype.yPos = 0;
function Disc(c) {
this.SIZE = 50;
this.set_color(c);
return this;
}
Disc.prototype.get_color = function() {
return this.color;
};
Disc.prototype.set_color = function(c) {
if (c === "black") {
return this.color = 'rgb(0, 0, 0)';
} else {
return this.color = 'rgb(255, 255, 255)';
}
};
Disc.prototype.get_xPos = function() {
return this.xPos;
};
Disc.prototype.set_xPos = function(x) {
return this.xPos = x;
};
Disc.prototype.get_yPos = function() {
return this.yPos;
};
Disc.prototype.set_yPos = function(y) {
return this.yPos = y;
};
Disc.prototype.draw = function(context) {
context.beginPath();
context.arc((this.xPos * this.SIZE) + (this.SIZE / 2), (this.yPos * this.SIZE) + (this.SIZE / 2), this.SIZE / 2, 0, 2 * Math.PI, false);
context.fillStyle = this.color;
context.fill();
context.lineWidth = 3;
context.strokeStyle = '#000000';
context.stroke();
return true;
};
return Disc;
})();
}).call(this);
<file_sep>// Generated by CoffeeScript 1.9.1
(function() {
window.Game = (function() {
Game.prototype.canvas = null;
Game.prototype.context = null;
Game.prototype.board = null;
function Game() {
this.generateCanvas();
this.board = new Board(this.canvas, this.context);
this.canvas.addEventListener("click", this.click.bind(this), false);
return this;
}
Game.prototype.generateCanvas = function() {
document.getElementById('game').innerHTML = '';
this.canvas = document.createElement('canvas');
document.getElementById('game').appendChild(this.canvas);
this.canvas.height = '400';
this.canvas.width = '400';
return this.context = this.canvas.getContext('2d');
};
Game.prototype.click = function(e) {
return this.board.make_move(e);
};
return Game;
})();
}).call(this);
| 2e435a4aa367503f0e21d7a9ed6ca0431c061f36 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | iplay88keys/Reversi-Coffee | edae898a97f1757499bed5aa574af958272e004f | d35fd6faa51ef4025642ff583a3f927d47c25468 |
refs/heads/master | <repo_name>speps/speps.github.io<file_sep>/articles/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>speps.fr</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="/css/main.css"/>
<link rel="stylesheet" type="text/css" href="/css/syntax.css"/>
<link rel='shortcut icon' href='/favicon.ico'/>
<link rel='icon' href='/favicon.gif' type='image/gif'/>
<link href="/index.xml" rel="alternate" type="application/rss+xml" title="speps.fr"/>
<link href="/index.xml" rel="feed" type="application/rss+xml" title="speps.fr"/>
</head>
<body>
<div id="bg-container">
<div id="bg">
<div id="bg-right"></div>
</div>
</div>
<div id="main-container">
<div id="main">
<div id="header">
<h1><a href="/" title="Return to the first page">speps.fr</a></h1>
<ul>
<li><a href="/aboutme" title="Some information about myself"><span class="left"></span><span class="mid">About Me</span><span class="right"></span></a></li>
<li><a href="/projects" title="My work, my projects, my hobbies"><span class="left"></span><span class="mid">Projects</span><span class="right"></span></a></li>
<li><a href="/articles" title="Some articles I wrote"><span class="left"></span><span class="mid">Articles</span><span class="right"></span></a></li>
<li><a href="/resume" title="My resume for your recruiting needs"><span class="left"></span><span class="mid">Resume</span><span class="right"></span></a></li>
<li><a href="/links" title="What I spend my time with on the web"><span class="left"></span><span class="mid">Links</span><span class="right"></span></a></li>
</ul>
<div id="social"><a href="http://www.linkedin.com/in/remigillig"><img src="/images/linkedin.png"/></a></div>
<div id="social"> </div>
<div id="social"><a href="http://twitter.com/remigillig"><img src="/images/twitter.png"/></a></div>
</div>
<div id="content">
<div id="page">
<h1>Articles</h1>
<ul>
<li>
<a href="/articles/trespasser-part1/">Trespasser - C++ archeology and oxidization - Part 1 Loading Scene Data</a><div class="date">2021-01-21 13:31:42 +0000</div>
</li>
<li>
<a href="/articles/torus-trooper-part4/">Torus Trooper - Rebooting a 15 year-old game written in D - Part 4 Final steps</a><div class="date">2020-11-26 22:07:27 +0000</div>
</li>
<li>
<a href="/articles/torus-trooper-part3/">Torus Trooper - Rebooting a 15 year-old game written in D - Part 3 WebAssembly</a><div class="date">2020-07-26 21:36:11 +0000</div>
</li>
<li>
<a href="/articles/torus-trooper-part2/">Torus Trooper - Rebooting a 15 year-old game written in D - Part 2 Running</a><div class="date">2020-07-19 22:23:30 +0000</div>
</li>
<li>
<a href="/articles/torus-trooper-part1/">Torus Trooper - Rebooting a 15 year-old game written in D - Part 1 Compiling</a><div class="date">2020-07-12 19:46:57 +0000</div>
</li>
<li>
<a href="/articles/hugo-setup/">Setup Hugo with Travis CI and GitHub Pages</a><div class="date">2016-01-24 11:26:57 +0000</div>
</li>
<li>
<a href="/articles/directx-refcount/">Debugging a DirectX memory leak</a><div class="date">2013-08-10 21:31:30 +0000</div>
</li>
</ul>
</div>
</div>
<div id="footer"><p>2021-03-06 09:57:50 UTC - I speak for myself, I am not affiliated with any company - All rights reserved</p></div>
</div>
</div>
</body>
</html><file_sep>/media/articles/jpt_wavelet.js
const canvas = document.getElementById(canvas_id);
const ctx = canvas.getContext("2d");
const sizeX = 64;
const sizeZ = 256;
const width = 1024;
const marginLeft = Math.floor((canvas.width - width) >> 1);
const marginTop = 0;
const scale = Math.round(width / sizeX);
let values = [];
for (var i = 0; i < sizeX; i++) {
const x = i / sizeX;
values.push(25*x*(x-0.25)*(x-0.5)*(x-0.75)*(x-1));
}
let mouseDown = false;
let mousePrevPos = undefined;
canvas.onmousedown = function(event) {
if (event.button == 0) {
mouseDown = true;
}
};
canvas.onmouseup = canvas.onmouseleave = canvas.onmouseout = function(event) {
mouseDown = false;
};
canvas.onmousemove = function(event) {
if (!mouseDown) return;
const rect = canvas.getBoundingClientRect();
const x = Math.floor(event.clientX - rect.left - marginLeft);
const z = Math.floor(event.clientY - rect.top - marginTop);
const pos = Math.floor(x / scale);
const prevPos = mousePrevPos || pos;
if (pos > prevPos) {
for (var i = prevPos; i < pos; i++) {
if (i >= 0 && i < sizeX && z >= 0 && z < sizeZ) {
values[i] = z / sizeZ - 0.5;
}
}
} else if (prevPos > pos) {
for (var i = pos; i < prevPos; i++) {
if (i >= 0 && i < sizeX && z >= 0 && z < sizeZ) {
values[i] = z / sizeZ - 0.5;
}
}
}
update();
mousePrevPos = pos;
};
function fwt53(v) {
const n = v.length;
let x = Array.from(v);
let a = 0;
// predict 1
a = -0.5;
for (var i = 1; i < n - 2; i += 2) {
x[i] += a * (x[i - 1] + x[i + 1]);
}
x[n - 1] += 2 * a * x[n - 2];
// update 1
a = 0.25;
for (var i = 2; i < n; i += 2) {
x[i] += a * (x[i - 1] + x[i + 1]);
}
x[0] += 2 * a * x[1];
// scale
a = Math.sqrt(2);
for (var i = 0; i < n; i++) {
if (i % 2 == 0) x[i] *= a;
else x[i] /= a;
}
// pack
let temp = Array.from(x);
for (var i = 0; i < n; i++) {
if (i % 2 == 0) temp[Math.floor(i / 2)] = x[i];
else temp[Math.floor(n / 2 + i / 2)] = x[i];
}
for (var i = 0; i < n; i++) {
x[i] = temp[i];
}
return x;
}
function iwt53(v) {
const n = v.length;
let x = Array.from(v);
let a = 0;
let temp = Array.from(x);
for (var i = 0; i < Math.floor(n / 2); i++) {
temp[i * 2] = x[i];
temp[i * 2 + 1] = x[i + Math.floor(n / 2)];
}
for (var i = 0; i < n; i++) {
x[i] = temp[i];
}
// undo scale
a = 1 / Math.sqrt(2);
for (var i = 0; i < n; i++) {
if (i % 2 == 0) x[i] *= a;
else x[i] /= a;
}
// undo update 1
a = -0.25;
for (var i = 2; i < n; i += 2) {
x[i] += a * (x[i - 1] + x[i + 1]);
}
x[0] += 2 * a * x[1];
// undo predict 1
a = 0.5;
for (var i = 1; i < n - 2; i += 2) {
x[i] += a * (x[i - 1] + x[i + 1]);
}
x[n - 1] += 2 * a * x[n - 2];
return x;
}
function drawValues(left, top, v, color, text) {
ctx.strokeStyle = '#aaa';
ctx.strokeRect(left, top, width, sizeZ);
for (var i = 0; i < sizeX; i++) {
const x = left + (i + 0.5) * scale;
const z = top + (v[i] + 0.5) * sizeZ;
ctx.beginPath();
ctx.strokeStyle = '#aaa';
ctx.moveTo(x, z);
ctx.lineTo(x, top + sizeZ);
ctx.stroke();
ctx.beginPath();
ctx.fillStyle = color;
ctx.ellipse(x, z, 4, 4, 0, 0, 2 * Math.PI);
ctx.fill();
}
ctx.fillStyle = '#000';
ctx.font = "10pt monospace";
ctx.fillText(text, left + 10, top + 20);
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawValues(marginLeft, marginTop, values, '#999', "Original values (click to change values)");
let coeffs0 = fwt53(values);
drawValues(marginLeft, marginTop + sizeZ, coeffs0, '#090', "DWT53 applied once");
let coeffs1 = fwt53(coeffs0);
drawValues(marginLeft, marginTop + sizeZ * 2, coeffs1, '#009', "DWT53 applied twice");
let coeffs5 = fwt53(fwt53(fwt53(fwt53(coeffs1))));
drawValues(marginLeft, marginTop + sizeZ * 3, coeffs5, '#900', "DWT53 applied until one approximation coefficient left");
let recons = iwt53(iwt53(iwt53(iwt53(iwt53(iwt53(coeffs5))))));
drawValues(marginLeft, marginTop + sizeZ * 4, recons, '#990', "Reconstructed values");
}
update();
<file_sep>/articles/torus-trooper-part4/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title><NAME> - Rebooting a 15 year-old game written in D - Part 4 Final steps - speps.fr</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="/css/main.css"/>
<link rel="stylesheet" type="text/css" href="/css/syntax.css"/>
<link rel='shortcut icon' href='/favicon.ico'/>
<link rel='icon' href='/favicon.gif' type='image/gif'/>
<link href="/index.xml" rel="alternate" type="application/rss+xml" title="speps.fr"/>
<link href="/index.xml" rel="feed" type="application/rss+xml" title="speps.fr"/>
</head>
<body>
<div id="bg-container">
<div id="bg">
<div id="bg-right"></div>
</div>
</div>
<div id="main-container">
<div id="main">
<div id="header">
<h1><a href="/" title="Return to the first page">speps.fr</a></h1>
<ul>
<li><a href="/aboutme" title="Some information about myself"><span class="left"></span><span class="mid">About Me</span><span class="right"></span></a></li>
<li><a href="/projects" title="My work, my projects, my hobbies"><span class="left"></span><span class="mid">Projects</span><span class="right"></span></a></li>
<li><a href="/articles" title="Some articles I wrote"><span class="left"></span><span class="mid">Articles</span><span class="right"></span></a></li>
<li><a href="/resume" title="My resume for your recruiting needs"><span class="left"></span><span class="mid">Resume</span><span class="right"></span></a></li>
<li><a href="/links" title="What I spend my time with on the web"><span class="left"></span><span class="mid">Links</span><span class="right"></span></a></li>
</ul>
<div id="social"><a href="http://www.linkedin.com/in/remigillig"><img src="/images/linkedin.png"/></a></div>
<div id="social"> </div>
<div id="social"><a href="http://twitter.com/remigillig"><img src="/images/twitter.png"/></a></div>
</div>
<div id="content">
<div id="page">
<h1>Torus Trooper - Rebooting a 15 year-old game written in D - Part 4 Final steps</h1>
<div id="sideinfo">
<nav id="TableOfContents">
<ul>
<li><a href="#hooking-up-keyboard-input">Hooking up keyboard input</a></li>
<li><a href="#fmodf">fmodf</a></li>
<li><a href="#tackling-memory-allocation">Tackling memory allocation</a></li>
<li><a href="#resizing-the-game">Resizing the game</a></li>
<li><a href="#playing-audio">Playing audio</a></li>
<li><a href="#fix-gamedraw-loop">Fix game/draw loop</a></li>
<li><a href="#loading-screen">Loading screen</a></li>
<li><a href="#saving-local-scoresreplays">Saving local scores/replays</a></li>
<li><a href="#mobile-support">Mobile support</a>
<ul>
<li><a href="#fullscreen-mode">Fullscreen mode</a></li>
<li><a href="#on-screen-controls">On screen controls</a></li>
<li><a href="#progressive-web-app-pwa-support">Progressive Web App (PWA) support</a></li>
</ul>
</li>
<li><a href="#wrapping-up-the-series">Wrapping up the series</a></li>
</ul>
</nav>
</div>
<p>See also</p>
<ul>
<li><a href="/articles/torus-trooper-part1">Part 1 - Compiling a new executable</a></li>
<li><a href="/articles/torus-trooper-part2">Part 2 - Running the game for the first time</a></li>
<li><a href="/articles/torus-trooper-part3">Part 3 - Porting to WebAssembly</a></li>
<li><a href="/articles/torus-trooper-part4">Part 4 - Final steps</a></li>
</ul>
<h2 id="hooking-up-keyboard-input">Hooking up keyboard input</h2>
<p>Remember the interface described earlier:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-d" data-lang="d"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">InputBackend</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">update</span><span class="o">();</span>
<span class="kd">public</span> <span class="kt">int</span> <span class="nf">getDirState</span><span class="o">();</span>
<span class="kd">public</span> <span class="kt">int</span> <span class="nf">getButtonState</span><span class="o">();</span>
<span class="kd">public</span> <span class="kt">bool</span> <span class="nf">getExitState</span><span class="o">();</span>
<span class="kd">public</span> <span class="kt">bool</span> <span class="nf">getPauseState</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>Here is the implementation for WebAssembly:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-d" data-lang="d"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">InputBackendWASM</span> <span class="o">:</span> <span class="n">InputBackend</span> <span class="o">{</span>
<span class="kt">uint</span> <span class="n">state</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">override</span> <span class="kt">void</span> <span class="nf">update</span><span class="o">()</span> <span class="o">{</span>
<span class="kn">import</span> <span class="nn">wasm</span><span class="o">;</span>
<span class="n">state</span> <span class="o">=</span> <span class="n">wasm</span><span class="o">.</span><span class="na">inputState</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kd">override</span> <span class="kt">int</span> <span class="nf">getDirState</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">state</span> <span class="o">&</span> <span class="mh">0xF</span><span class="o">;</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">override</span> <span class="kt">int</span> <span class="nf">getButtonState</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">state</span> <span class="o">&</span> <span class="mh">0x30</span><span class="o">;</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">override</span> <span class="kt">bool</span> <span class="nf">getExitState</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="o">(</span><span class="n">state</span> <span class="o">&</span> <span class="mh">0x40</span><span class="o">)</span> <span class="o">!=</span> <span class="mi">0</span><span class="o">;</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">override</span> <span class="kt">bool</span> <span class="nf">getPauseState</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="o">(</span><span class="n">state</span> <span class="o">&</span> <span class="mh">0x80</span><span class="o">)</span> <span class="o">!=</span> <span class="mi">0</span><span class="o">;</span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>Very simple, the good thing is that the original code already used masks for gameplay inputs. I just had to add another bit for exit and another one for pause.</p>
<p>From the JS side, there are <code>keydown</code>/<code>keyup</code> events that map the masks to the final value:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="kd">function</span> <span class="nx">maskInput</span><span class="p">(</span><span class="nx">code</span><span class="p">,</span> <span class="nx">enable</span><span class="p">)</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">masks</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">ArrowUp</span><span class="o">:</span> <span class="mh">0x1</span><span class="p">,</span>
<span class="nx">ArrowDown</span><span class="o">:</span> <span class="mh">0x2</span><span class="p">,</span>
<span class="nx">ArrowLeft</span><span class="o">:</span> <span class="mh">0x4</span><span class="p">,</span>
<span class="nx">ArrowRight</span><span class="o">:</span> <span class="mh">0x8</span><span class="p">,</span>
<span class="nx">ControlLeft</span><span class="o">:</span> <span class="mh">0x10</span><span class="p">,</span>
<span class="nx">ShiftLeft</span><span class="o">:</span> <span class="mh">0x20</span><span class="p">,</span>
<span class="nx">Escape</span><span class="o">:</span> <span class="mh">0x40</span><span class="p">,</span>
<span class="nx">KeyP</span><span class="o">:</span> <span class="mh">0x80</span>
<span class="p">};</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">code</span> <span class="k">in</span> <span class="nx">masks</span><span class="p">)</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">mask</span> <span class="o">=</span> <span class="nx">masks</span><span class="p">[</span><span class="nx">code</span><span class="p">];</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">enable</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">inputState</span> <span class="o">|=</span> <span class="nx">mask</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="nx">inputState</span> <span class="o">&=</span> <span class="o">~</span><span class="nx">mask</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">"keydown"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">event</span><span class="p">.</span><span class="nx">defaultPrevented</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">maskInput</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">code</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">},</span> <span class="kc">true</span><span class="p">);</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">"keyup"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">event</span><span class="p">.</span><span class="nx">defaultPrevented</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">maskInput</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">code</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">},</span> <span class="kc">true</span><span class="p">);</span>
</code></pre></td></tr></table>
</div>
</div><p>This works well enough, it can be extended later with more keys that map to the same input or make it customisable.</p>
<h2 id="fmodf">fmodf</h2>
<p>While doing the custom runtime, and because it’s not using any C runtime stuff, it complained about an undefined <code>fmod</code> symbol at link time. It’s a math function to compute the floating-point remainder of the operation <code>x / y</code>.</p>
<p>Unfortunately this doesn’t have a JS <code>Math</code> equivalent like the other ones, but it works in JS with the <code>%</code> operator, so I just ended up using that:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="nx">wasm_fmodf</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">x</span> <span class="o">%</span> <span class="nx">y</span><span class="p">;</span> <span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="tackling-memory-allocation">Tackling memory allocation</h2>
<p>In the title screen, I found that approximately every 4800 frame there was an increase of the WASM memory buffer. It came from a <code>Vector3</code> allocation in <code>createTorusShape</code> used to draw multiple parts of the menu. I solved this one by using the <a href="https://dlang.org/spec/attribute.html#scope"><code>scope</code> keyword in D</a>, it means the allocation is limited to the scope:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-d" data-lang="d"><span class="kd">private</span> <span class="kt">void</span> <span class="nf">createTorusShape</span><span class="o">(</span><span class="kt">int</span> <span class="n">n</span><span class="o">)</span> <span class="o">{</span>
<span class="n">scope</span> <span class="n">Vector3</span> <span class="n">cp</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Vector3</span><span class="o">;</span>
<span class="n">cp</span><span class="o">.</span><span class="na">z</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
<span class="n">scope</span> <span class="n">Vector3</span> <span class="n">ringOfs</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Vector3</span><span class="o">;</span>
<span class="o">...</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>However, during gameplay there are class instances that will live beyond the scope of a method and will need cleaning up once ununsed (eg. bullets or enemies). Ideally, the GC would take care of that but D doesn’t really have a GC unless you use the <code>druntime</code> code. Best here is to reuse memory as much as possible and identify which parts still need allocations.</p>
<p>This is an area that probably needs more attention as it currently leaks memory but it’s still possible to play through the game multiple times before it’s an issue. Help would be appreciated on a solution, possibly making a very basic GC would be good but an easier way would just be to make a pool of most things that can be reused (some classes already did that but only for game stuff).</p>
<h2 id="resizing-the-game">Resizing the game</h2>
<p>I did the whole series so far using a fixed resolution of 800 x 600 but all the code to support resizing is available so let’s try to handle that correctly.</p>
<p>I exposed a D method to WASM that will be called whenever the game needs to be resized, that tells the game what size the GL viewport is.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="kd">function</span> <span class="nx">onResize</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">w</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">innerWidth</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">h</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">innerHeight</span><span class="p">;</span>
<span class="kr">const</span> <span class="nx">ratio</span> <span class="o">=</span> <span class="mf">4.0</span> <span class="o">/</span> <span class="mf">3.0</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">w</span> <span class="o"><</span> <span class="p">(</span><span class="nx">h</span> <span class="o">*</span> <span class="nx">ratio</span><span class="p">))</span> <span class="p">{</span>
<span class="nx">h</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">round</span><span class="p">(</span><span class="nx">w</span> <span class="o">/</span> <span class="nx">ratio</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="nx">w</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">round</span><span class="p">(</span><span class="nx">h</span> <span class="o">*</span> <span class="nx">ratio</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">left</span> <span class="o">=</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">innerWidth</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">-</span> <span class="nx">w</span> <span class="o">/</span> <span class="mi">2</span><span class="p">)</span> <span class="o">+</span> <span class="s2">"px"</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">top</span> <span class="o">=</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">innerHeight</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">-</span> <span class="nx">h</span> <span class="o">/</span> <span class="mi">2</span><span class="p">)</span> <span class="o">+</span> <span class="s2">"px"</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">width</span> <span class="o">=</span> <span class="nx">w</span> <span class="o">+</span> <span class="s2">"px"</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">height</span> <span class="o">=</span> <span class="nx">h</span> <span class="o">+</span> <span class="s2">"px"</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">width</span> <span class="o">=</span> <span class="nx">w</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">height</span> <span class="o">=</span> <span class="nx">h</span><span class="p">;</span>
<span class="nx">exports</span><span class="p">.</span><span class="nx">_resized</span><span class="p">(</span><span class="nx">w</span><span class="p">,</span> <span class="nx">h</span><span class="p">);</span>
<span class="p">}</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">"resize"</span><span class="p">,</span> <span class="nx">onResize</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span>
</code></pre></td></tr></table>
</div>
</div><p>That allows the game to retain its original 4:3 ratio. I found using a wider viewport results in camera issues that I’m not willing to fix at this point, it also stretches the text and doesn’t look as good.</p>
<h2 id="playing-audio">Playing audio</h2>
<p>Playing music and sound effects is an important part of the game’s character. However, supporting SDL_Mixer in WebAssembly wasn’t realistic. The best solution I found is to embed the sound files as <code>ubyte[]</code> and create bridge between JS and WASM that then uses the WebAudio API to play sounds.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-d" data-lang="d"><span class="kt">ubyte</span><span class="o">[]</span> <span class="nf">read</span><span class="o">(</span><span class="kt">string</span> <span class="n">path</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/boss_dest.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/boss_dest.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/charge.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/charge.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/charge_shot.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/charge_shot.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/extend.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/extend.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/hit.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/hit.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/middle_dest.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/middle_dest.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/myship_dest.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/myship_dest.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/shot.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/shot.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/small_dest.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/small_dest.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/chunks/timeup_beep.wav"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/chunks/timeup_beep.wav"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/musics/tt1.ogg"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/musics/tt1.ogg"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/musics/tt2.ogg"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/musics/tt2.ogg"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/musics/tt3.ogg"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/musics/tt3.ogg"</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">path</span> <span class="o">==</span> <span class="s">"sounds/musics/tt4.ogg"</span><span class="o">)</span> <span class="k">return</span> <span class="k">cast</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">[])</span> <span class="n">import</span><span class="o">(</span><span class="s">"sounds/musics/tt4.ogg"</span><span class="o">);</span>
<span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>Then add a few new WASM exposed methods:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-d" data-lang="d"><span class="n">extern</span> <span class="o">(</span><span class="n">C</span><span class="o">)</span> <span class="o">{</span>
<span class="kt">uint</span> <span class="nf">wasm_sound_load</span><span class="o">(</span><span class="kd">const</span><span class="o">(</span><span class="kt">char</span><span class="o">*)</span> <span class="n">nameptr</span><span class="o">,</span> <span class="n">size_t</span> <span class="n">namelen</span><span class="o">,</span> <span class="kd">const</span><span class="o">(</span><span class="kt">ubyte</span><span class="o">*)</span> <span class="n">bufptr</span><span class="o">,</span> <span class="n">size_t</span> <span class="n">buflen</span><span class="o">);</span>
<span class="kt">void</span> <span class="nf">wasm_sound_play</span><span class="o">(</span><span class="kd">const</span><span class="o">(</span><span class="kt">char</span><span class="o">*)</span> <span class="n">nameptr</span><span class="o">,</span> <span class="n">size_t</span> <span class="n">namelen</span><span class="o">);</span>
<span class="kt">void</span> <span class="nf">wasm_sound_fadeMusic</span><span class="o">(</span><span class="kt">uint</span> <span class="n">ms</span><span class="o">);</span>
<span class="kt">void</span> <span class="nf">wasm_sound_haltMusic</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>The main trick here was to make sure of 2 things:</p>
<ul>
<li>Playing the same sound effect multiple times in a row is possible</li>
<li>The music system needs to behave the same way as SDL_Mixer: only one music at once, in a loop, and some way to fade before the next music is played</li>
</ul>
<p>For 1, I found some StackOverflow answers that weren’t satisfying until I discovered that <code>AudioContext.createBufferSource</code> can just be called every time we need to play a sound and we only need the <code>AudioBuffer</code> instances for each sound to be preloaded.</p>
<p>For 2, the same flow can be reused for preloading but then also connect a <code>GainNode</code> to control the volume and store the sound instance so it can be stopped when the next music starts. Conveniently, the <code>gain</code> property is an <code>AudioParam</code> instance which has a <code>linearRampToValueAtTime</code> method which is used to fade out the music.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"> <span class="c1">// ...
</span><span class="c1"></span> <span class="nx">wasm_sound_play</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">nameptr</span><span class="p">,</span> <span class="nx">namelen</span><span class="p">)</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">name</span> <span class="o">=</span> <span class="nx">decoder</span><span class="p">.</span><span class="nx">decode</span><span class="p">(</span><span class="k">new</span> <span class="nx">Uint8Array</span><span class="p">(</span><span class="nx">memory</span><span class="p">.</span><span class="nx">buffer</span><span class="p">,</span> <span class="nx">nameptr</span><span class="p">,</span> <span class="nx">namelen</span><span class="p">));</span>
<span class="kr">const</span> <span class="nx">isMusic</span> <span class="o">=</span> <span class="nx">name</span><span class="p">.</span><span class="nx">startsWith</span><span class="p">(</span><span class="s2">"sounds/musics"</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">src</span> <span class="o">=</span> <span class="nx">ac</span><span class="p">.</span><span class="nx">createBufferSource</span><span class="p">();</span>
<span class="nx">src</span><span class="p">.</span><span class="nx">buffer</span> <span class="o">=</span> <span class="nx">acData</span><span class="p">[</span><span class="nx">name</span><span class="p">];</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">isMusic</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">acMusic</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">acMusic</span><span class="p">.</span><span class="nx">node</span><span class="p">.</span><span class="nx">stop</span><span class="p">();</span>
<span class="nx">acMusic</span><span class="p">.</span><span class="nx">gain</span><span class="p">.</span><span class="nx">disconnect</span><span class="p">();</span>
<span class="nx">acMusic</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
<span class="p">}</span>
<span class="kr">const</span> <span class="nx">gain</span> <span class="o">=</span> <span class="nx">ac</span><span class="p">.</span><span class="nx">createGain</span><span class="p">();</span>
<span class="nx">src</span><span class="p">.</span><span class="nx">connect</span><span class="p">(</span><span class="nx">gain</span><span class="p">);</span>
<span class="nx">src</span><span class="p">.</span><span class="nx">loop</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="nx">gain</span><span class="p">.</span><span class="nx">connect</span><span class="p">(</span><span class="nx">ac</span><span class="p">.</span><span class="nx">destination</span><span class="p">);</span>
<span class="nx">acMusic</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">node</span><span class="o">:</span> <span class="nx">src</span><span class="p">,</span> <span class="nx">gain</span><span class="o">:</span> <span class="nx">gain</span> <span class="p">};</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="nx">src</span><span class="p">.</span><span class="nx">connect</span><span class="p">(</span><span class="nx">ac</span><span class="p">.</span><span class="nx">destination</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">src</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span>
<span class="p">},</span>
<span class="nx">wasm_sound_fadeMusic</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">ms</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">acMusic</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">acMusic</span><span class="p">.</span><span class="nx">gain</span><span class="p">.</span><span class="nx">linearRampToValueAtTime</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">ac</span><span class="p">.</span><span class="nx">currentTime</span> <span class="o">+</span> <span class="nx">ms</span> <span class="o">*</span> <span class="mf">0.001</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">},</span>
<span class="c1">// ...
</span></code></pre></td></tr></table>
</div>
</div><h2 id="fix-gamedraw-loop">Fix game/draw loop</h2>
<p>On platforms where the game runs a bit slower, it looks a bit jarring as the whole gameplay slows down to a crawl. The usual way I fix this is by using the method from <a href="https://gafferongames.com/post/fix_your_timestep/">G<NAME>ler</a>. It’s similar to what the original game did but original had a sleep timer which isn’t very practical and doesn’t really work in some contexts.</p>
<p>The big change is splitting the update loop from the draw method. The game loop is now done in JS to avoid having to pass frame times back and forth across the JS/WASM boundary.</p>
<p>It looks something like this:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="kr">const</span> <span class="nx">targetFrameRate</span> <span class="o">=</span> <span class="mf">1000.0</span> <span class="o">/</span> <span class="mf">60.0</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">frameAccumulator</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">previousTimestamp</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
<span class="kd">function</span> <span class="nx">loop</span><span class="p">(</span><span class="nx">timestamp</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">previousTimestamp</span> <span class="o">==</span> <span class="kc">null</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">previousTimestamp</span> <span class="o">=</span> <span class="nx">timestamp</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">diff</span> <span class="o">=</span> <span class="nx">timestamp</span> <span class="o">-</span> <span class="nx">previousTimestamp</span><span class="p">;</span>
<span class="nx">previousTimestamp</span> <span class="o">=</span> <span class="nx">timestamp</span><span class="p">;</span>
<span class="nx">frameAccumulator</span> <span class="o">+=</span> <span class="nx">diff</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">numUpdates</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="nx">frameAccumulator</span> <span class="o">>=</span> <span class="nx">targetFrameRate</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">frameAccumulator</span> <span class="o">-=</span> <span class="nx">targetFrameRate</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exports</span><span class="p">.</span><span class="nx">_update</span><span class="p">())</span> <span class="p">{</span>
<span class="nx">numUpdates</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="k">break</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">numUpdates</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">exports</span><span class="p">.</span><span class="nx">_draw</span><span class="p">();</span>
<span class="nx">numUpdates</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">requestAnimationFrame</span><span class="p">(</span><span class="nx">loop</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="loading-screen">Loading screen</h2>
<p>With adding the audio, the transfer of <code>tt.wasm</code> is becoming a problem on first visit (it’s cached afterwards). Before embedding the audio, the server side compression in HTTP was doing an amazing job. However, with <code>.ogg</code> files it’s not as efficient as those are already compressed. At the time of writing, it’s a 5.49 MB transferred for a 7.66 MB total file size once decompressed. I’ll need to find a solution and show a progress bar during loading.</p>
<p>For this, I had the idea of using an embedded SVG document inside the index page to avoid multiple transfers and have a way of displaying the controls while it’s loading. To get the SVG, I did a debug output of some of the vector art from the game into a SVG path syntax (the <code>d</code> attribute of a <code>path</code> element) and included that into the index page. That means the game title is now visible even before the loading the WASM binary is done.</p>
<p>With this, because all the static content is included in the index page, it’s possible to show something if JavaScript is disabled. Then, if it’s enabled, we can test for browser features required and for optional ones. A message is displayed accordingly.</p>
<p>If everything works, the Fetch API is used to report an accurate progress bar of how the WASM download is doing. If compression is enabled server side the <code>Content-Length</code> header from the HTTP request isn’t accurate is it’s the compressed size. The solution I used here is to hardcode the WASM size in the JS code as it’s unlikely to change drastically anyway.</p>
<video controls src="/media/articles/tt_loading.mp4"></video>
<h2 id="saving-local-scoresreplays">Saving local scores/replays</h2>
<p>The game save 2 types of files: a <code>tt.prf</code> file which contains high-scores and unlocked levels, replays as <code>last.rpl</code> and <code>error.rpl</code>. I’m going to map the <code>std.file.read</code> and <code>std.file.write</code> functions to read/write with the LocalStorage API in JavaScript. The only trick here is that LocalStorage is a string key/value store, it maps string keys to string values. It’s very simple to use for my binary data, I have to convert the files to/from a string. I tried using the <code>btoa</code>/<code>atob</code> calls in JavaScript but it expects well-formed strings which aren’t going to work the data the game is writing as it can contain invalid UTF-8 sequences for example. So I just converted to a hex string, eg. <code>[104, 101, 108, 108, 111]</code> becomes <code>68656c6c6f</code> and vice-versa.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="kd">function</span> <span class="nx">bin2hex</span><span class="p">(</span><span class="nx">buf</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">buf</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">hexstr</span><span class="p">,</span> <span class="kr">byte</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">hexstr</span> <span class="o">+</span> <span class="p">(</span><span class="s1">'0'</span> <span class="o">+</span> <span class="p">(</span><span class="kr">byte</span> <span class="o">&</span> <span class="mh">0xFF</span><span class="p">).</span><span class="nx">toString</span><span class="p">(</span><span class="mi">16</span><span class="p">)).</span><span class="nx">slice</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">);</span>
<span class="p">},</span> <span class="s2">""</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">hex2bin</span><span class="p">(</span><span class="nx">hexstr</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">Uint8Array</span><span class="p">.</span><span class="nx">from</span><span class="p">(</span><span class="nx">hexstr</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/../g</span><span class="p">).</span><span class="nx">reduce</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">bytes</span><span class="p">,</span> <span class="nx">hex</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">bytes</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nb">parseInt</span><span class="p">(</span><span class="nx">hex</span><span class="p">,</span> <span class="mi">16</span><span class="p">));</span>
<span class="k">return</span> <span class="nx">bytes</span><span class="p">;</span>
<span class="p">},</span> <span class="p">[]));</span>
<span class="p">}</span>
<span class="c1">// ...
</span><span class="c1"></span>
<span class="nx">wasm_writeFile</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">nameptr</span><span class="p">,</span> <span class="nx">namelen</span><span class="p">,</span> <span class="nx">dataptr</span><span class="p">,</span> <span class="nx">datalen</span><span class="p">)</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">name</span> <span class="o">=</span> <span class="nx">decoder</span><span class="p">.</span><span class="nx">decode</span><span class="p">(</span><span class="k">new</span> <span class="nx">Uint8Array</span><span class="p">(</span><span class="nx">memory</span><span class="p">.</span><span class="nx">buffer</span><span class="p">,</span> <span class="nx">nameptr</span><span class="p">,</span> <span class="nx">namelen</span><span class="p">));</span>
<span class="kr">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Uint8Array</span><span class="p">(</span><span class="nx">memory</span><span class="p">.</span><span class="nx">buffer</span><span class="p">,</span> <span class="nx">dataptr</span><span class="p">,</span> <span class="nx">datalen</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">str</span> <span class="o">=</span> <span class="nx">bin2hex</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
<span class="nx">localStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">str</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">"saved "</span> <span class="o">+</span> <span class="nx">name</span> <span class="o">+</span> <span class="s2">" with "</span> <span class="o">+</span> <span class="nx">data</span><span class="p">.</span><span class="nx">length</span> <span class="o">+</span> <span class="s2">" bytes"</span><span class="p">);</span>
<span class="p">},</span>
</code></pre></td></tr></table>
</div>
</div><p>Note the files are binary compatible with the original game. If you have a replay or high-scores, you can technically import them in the browser using the Dev Tools and have the online version of the game load them.</p>
<h2 id="mobile-support">Mobile support</h2>
<p>A lot of people nowadays just browse on mobile (hello you!), I thought it would be great if the game was somewhat playable on mobile. It’s a lot of work to get it to behave close to a native app but I tried to do that.</p>
<h3 id="fullscreen-mode">Fullscreen mode</h3>
<p>This is easy, there is an API for it that’s been around for a while. I just had to add a button.</p>
<h3 id="on-screen-controls">On screen controls</h3>
<p>A bit harder, but I didn’t want to make it too complicated. The main element here is a SVG layer on top that has elements with <code>id</code> attribute set. Every time a touch event happens, the touched elements are checked and the <code>id</code> is mapped to the bitmask the game knows.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-js" data-lang="js"><span class="kr">const</span> <span class="nx">uiMap</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">uiA</span><span class="o">:</span> <span class="mh">0x10</span><span class="p">,</span>
<span class="nx">uiB</span><span class="o">:</span> <span class="mh">0x20</span><span class="p">,</span>
<span class="nx">uiBack</span><span class="o">:</span> <span class="mh">0x40</span><span class="p">,</span>
<span class="nx">uiDirR</span><span class="o">:</span> <span class="mh">0x8</span><span class="p">,</span>
<span class="nx">uiDirBR</span><span class="o">:</span> <span class="mh">0xA</span><span class="p">,</span>
<span class="nx">uiDirB</span><span class="o">:</span> <span class="mh">0x2</span><span class="p">,</span>
<span class="nx">uiDirBL</span><span class="o">:</span> <span class="mh">0x6</span><span class="p">,</span>
<span class="nx">uiDirL</span><span class="o">:</span> <span class="mh">0x4</span><span class="p">,</span>
<span class="nx">uiDirTL</span><span class="o">:</span> <span class="mh">0x5</span><span class="p">,</span>
<span class="nx">uiDirT</span><span class="o">:</span> <span class="mh">0x1</span><span class="p">,</span>
<span class="nx">uiDirTR</span><span class="o">:</span> <span class="mh">0x9</span>
<span class="p">};</span>
<span class="kd">function</span> <span class="nx">uiID</span><span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">element</span><span class="p">.</span><span class="nx">id</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">element</span><span class="p">.</span><span class="nx">id</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">element</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">element</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">.</span><span class="nx">id</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">registerTouchEvent</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">state</span><span class="p">)</span> <span class="p">{</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">ids</span> <span class="o">=</span> <span class="p">[];</span>
<span class="k">for</span> <span class="p">(</span><span class="kr">const</span> <span class="nx">touch</span> <span class="k">of</span> <span class="nx">event</span><span class="p">.</span><span class="nx">touches</span><span class="p">)</span> <span class="p">{</span>
<span class="kr">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">elementFromPoint</span><span class="p">(</span><span class="nx">touch</span><span class="p">.</span><span class="nx">clientX</span><span class="p">,</span> <span class="nx">touch</span><span class="p">.</span><span class="nx">clientY</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">id</span> <span class="o">=</span> <span class="nx">uiID</span><span class="p">(</span><span class="nx">element</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">id</span> <span class="k">in</span> <span class="nx">uiMap</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">ids</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nx">touchInputState</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="nx">id</span> <span class="k">of</span> <span class="nx">ids</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">touchInputState</span> <span class="o">|=</span> <span class="nx">uiMap</span><span class="p">[</span><span class="nx">id</span><span class="p">];</span>
<span class="p">}</span>
<span class="nx">updateInput</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">ids</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">},</span> <span class="kc">false</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">registerTouchEvent</span><span class="p">(</span><span class="s2">"touchstart"</span><span class="p">);</span>
<span class="nx">registerTouchEvent</span><span class="p">(</span><span class="s2">"touchend"</span><span class="p">);</span>
<span class="nx">registerTouchEvent</span><span class="p">(</span><span class="s2">"touchmove"</span><span class="p">);</span>
<span class="nx">registerTouchEvent</span><span class="p">(</span><span class="s2">"touchcancel"</span><span class="p">);</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="progressive-web-app-pwa-support">Progressive Web App (PWA) support</h3>
<p>This mainly consisted of generating the <code>manifest.json</code> file to describe the application. A lot of tutorials I have found describing the setup of a PWA usually omitted to detail the ServiceWorker life cycle though. Every time the page loads, the <code>sw.js</code> file is checked for differences, and if there are any it’ll load a new worker but only shut down the previous one when the page is closed and not when merely reloading (except when using Shift+F5). In the end, I added a simple way during the public deploy to add the git commit SHA in <code>sw.js</code> to reload it every time it changes and that also clears the cache. Otherwise files would still be in cache.</p>
<p><img src="/media/articles/tt7.png" alt=""></p>
<h2 id="wrapping-up-the-series">Wrapping up the series</h2>
<p>It’s been a long journey but it was a very good project personally. Some of things I had to learn and discover:</p>
<ul>
<li>Evolution of D as a language: I had to modify code from D v0.110 to work on the modern frontend D v2.093 (when I started the project it was the latest). This was great experience as I could see both evolution of language and standard library.</li>
<li>Removing dependencies by writing my own parser for expressions and XML: this was fun and very satisfying once it was working.</li>
<li>Porting from deprecated OpenGL to more modern API: this is close to my day job so it wasn’t too bad, it’s the usual thing of lowering the overhead of the CPU side by doing less things.</li>
<li>Making a custom runtime for D was fun but painful at times: there is some progress being made here but it’ll take a while before it becomes easier.</li>
<li>Learning new(-ish) web technologies I hadn’t touched before: WebAssembly, WebGL, WebAudio, LocalStorage, PWA</li>
<li>Asking questions on the D forums was a great experience: the people are always helpful and everyone enjoys participating</li>
</ul>
<p>Finally, I don’t think this is finished just yet as I’m sure there’ll be some feedback and issues found. Anyway, thanks for reading up to here. Enjoy the game!</p>
<p>It’s playable at <a href="https://torustrooper.xyz">https://torustrooper.xyz</a></p>
<p>Code is available at <a href="https://github.com/speps/tt">https://github.com/speps/tt</a></p>
</div>
</div>
<div id="footer"><p>2021-03-06 09:57:50 UTC - I speak for myself, I am not affiliated with any company - All rights reserved</p></div>
</div>
</div>
</body>
</html> | fdd1713cdc304beeae76ee8e74defbc4ff221a45 | [
"JavaScript",
"HTML"
] | 3 | HTML | speps/speps.github.io | 5678f9480e7efdc6d930f4ca0f309819efe9c208 | 21f4a00e72b5c34607277ac83a362114f4417c48 |
refs/heads/master | <file_sep>
exports.render = function(model, outputFolder, options) {
// Port the code from this pull request
// https://github.com/rprieto/supersamples/issues/4
};
| 164f47c84a615ed3c3a29f9b6e059e8fd4b64261 | [
"JavaScript"
] | 1 | JavaScript | shaketbaby/supersamples | c948d52490b61c5e29da6401a6efb101ff3907bb | a7c54597fd18e7b09647f1fa6abc69ed4c22051f |
refs/heads/master | <file_sep>const setupDevEnv = require('./index');
// To mock the module, enable next 2 lines
//jest.mock('./index');
//setupDevEnv.mockResolvedValue({os: 'custom OS'});
it('should return the os info for the environment', () => {
/*
try {
const output = await setupDevEnv();
expect(output.os).toBeDefined();
} catch (err) {
expect(err).toThrow(err);
}
*/
setupDevEnv().then(output => {
expect(output.os).toBeDefined();
}).catch(err => expect(err).toThrow(err));
});
<file_sep>Setup Dev Env
https://github.com/tulaneadam/setup-dev-env
Setup Dev Env is a cross-platform node app to detect your computer's OS and automatically set up your development environment on Windows, Mac, and Linux platforms. Install Node.js, Mongodb, Git, GitKraken, VSCode, Nautilus (Linux only) and the main package manager(Chocolatey, Brew, Snap, or Gnome Software Center) on any platform the app is run on.
A. To install and run setup-dev-env node app on Windows, Mac, or Linux(debian/ubuntu/mint/chromebook):
Step 1. Install nodejs:
a. Linux(Debian/Chromebook) (run in terminal):
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - && sudo apt-get install -y nodejs
b. Linux (Ubuntu/Mint) (run in terminal):
sudo apt install -y nodejs npm
c. Mac (download and run nodejs installer):
https://nodejs.org/dist/v10.16.3/node-v10.16.3.pkg
d. Windows (download and run nodejs installer):
https://nodejs.org/dist/v10.16.3/node-v10.16.3-x86.msi
Step 2. Download the setup-dev-env app to your desktop and unzip.
https://github.com/tulaneadam/setup-dev-env/archive/master.zip
Step 3. Open folder in terminal, install and run with:
cd setup-dev-env-master
npm i && npm start
Step 4. Restart computer when finished (Linux users only).
| 21e98dcb3cb2f7d9c1aa066a209fbb4abd6db374 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | tulaneadam/setup-dev-env | c4d376494f31c42c78cbba8caf05c1cb01bacdde | 444f2d4324e6535ad51bde2eb3db7c7e7265474b |
refs/heads/master | <repo_name>drikerf/drikerf<file_sep>/README.md
# Drikerf.com
Personal webpage.
<file_sep>/public/js/drikerf.js
// Nothing here. Or is there? ...
| c8ca9f37cd7866c1e9a303992c66401f76a64bfc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | drikerf/drikerf | de088d0e587490971299030f7cc64f33ecdf78d0 | 557225a10163f019bd72dd407367cfb4bbb59428 |
refs/heads/master | <repo_name>s3virge/CodingBat<file_sep>/src/CodingBat/Main.java
package CodingBat;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// testAltPairs();
testwithoutX2();
}
/*
Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien".
altPairs("kitten") → "kien"
altPairs("Chocolate") → "Chole"
altPairs("CodingHorror") → "Congrr"
altPairs("yak") → "ya"
altPairs("ya") → "ya"
altPairs("y") → "y"
altPairs("") → ""
altPairs("ThisThatTheOther") → "ThThThth" "ThThThth" OK
*/
public static String altPairs(String str) {
String sRes = new String();
int sLength = str.length();
if (sLength == 0) {
return str;
}
int n = 0;
for (int c = 0; c < sLength; c++) {
if (n > 1) {
n = 0;
c += 2;
}
if (c > sLength - 1) {
break;
}
sRes += str.charAt(c);
n++;
}
return sRes;
}
public static String altPairs2(String str) {
String sRes = new String();
for (int c = 0; c < str.length(); c += 4) {
int end = c + 2;
if (end > str.length()) {
end = str.length();
}
sRes += str.substring(c, end);
}
return sRes;
}
public static String altPairsAnswer(String str) {
String result = "";
// Run i by 4 to hit 0, 4, 8, ...
for (int i=0; i<str.length(); i += 4) {
// Append the chars between i and i+2
int end = i + 2;
if (end > str.length()) {
end = str.length();
}
result = result + str.substring(i, end);
}
return result;
}
public static String withoutX2(String str) {
int counter = 0;
//если в строке два символа и больше, то проверяем вторую букву на 'x'
if (str.length() > 1 && str.charAt(1) == 'x') {
//вторая буква 'x' избавляемся от нее
str = str.charAt(0) + str.substring(2);
counter++;
}
//если строка не пустая и первая буква х
if (str.length() > 0 && str.charAt(0) == 'x') {
str = str.substring(1); //то избавляемя от х
counter++;
}
//str стала на один символ короче. //если строка не пустая и первая буква х
//и еще не удалялись две буквы х
if (str.length() > 0 && counter !=2 && str.charAt(0) == 'x') {
str = str.substring(1);
}
return str;
}
public static void testAltPairs() {
ArrayList<String> arr = new ArrayList<String>();
arr.add("kitten");
arr.add("Chocolate");
arr.add("CodingHorror");
arr.add("yak");
arr.add("ya");
arr.add("y");
arr.add("");
arr.add("");
for (String str : arr) {
System.out.print(str + " -> ");
System.out.println(altPairs(str));
}
}
public static void testwithoutX2() {
ArrayList<String> arr = new ArrayList<String>();
arr.add("xHi");
arr.add("Hxi");
arr.add("Hi");
arr.add("");
arr.add("q");
arr.add("x");
arr.add("qq");
arr.add("xq");
arr.add("qx");
arr.add("xx");
arr.add("xxx");
arr.add("xaxb");
arr.add("xHxllo");
for (String str : arr) {
System.out.print(str + " -> ");
System.out.println(withoutX2(str));
}
}
}
| 0b6468d00785d7aaa6b5cdd4d83fede026e273a0 | [
"Java"
] | 1 | Java | s3virge/CodingBat | aaeab7c0de733f2bb5432e1bb7e0fb2d0cf2ee18 | 3a6d83cafdc421edf39374f3ecf31738e2ff3234 |
refs/heads/master | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnangis <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/20 20:00:12 by nnangis #+# #+# */
/* Updated: 2018/03/27 18:09:00 by nnangis ### ########.fr */
/* */
/* ************************************************************************** */
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "libft.h"
#include "fillit.h"
static int count_links(const char buf[22])
{
int i;
int links;
i = 0;
links = 0;
while (i < 20)
{
if (buf[i] == '#')
{
if ((i + 1) < 20 && buf[i + 1] == '#')
++links;
if ((i - 1) >= 0 && buf[i - 1] == '#')
++links;
if ((i + 5) < 20 && buf[i + 5] == '#')
++links;
if ((i - 5) >= 0 && buf[i - 5] == '#')
++links;
}
i++;
}
if (links == 6 || links == 8)
return (1);
return (0);
}
static uint32_t record_tetrimino(const char buf[22])
{
int i;
int j;
uint32_t tetrimino;
i = 0;
j = -1;
tetrimino = 0;
while (i < 19)
{
if (buf[i] == '#')
{
if (j == -1)
j = i;
tetrimino |= (1 << (i - j));
}
++i;
}
return (tetrimino);
}
static uint32_t is_valid(const char buf[22], int ret, int sharp, int dots)
{
int i;
i = 0;
while (i < 20)
{
if (i % 5 < 4)
{
if (buf[i] != '.' && buf[i] != '#')
return (-1U);
else if (buf[i] == '#')
++sharp;
else if (buf[i] == '.')
++dots;
}
else if (buf[i] != '\n')
return (-1U);
++i;
}
if ((ret == 21 && buf[i] != '\n')
|| sharp != 4 || dots != 12 || !count_links(buf))
return (-1U);
return (record_tetrimino(buf));
}
int parse_file(t_fillit *data, const char *path)
{
int fd;
char buf[22];
t_tetri *new;
int ret;
int save_ret;
if ((fd = open(path, O_RDONLY)) == -1)
return (-1);
ft_bzero(buf, 22);
while ((ret = read(fd, buf, 21)) > 0)
{
if (ft_strlen(buf) < 20 || (new = create_tetri(is_valid(buf, ret, 0, 0),
data->letter++)) == 0 || new->tetrimino == -1U
|| data->nb_tetri++ > 26)
{
free_list(&data->list);
return (-1);
}
save_ret = ret;
enqueue(&data->list, new);
ft_bzero(buf, 21);
}
if (data->nb_tetri == 0 || close(fd) == -1 || save_ret != 20)
return (-1);
return (0);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: nnangis <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2017/07/04 20:38:48 by nnangis #+# #+# #
# Updated: 2017/07/04 21:26:52 by nnangis ### ########.fr #
# #
# **************************************************************************** #
NAME = libft.a
SOURCES =ft_memset.c ft_bzero.c ft_memcpy.c ft_memccpy.c ft_memmove.c \
ft_memchr.c ft_memcmp.c ft_memalloc.c ft_memdel.c \
ft_isalnum.c ft_isalpha.c ft_isascii.c ft_isdigit.c ft_isprint.c \
ft_itoa.c ft_atoi.c ft_tolower.c ft_toupper.c \
ft_putchar.c \
ft_putendl.c ft_putnbr.c \
ft_putstr.c \
ft_putchar_fd.c \
ft_putendl_fd.c ft_putnbr_fd.c \
ft_putstr_fd.c \
ft_strcat.c ft_strchr.c ft_strclr.c ft_strcmp.c ft_strcpy.c \
ft_strdel.c ft_strdup.c ft_strequ.c ft_striter.c ft_striteri.c \
ft_strjoin.c ft_strlcat.c ft_strlen.c ft_strmap.c ft_strmapi.c \
ft_strncat.c ft_strncmp.c ft_strncpy.c ft_strnequ.c ft_strnew.c \
ft_strnstr.c ft_strrchr.c ft_strsplit.c ft_strstr.c \
ft_strsub.c ft_strtrim.c \
ft_lstadd.c ft_lstdel.c ft_lstdelone.c ft_lstiter.c \
ft_lstmap.c ft_lstnew.c \
ft_print_a.c
HEADERS = libft.h
OBJECTS = $(subst .c,.o,$(SOURCES))
WFLAGS = -Wall -Werror -Wextra
all: $(NAME)
$(NAME): $(OBJECTS)
@ar rc $(NAME) $(OBJECTS)
@ranlib $(NAME)
$(OBJECTS): $(SOURCES) $(HEADERS)
@gcc $(WFLAGS) -c $(SOURCES)
clean:
@rm -f $(OBJECTS)
fclean: clean
@rm -f $(NAME)
re: fclean all
.PHONY: all clean fclean re
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnangis <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/22 16:07:55 by nnangis #+# #+# */
/* Updated: 2018/03/27 18:08:35 by nnangis ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
#include "fillit.h"
char *grow_map(char *map, uint32_t *map_size, t_tetri **list)
{
char *new_map;
*map_size += 1;
if (!(new_map = create_map(*map_size)))
{
free_list(list);
ft_putendl_fd("Cannot allocate more memory, exit...", 2);
exit(EXIT_FAILURE);
}
free(map);
return (new_map);
}
char *create_map(uint32_t map_size)
{
uint32_t i;
uint32_t len;
char *map;
i = 0;
len = map_size * map_size + map_size;
if (!(map = ft_strnew(len)))
return (NULL);
while (i < len)
{
map[i] = '.';
++i;
if ((i + 1) % (map_size + 1) == 0)
map[i++] = '\n';
}
return (map);
}
void scale_up(uint64_t *new_val, uint64_t mask, uint8_t line_count)
{
*new_val += (mask << line_count);
}
void scale_down(uint64_t *new_val, uint64_t mask, uint8_t line_count)
{
*new_val += (mask >> line_count);
}
void scale_values(t_tetri *list,
void (*scale_ft)(uint64_t *, uint64_t, uint8_t))
{
uint64_t mask;
uint64_t new_val;
uint8_t line_count;
while (list)
{
mask = 1;
new_val = 0;
line_count = 1;
while (list->tetrimino & mask)
{
new_val += mask;
mask <<= 1;
}
while ((mask <<= 1) < list->tetrimino)
if (list->tetrimino & mask)
{
scale_ft(&new_val, mask, line_count);
if (!(list->tetrimino & (mask << 1)))
++line_count;
}
if (list->tetrimino != 0xF)
list->tetrimino = new_val;
list = list->next;
}
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnangis <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/20 20:12:17 by nnangis #+# #+# */
/* Updated: 2018/03/27 18:07:58 by nnangis ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FILLIT_H
# define FILLIT_H
# include <inttypes.h>
# define PLACE 1
# define CLEAR 0
typedef struct s_tetri
{
uint64_t tetrimino;
char letter;
struct s_tetri *next;
} t_tetri;
typedef struct s_fillit
{
t_tetri *list;
char *map;
uint32_t map_size;
uint32_t nb_tetri;
char letter;
} t_fillit;
int parse_file(t_fillit *data, const char *path);
void enqueue(t_tetri **list, t_tetri *entry);
void free_list(t_tetri **list);
t_tetri *create_tetri(uint32_t data, char letter);
char *grow_map(char *map, uint32_t *cur_size, t_tetri **list);
void algo(t_fillit *data);
uint32_t resize_map(uint32_t limit, t_tetri *list);
char *create_map(uint32_t map_size);
void scale_values(t_tetri *list,
void (*scale_ft)(uint64_t *, uint64_t, uint8_t));
void scale_up(uint64_t *new_val, uint64_t mask, uint8_t line_count);
void scale_down(uint64_t *new_val, uint64_t mask,
uint8_t line_count);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnangis <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/20 20:31:04 by nnangis #+# #+# */
/* Updated: 2018/03/22 15:54:34 by nnangis ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "fillit.h"
t_tetri *create_tetri(uint32_t data, char letter)
{
t_tetri *new;
if (!(new = (t_tetri *)malloc(sizeof(*new))))
return (NULL);
new->tetrimino = data;
new->letter = letter;
new->next = NULL;
return (new);
}
void enqueue(t_tetri **list, t_tetri *entry)
{
t_tetri *tmp;
if (*list == NULL)
*list = entry;
else
{
tmp = *list;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = entry;
}
}
void free_list(t_tetri **list)
{
t_tetri *tmp;
tmp = *list;
while (tmp)
{
tmp = (*list)->next;
free(*list);
(*list) = tmp;
}
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* algo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnangis <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/20 20:00:31 by nnangis #+# #+# */
/* Updated: 2018/04/06 01:08:41 by abeauvoi ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
#include "libft.h"
#include "fillit.h"
static void place_tetri(int tetrimino, char *map, char mode, char letter)
{
if (mode == PLACE)
while (tetrimino > 0)
{
if (tetrimino & 1)
*map = letter;
tetrimino >>= 1;
++map;
}
else
while (tetrimino > 0)
{
if (tetrimino & 1)
*map = '.';
tetrimino >>= 1;
++map;
}
}
static int can_place_tetri(char *map, int tetrimino)
{
while (*map && tetrimino)
{
if ((*map == '\n' || *map != '.') && (tetrimino & 1) == 1)
return (0);
tetrimino >>= 1;
++map;
}
return (tetrimino == 0);
}
static int solve(int pos, char *map, t_tetri *list)
{
if (list == NULL)
return (1);
if (map[pos] == 0)
return (0);
if (can_place_tetri(map + pos, list->tetrimino) == 1)
{
place_tetri(list->tetrimino, map + pos, PLACE, list->letter);
if (solve(0, map, list->next) == 1)
return (1);
place_tetri(list->tetrimino, map + pos, CLEAR, list->letter);
}
return (solve(pos + 1, map, list));
}
void algo(t_fillit *data)
{
if (data->nb_tetri == 1 && data->list->tetrimino == 99)
{
data->map_size = 2;
scale_values(data->list, scale_down);
}
if (data->nb_tetri <= 2)
{
data->map_size = 3;
scale_values(data->list, scale_down);
}
if (!(data->map = create_map(data->map_size)))
{
free_list(&data->list);
ft_putendl_fd("Cannot allocate more memory, exit...", 2);
exit(EXIT_FAILURE);
}
while (!solve(0, data->map, data->list))
{
data->map = grow_map(data->map, &data->map_size, &data->list);
scale_values(data->list, scale_up);
}
ft_putstr(data->map);
free(data->map);
}
<file_sep>NAME = fillit
LIB = libft.a
LIB_DIR = libft
PARSER_DIR = parser
SRC_DIR = src
ALGO_DIR = algo
OBJ_DIR = obj
VPATH = $(SRC_DIR):$(addprefix $(SRC_DIR)/, $(PARSER_DIR) $(ALGO_DIR))
SRC = main.c parser.c algo.c list.c utils.c
OBJ = $(addprefix $(OBJ_DIR)/,$(SRC:.c=.o))
CFLAGS = -Wall -Werror -Wextra -I. -I$(LIB_DIR)
LFLAGS = -L$(LIB_DIR) -lft
COMP = $(CC) $(CFLAGS) -o $@ -c $<
LINK = $(CC) $(LFLAGS) -o $@ $(filter-out $(LIB_DIR)/$(LIB) $(OBJ_DIR), $^)
all: $(NAME)
$(LIB_DIR)/$(LIB):
@make -C $(LIB_DIR)
$(NAME): $(LIB_DIR)/$(LIB) $(OBJ)
$(LINK)
$(OBJ_DIR)/%.o: %.c
@mkdir -p $(OBJ_DIR)
$(COMP)
clean:
@rm $(OBJ) 2> /dev/null || true
@make -C $(LIB_DIR) $@
@rm -rf $(OBJ_DIR)
@echo "cleaned .o files"
fclean: clean
@rm $(NAME) 2> /dev/null || true
@make -C $(LIB_DIR) $@
@echo "removed binary"
re: fclean all
.PHONY: all clean fclean re
| 880ea419f101f5596c748f61fd080aa04d350b00 | [
"C",
"Makefile"
] | 7 | C | abeauvoi/fillit | 657667b7585e66dc9ee91a8afe18f9dd7aa207e8 | 0ab0b369c851b7ef67aa1ed14e83e268fdba5997 |
refs/heads/master | <file_sep>/**
* Creates a <portal> element with src.
* @param {String} src
*/
function createPortal(src) {
if (!'HTMLPortalElement' in window) {
console.error(this + ": This browser does not support the html <portal> tag!")
let portal = document.createElement('p')
portal.innerHTML('This browser does not support Portals! On Google Chrome, they can be enabled at chrome://flags.')
return portal
}
let portal = document.createElement('portal')
if (src) {
portal.src = src
}
portal.addEventListener('click', evt => {
portal.activate();
})
return portal
}
<file_sep>var music = new Audio('/gmodloadMusic.mp3')
music.play()
var fields = {
serverName: document.getElementById('ServerName'),
loadingStatus: document.getElementById('LoadingStatus'),
filesNeeded: 0,
currentFiles: 0,
}
function GameDetails(servername, serverurl, mapname, maxplayers, steamid, gamemode) {
fields.serverName.innerHTML = servername
}
function SetStatusChanged(status) {
fields.loadingStatus.innerHTML = status
}
function SetFilesTotal(total) {
fields.currentFiles = total
}
function SetFilesNeeded(needed) {
fields.filesNeeded = needed
refreshProgress()
}
function refreshProgress() {
var calculated
let currentFiles = fields.currentFiles
let filesNeeded = fields.filesNeeded
calculated = ((currentFiles - filesNeeded) / currentFiles) * 100
document.getElementById('progress').style = `width: ${calculated}%`
}<file_sep>local args = {...}
local file = args[1]
local path = http.get("https://sulfrix.github.io/slayds/content/".. file)
path = http.get("https://sulfrix.github.io/slayds/content/programs/".. file ..".lua")
local destpath = args[2]
program = fs.open("slaydsfiles/programfiles/".. destpath, "w")
program.write(path.readAll())
program.close()
path.close()
<file_sep>print("Updating Slay Download Service...")
shell.run("pastebin run JTg10ZgJ")
print("Finished updating.")
<file_sep>print("Now downloading 3rd party programs.")
print("I don't host these, the files download from the original pastebin.")
print("DISCLAIMER: I DID NOT MAKE THESE.")
sleep(3)
print("--------Enter program name below--------")
local file = read()
local path = http.get("https://sulfrix.github.io/slayds/content/programs/3rd_party/".. file ..".3rd")
program = fs.open("slaydsfiles/program", "w")
program.write(path.readAll())
program.close()
path.close()
shell.run("slaydsfiles/program")
<file_sep># Sulfrix's GitHub Pages
My GitHub Pages where I first started coding in HTML and JavaScript.\
I'm obviously not the best at any of this but this is all just for fun and when I'm bored.
<file_sep>print("Enter a URL to download the contents of it.")
local file = read()
print("Where should this be stored? (this makes a new file if it doesn't already exist. Otherwise, it overwrites the file.)")
local dest = read()
local path = http.get(file)
program = fs.open(dest, "w")
program.write(path.readAll())
program.close()
path.close()
print("File downloaded.")
<file_sep>print("Interactive command block!")
print("Do /quit to exit program.")
while true do
print("Enter command.")
term.write("/")
command = read()
if command == "quit" then
break
end
success, output = commands.exec(command)
if success == false then
term.setTextColor(colors.red)
print("Error!")
end
print(output[1])
term.setTextColor(colors.white)
end
<file_sep>function cleanmode ()
local options = {
cleanmode = false
}
shell.run("clear")
print("Clean Mode Setting")
print("Press Y to enable Clean Mode.")
print("Press anything else to disable.")
local event, key = os.pullEvent("key")
if key == keys.y then
options.cleanmode = true
else
options.cleanmode = false
end
local optfile = fs.open("slaydsfiles/options", "w")
optfile.write(textutils.serialise(options))
optfile.close()
end
local args = {...}
local action = args[1]
local file = args[2]
if not fs.exists("slaydsfiles/options") then
cleanmode()
end
local optfile = fs.open("slaydsfiles/options", "r")
local options = textutils.unserialise(optfile.readAll())
optfile.close()
if action == nil and not options.cleanmode == true then
print("Usage:")
print("slayds run <file>: Runs a file from SlayDS servers")
print("slayds save <file> <path>: Saves a file to your computer at <path>")
print("slayds run update: Updates SlayDS. Do this often.")
print("slayds cleanmode: Change the Clean Mode option.")
return
end
if options.cleanmode == true then
while true do
shell.run("clear")
term.setTextColor(colors.lightGray)
print("Clean Mode")
term.setTextColor(colors.white)
print("Welcome to Slay Download System!")
print("-----Actions-----")
print("R - Downloads and runs a file")
print("S - Saves a file at a path")
print("C - Change your Clean Mode Preferences")
print("E - Exit")
local event, key = os.pullEvent('key')
if key == keys.r then
sleep(0.1)
print("Enter the name of the file you want to run.")
local action = "run"
local file = read()
break
end
if key == keys.s then
sleep(0.1)
print("Enter the name of the file you want to save.")
local action = "save"
local file = read()
break
end
if key == keys.c then
sleep(0.1)
cleanmode()
return
end
if key == keys.e then
return
end
end
end
if action == "cleanmode" then
cleanmode()
return
end
if file == nil then
print("Please enter the desired file to download/run")
return
end
local path = http.get("https://sulfrix.github.io/slayds/content/programs/".. file ..".lua")
print("Downloading ".. args[1] .."...")
if not fs.exists("slaydsfiles/program") then
if not fs.exists("slaydsfiles/") then
fs.makeDir("slaydsfiles/")
end
local program = fs.open("slaydsfiles/program", "w")
program.close()
end
program = fs.open("slaydsfiles/program", "w")
program.write(path.readAll())
program.close()
path.close()
if action == "run" then
shell.run("clear")
shell.run("slaydsfiles/program")
fs.delete("slaydsfiles/program")
end
if action == "save" then
if args[3] == nil then
print("Specify a path.")
return
end
shell.run("clear")
path = http.get("https://sulfrix.github.io/slayds/content/programs/".. file ..".lua")
local destpath = args[3]
program = fs.open(destpath, "w")
program.write(path.readAll())
program.close()
end<file_sep>console.log(this + ": Loading notification system")
var notifArea = document.createElement('div');
var style = document.createElement('link');
if (window.localStorage.getItem('notifications') == null || window.localStorage.getItem('notifications') == "undefined") {
window.localStorage.setItem('notifications', '[]')
}
var closingAnimations = 0
style.rel = 'stylesheet'
style.href = 'styles/css/notifications.css'
notifArea.classList.add('notifArea');
notifArea.id = 'notifArea';
document.body.append(style);
document.body.append(notifArea);
class Notifsys {
constructor(key) {
this.storageKey = key
}
get notifList() {
return JSON.parse(window.localStorage.getItem(this.storageKey))
}
set notifList(notifList) {
window.localStorage.setItem(this.storageKey, JSON.stringify(notifList))
}
appendNotif(content, refresh) {
let tmpnotif = {}
let tmplist = this.notifList
tmpnotif.content = content
tmplist.push(tmpnotif)
this.notifList = tmplist
if (refresh == true) {
refreshNotifications()
}
}
}
var notifsys = new Notifsys('notifications')
function removeNotif(notifID) {
if (typeof notifID !== "number") {
return console.error(this + ": TypeError, expected number, got " + typeof notifID)
}
let x = notifsys.notifList
x.splice(notifID, 1)
notifsys.notifList = x
}
function refreshNotifications() {
let notifArea = document.getElementById('notifArea');
notifArea.innerHTML = ""
let notifs = notifsys.notifList;
for (i in notifs) {
let x = notifs[i];
let y = document.createElement('div');
let text = document.createElement('div');
let closeButton = document.createElement('button');
text.id = i
closeButton.addEventListener('click', evt => {
evt.path[0].classList.add('closingNotif')
evt.path[2].classList.add('closingNotif')
let x = evt.path[1].id
x = parseInt(x, 10)
removeNotif(x)
closingAnimations += 1
setTimeout(function () {
evt.path[2].classList.add('closedNotif')
closingAnimations -= 1
if (closingAnimations <= 0) {
refreshNotifications()
}
}, 1000)
})
y.addEventListener('click', evt => {
console.log(evt.path)
})
text.innerHTML = x.content;
closeButton.classList.add('closeButton')
closeButton.innerHTML = 'Dismiss'
text.classList.add('text')
y.classList.add('notification')
notifArea.appendChild(y)
y.appendChild(text)
text.appendChild(closeButton)
};
};
refreshNotifications()
| ea05fd2b8553a48e9ad278e99e4754d42a7f0d9b | [
"JavaScript",
"Markdown",
"Lua"
] | 10 | JavaScript | theslaymann/theslaymann.github.io | 7692f4264fb44c3022045dd0a5fb55d7ff3f0242 | 96be017cbcae2e0e4b0e5c4f2946e47b05e27f77 |
refs/heads/main | <file_sep>using System;
namespace program
{
class Program
{
static string removeBlancks(string str)
{
string removed = str.Replace(" ", "");
return removed;
}
static int GetDigit(string str)
{
string str2 = string.Empty;
int val = 0;
for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str[i]))
{
str2 += str[i];
}
}
if (str2.Length > 0)
{
val = int.Parse(str2);
}
return val;
}
static string Acronyms(string str)
{
char[] tempArray = new char[str.Length];
string abbr="";
int loop = 0;
tempArray = str.ToCharArray();
abbr += (char)((int)tempArray[0] ^ 32);
abbr += '-';
for (loop = 0; loop < str.Length - 1; loop++)
{
if (tempArray[loop] == ' ' || tempArray[loop] == '\t' || tempArray[loop] == '\n')
{
abbr += (char)((int)tempArray[loop + 1] ^ 32);
abbr += '-';
}
}
return abbr;
}
static int countNonSpaces(string str)
{
string nospaces = str.Replace(" ", "");
return nospaces.Length;
}
static string[] stringlessthan(string[] str, int value)
{
for(int i = 0; i < str.Length; i++)
{
int temp = (str[i].Length);
if(temp > value)
{
Console.WriteLine(str[i]);
}
}
return str;
}
static void Main(string[] args)
{
Console.WriteLine(removeBlancks("paosdpfo apsodf "));
Console.WriteLine("----------------------");
Console.WriteLine(GetDigit("12ksls3"));
Console.WriteLine("----------------------");
Console.WriteLine(Acronyms("ASDjhsd kajsdfhksajd AKSJDFHAKSDJH alsdkfalsdk LAKSDJFLASKDFJ asldkfjlasdkj ALDKFJALSDK lasdlkf"));
Console.WriteLine("----------------------");
Console.WriteLine(countNonSpaces("lasdkslfdk asdlkfk dkdkkd"));
Console.WriteLine("----------------------");
}
}
}
| ff845fd76ed852058eea282d256113051ab363be | [
"C#"
] | 1 | C# | isaacSoto10/Todo1 | 5657bb326f265937278cbce6cdae091518b0f66d | 49d2b562aac24f24b0853a0e8da6a0fc8d36606f |
refs/heads/master | <file_sep>CWho
----
<NAME> (<EMAIL>)
CWho centralizes the gathering of "who" data across a cluster of machines.
The data is recorded internally as a time series, which facilitates further
analytics.
A lightweight agent written in Go reads the utmp file directly on each client,
parses it and sends the data to a centralized collection server. The agent is
intended to run out of cron, at any frequency desired by the user.
A collection server also written in Go accepts connections from clients and
records each line of utmp data with a timestamp generated when the connection
is initiated.
A web dashboard written in Python shows the aggregate results recorded by the
server.
CWho permits rapid determination of whether or not a particular user is or is
not logged into any given machine at any time.
Schema for utmp table:
```
CREATE TABLE utmp (sampletime bigint, host varchar(258), user varchar(34),
line varchar(34), fromhost varchar(258), timestamp varchar(34));
```
Schema for hosts table:
```
CREATE TABLE hosts (host varchar(258), hostid integer NOT NULL
AUTO_INCREMENT PRIMARY KEY, mostrecent bigint);
```
Schema for last table:
```
CREATE TABLE last (host varchar(258), user varchar(34), timestamp varchar(34));
```
<file_sep>#!/usr/bin/python3
# Pull data from the CWho database and generate the Web dashboard
# <NAME> (<EMAIL>)
#
# Requires package: python3-mysqldb
#
import cgi, time, sys, MySQLdb, configparser
print('Content-type: text/html\n')
print('<html>')
print('<head>')
print('<title>CWho</title>')
print('<meta http-equiv="refresh" content="600">')
print('<style type="text/css">* { border-radius: 5px; } h1 { font-family: Arial, Helvetica; } p { font-size: medium; font-weight: bold; font-family: Arial, Helvetica; width: 80%; margin: 10px auto; } table { height: 15%; margin: 10px auto; width: 80%; } td { 0px; font-family: Courier; }</style>')
print('</head>')
print('<body bgcolor=White text=Black vlink=Black text=Black>')
print('<h1>CWho: ' + time.strftime("%A %b %d %H:%M:%S %Z", time.localtime()) + '</h1>')
cfg = configparser.ConfigParser()
cfg.read('/etc/cwho/dashboard.ini')
dbuser = cfg.get('database', 'user')
dbpass = cfg.get('database', 'passwd')
dbname = cfg.get('database', 'db')
dbhost = cfg.get('database', 'host')
db = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpass,db=dbname)
curs = db.cursor()
query = 'SELECT host, mostrecent from hosts ORDER BY host ASC;'
curs.execute(query)
hosts = curs.fetchall()
for host in hosts:
query = 'SELECT * FROM utmp WHERE host = \'' + host[0] + '\' AND sampletime = ' + str(host[1]) + ';'
curs.execute(query)
utmps = curs.fetchall()
toggle = 0
# user port fromhost time
print('<p>' + host[0] + '</p>')
print('<table>')
for row in utmps:
if toggle == 0:
print('<tr bgcolor=#ccffcc><td>')
else:
print('<tr><td>')
print(row[2])
print('</td><td>')
print(row[3])
print('</td><td>')
print(row[5])
print('</td><td>')
print(row[4])
print('</td></tr>')
toggle = not toggle
print('</table>')
# We need to commit() the query on inserts and modifies after execution before they actually take effect
# db.commit()
print('</body>')
print('</html>')
db.close()
<file_sep>//
// Cwho data collection server, <NAME>, <EMAIL>
//
package main
import (
"net"
"os"
"strings"
"bufio"
"log"
"strconv"
"time"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
var dbUser, dbPass, dbName, dbHost string
func main() {
var bindaddr, conffile string
if (len(os.Args) != 5) {
log.Fatalf("Usage: %s -b bindaddr -f configfile\n", os.Args[0])
}
for i := 1; i < len(os.Args); i++ {
switch os.Args[i] {
case "-b":
bindaddr = os.Args[i+1]
case "-f":
conffile = os.Args[i+1]
}
}
conf, err := os.Open(conffile)
if err != nil {
log.Fatalf("Failed opening configuration file for reading")
}
inp := bufio.NewScanner(conf)
for inp.Scan() {
line := inp.Text()
if (len(line) > 0) {
fields := strings.Fields(line)
key := strings.ToLower(fields[0])
switch key {
case "dbuser":
dbUser = fields[1]
case "dbpass":
dbPass = fields[1]
case "dbname":
dbName = fields[1]
case "dbhost":
dbHost = fields[1]
default:
log.Print("Ignoring nonsense configuration %s\n", fields[1])
}
}
}
conf.Close()
listener, err := net.Listen("tcp", bindaddr+":5963")
if err != nil {
log.Fatalf("Failure calling net.Listen()\n")
}
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go handle_connection(conn)
}
}
//
// Database schema:
// CREATE TABLE utmp (sampletime bigint, host varchar(258), user varchar(34), line varchar(34), fromhost varchar(258), timestamp varchar(34));
// CREATE TABLE hosts (host varchar(258), hostid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, mostrecent bigint);
// CREATE TABLE last (host varchar(258), user varchar(34), timestamp varchar(34));
//
func handle_connection(c net.Conn) {
var myDSN string
input := bufio.NewScanner(c)
//
// Generate a timestamp for these samples
//
t := time.Now().Unix()
tt := strconv.FormatInt(t, 10)
for input.Scan() {
inp := input.Text()
data := strings.Fields(inp)
host := data[0]
user := data[1]
line := data[2]
from := data[3]
secs, _ := strconv.ParseInt(data[4], 10, 64)
usecs, _ := strconv.ParseInt(data[5], 10, 64)
myDSN = dbUser + ":" + dbPass + "@tcp(" + dbHost + ":3306)/" + dbName
dbconn, dbConnErr := sql.Open("mysql", myDSN)
if dbConnErr != nil {
log.Fatalf("Failed connecting to database")
}
dbPingErr := dbconn.Ping()
if dbPingErr != nil {
log.Fatalf("Failed pinging database connection")
}
//
// Check to see if the host exists in the host tracking table
//
dbCmd := "SELECT COUNT(*) FROM hosts WHERE host = '" + host + "';"
_, dbExecErr := dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing SELECT for host " + host)
}
var hostp string
_ = dbconn.QueryRow(dbCmd).Scan(&hostp)
hostpi, _ := strconv.Atoi(hostp)
//
// If not, add it to the hosts table. MySQL will generate an ID
// If so, we need to update the sample time in the mostrecent
// field
//
if (hostpi == 0) {
dbCmd := "INSERT INTO hosts (host, mostrecent) VALUES ('" + host + "'," + tt + ");"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing host table INSERT for host " + host)
}
} else {
dbCmd := "UPDATE hosts SET mostrecent = " + tt + " WHERE host = '" + host + "';"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing host table mostrecent field UPDATE for host " + host)
}
}
//
// Add the most recent batch of utmp entries to the database
//
stamp := time.Unix(secs,usecs).Format(time.Stamp)
dbCmd = "INSERT INTO utmp VALUES (" + tt + ",'" + host + "','" + user + "','" + line + "','" + from + "','" + stamp + "');"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing utmp table INSERT for host " + host)
}
//
// Update last login table
//
dbCmd = "SELECT COUNT(*) FROM last WHERE host = '" + host + "' AND user ='" + user + "';"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing SELECT for host " + host)
}
var lastp string
_ = dbconn.QueryRow(dbCmd).Scan(&lastp)
lastpi, _ := strconv.Atoi(lastp)
// User-host pair not already present in last login table
if (lastpi == 0) {
dbCmd := "INSERT INTO last VALUES ('" + host + "','" + user + "','" + stamp + "');"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing last table INSERT for user " + user + " and host " + host)
}
} else {
dbCmd := "UPDATE last SET timestamp = '" + stamp + "' WHERE host = '" + host + "' AND user = '" + user + "';"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing last table UPDATE for user " + user + " and host " + host)
}
}
//
// Drop old utmp entries for this host so the DB doesn't grow without bound
//
dbCmd = "DELETE FROM utmp WHERE host = '" + host + "' AND sampletime != '" + tt + "';"
_, dbExecErr = dbconn.Exec(dbCmd)
if dbExecErr != nil {
log.Fatalf("Failed executing utmp table cleanup DELETE for host " + host)
}
dbconn.Close()
}
c.Close()
}
<file_sep>//
// CWho agent, <NAME>, <EMAIL>
//
package main
// go get github.com/EricLagergren/go-gnulib/utmp
import (
"os"
"strings"
"log"
"net"
"fmt"
"bytes"
"github.com/EricLagergren/go-gnulib/utmp"
)
func main() {
var u = "/var/run/utmp"
var ut []*utmp.Utmp
if ((len(os.Args) != 3) || (os.Args[1] != "-h")) {
log.Fatalf("Usage: %s -h server\n", os.Args[0])
}
host, _ := os.Hostname()
if (strings.Index(host, ".") != -1) {
host = host[0:strings.Index(host, ".")]
}
//
// Read in utmp file
//
ut, err := utmp.ReadUtmp(u, 0x00)
if err != nil {
log.Fatalf("Error opening utmp file for reading")
}
//
// Open the connection to the collection host
//
conn, err := net.Dial("tcp", os.Args[2]+":5963")
if err != nil {
log.Fatalf("Error calling net.Dial()")
}
//
// For each line of the utmp file, parse out the information that we need.
//
for _, arg := range ut {
if (arg.Type == 7) {
ts := int64(arg.Tv.Sec)
tu := int64(arg.Tv.Usec)
//
// Remove the NULs our fields seem to get padded out with.
//
au := bytes.Trim(arg.User[:], "\x00")
al := bytes.Trim(arg.Line[:], "\x00")
ah := bytes.Trim(arg.Host[:], "\x00")
if (len(ah) == 0) {
ah = []byte("local")
}
fmt.Fprintf(conn, "%s %s %s %s %d %d\n", host, au, al, ah, ts, tu)
}
}
conn.Close()
}
| 9383b7cf74cb63492fb05202b72fa620760eaadb | [
"Markdown",
"Python",
"Go"
] | 4 | Markdown | seantcaron/cwho | bbe85c20f6b390790bd0efdf3e4ce86992d2ef4f | cf90fa40caebd38a6616ca547bfd18a7e3e44817 |
refs/heads/master | <file_sep>// pages/index/panel/panel.js
Page({
data: {
list: []
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
try {
var detail = wx.getStorageSync('options');
this.setData({ list: detail });
} catch (e) {
}
},
onReady: function () {
// 页面渲染完成
},
onShow: function () {
// 页面显示
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
}
})
| edc99eadda428286b06006bf072319952af5e700 | [
"JavaScript"
] | 1 | JavaScript | tvChan/growth | 685b7f4bfc8f140b755b2849473c9cf26d0e7ee7 | 6a68c9e81c410a8356119fdadaff3e2c0712eb7b |
refs/heads/master | <repo_name>thisisaaronland/go-marc<file_sep>/Makefile
CWD=$(shell pwd)
GOPATH := $(CWD)
prep:
if test -d pkg; then rm -rf pkg; fi
self: prep
if test -d src/github.com/thisisaaronland/go-marc; then rm -rf src/github.com/thisisaaronland/go-marc; fi
mkdir -p src/github.com/thisisaaronland/go-marc/fields
cp -r assets src/github.com/thisisaaronland/go-marc/
cp -r fields src/github.com/thisisaaronland/go-marc/
cp -r http src/github.com/thisisaaronland/go-marc/
cp marc.go src/github.com/thisisaaronland/go-marc/
cp -r vendor/* src/
rmdeps:
if test -d src; then rm -rf src; fi
build: fmt bin
deps:
@GOPATH=$(GOPATH) go get -u "github.com/whosonfirst/go-sanitize"
@GOPATH=$(GOPATH) go get -u "github.com/whosonfirst/go-whosonfirst-bbox"
@GOPATH=$(GOPATH) go get -u "github.com/jteeuwen/go-bindata/"
@GOPATH=$(GOPATH) go get -u "github.com/elazarl/go-bindata-assetfs/"
@GOPATH=$(GOPATH) go get -u "github.com/whosonfirst/go-http-mapzenjs"
rm -rf src/github.com/jteeuwen/go-bindata/testdata
vendor-deps: rmdeps deps
if test ! -d vendor; then mkdir vendor; fi
cp -r src/* vendor/
find vendor -name '.git' -print -type d -exec rm -rf {} +
rm -rf src
assets: self
@GOPATH=$(GOPATH) go build -o bin/go-bindata ./vendor/github.com/jteeuwen/go-bindata/go-bindata/
rm -rf templates/*/*~
rm -rf assets
mkdir -p assets/html
@GOPATH=$(GOPATH) bin/go-bindata -pkg html -o assets/html/html.go templates/html
static: self
@GOPATH=$(GOPATH) go build -o bin/go-bindata ./vendor/github.com/jteeuwen/go-bindata/go-bindata/
@GOPATH=$(GOPATH) go build -o bin/go-bindata-assetfs vendor/github.com/elazarl/go-bindata-assetfs/go-bindata-assetfs/main.go
rm -f static/css/*~ static/javascript/*~
@PATH=$(PATH):$(CWD)/bin bin/go-bindata-assetfs -pkg http static/javascript static/css
if test -f http/static_fs.go; then rm http/static_fs.go; fi
mv bindata_assetfs.go http/static_fs.go
# please move this in to a go-http-leaflet package (20180113/thisisaaronland)
leaflet:
if test -d tmp; then rm -rf tmp; fi
mkdir tmp
curl -s -o tmp/leaflet.zip http://cdn.leafletjs.com/leaflet/v1.2.0/leaflet.zip
unzip -d tmp tmp/leaflet.zip
mv tmp/leaflet.js static/javascript/
mv tmp/leaflet-src*.js static/javascript/
mv tmp/leaflet*.css static/css/
mv tmp/images/*.png static/images/
rm -rf tmp
build:
@make assets
@make static
@make bin
debug:
@make build
bin/marc-034d -mapzen-api-key $(MAPZEN_APIKEY)
fmt:
go fmt cmd/*.go
go fmt fields/*.go
go fmt http/*.go
go fmt *.go
bin: rmdeps self
rm -rf bin/*
@GOPATH=$(GOPATH) go build -o bin/marc-034 cmd/marc-034.go
@GOPATH=$(GOPATH) go build -o bin/marc-034d cmd/marc-034d.go
docker-build:
@make build
docker build -t marc-034d .
docker-debug: docker-build
docker run -it -p 8080:8080 -e 'MAPZEN_APIKEY=$(MAPZEN_APIKEY)' marc-034d
<file_sep>/static/javascript/marc-034.js
/* marc_034.js */
window.addEventListener("load", function load(event){
var map;
if (L.Mapzen) {
var api_key = document.body.getAttribute("data-mapzen-api-key");
L.Mapzen.apiKey = api_key;
var map_opts = { tangramOptions: {
scene: L.Mapzen.BasemapStyles.Refill,
// scene: "/tangram/refill-style.zip"
}};
map = L.Mapzen.map('map', map_opts);
var sw = [ -55, -180 ];
var ne = [ 55, 180 ];
var bounds = [ sw, ne ];
map.fitBounds(bounds);
}
else {
var el = document.getElementById("map");
el.innerText = "Maps are disabled because mapzen.js is not present.";
}
var m = document.getElementById("marc-034");
m.value = "";
var s = document.getElementById("submit");
s.onclick = function(){
var m = document.getElementById("marc-034");
m = m.value;
m = m.trim();
if (m == ""){
return false;
}
var enc = encodeURIComponent(m);
var url = location.protocol + "//" + location.host + "/bbox?034=" + enc;
var raw = document.getElementById("raw");
raw.innerHTML = "";
var bboxes = document.getElementById("bboxes");
bboxes.innerHTML = "";
if (map){
var sw = [ -55, -180 ];
var ne = [ 55, 180 ];
var bounds = [ sw, ne ];
map.fitBounds(bounds);
}
var on_success = function(rsp){
var str = JSON.stringify(rsp, null, 2);
var pre = document.createElement("pre");
pre.appendChild(document.createTextNode(url));
pre.appendChild(document.createTextNode("\n\n"));
pre.appendChild(document.createTextNode(str));
var raw = document.getElementById("raw");
raw.appendChild(pre);
var bbox = rsp["bbox"];
var minx = bbox[0].toFixed(6);
var miny = bbox[1].toFixed(6);
var maxx = bbox[2].toFixed(6);
var maxy = bbox[3].toFixed(6);
var coords = {
"S, W, N, E": [ miny, minx, maxy, maxx ],
"W, S, E, N": [ minx, miny, maxx, maxy ],
"N, E, S, W": [ maxy, maxx, miny, minx ],
}
var ul = document.createElement("ul");
for (var label in coords) {
var bbox = coords[label];
var str_bbox = bbox.join(",");
var code = document.createElement("code");
code.appendChild(document.createTextNode(str_bbox));
var li = document.createElement("li");
li.appendChild(document.createTextNode(label + " "));
li.appendChild(code);
ul.appendChild(li);
}
var bboxes = document.getElementById("bboxes");
bboxes.appendChild(ul);
if (map){
var sw = [ miny, minx ];
var ne = [ maxy, maxx ];
var bounds = [ sw, ne ];
var opts = { padding: [50, 50] };
map.fitBounds(bounds, opts);
var layer = L.geoJSON(rsp);
layer.addTo(map);
}
};
var req = new XMLHttpRequest();
req.onload = function(){
try {
var data = JSON.parse(this.responseText);
}
catch (e){
console.log("ERROR", e);
return false;
}
on_success(data);
};
console.log("FETCH", url);
req.open("get", url, true);
req.send();
return false;
}
});
<file_sep>/README.md
# go-marc
Go package for working with MARC records.
## Important
Not all of MARC. Probably not ever. Just the `034` field so far.
## Tools
### marc-034
Convert a MARC 034 string in to a (S, W, N, E) bounding box.
```
./bin/marc-034 -h
Usage of ./bin/marc-034:
-f string
A valid MARC 034 string (default "1#$aa$b22000000$dW1800000$eE1800000$fN0840000$gS0700000")
```
Currently this only supports `hdddmmss (hemisphere-degrees-minutes-seconds)` and `dddmmss (degrees-minutes-seconds)` notation. For example:
```
./bin/marc-034
2017/02/13 22:23:38 1#$aa$b22000000$dW1800000$eE1800000$fN0840000$gS0700000 <-- input (MARC 034)
2017/02/13 22:23:38 -70.000000, -180.000000 84.000000, 180.000000 <-- output (decimal WSG84)
```
### marc-034d
A web server for converting MARC 034 strings in to bounding boxes (formatted as GeoJSON)
```
./bin/marc-034d -h
Usage of ./bin/marc-034d:
-host string
The hostname to listen for requests on (default "localhost")
-httptest.serve string
if non-empty, httptest.NewServer serves on this address and blocks
-mapzen-api-key string
A valid Mapzen API key (default "mapzen-xxxxxx")
-port int
The port number to listen for requests on (default 8080)
```
For example:
```
$> ./bin/marc-034d -mapzen-api-key mapzen-1a2b3c
2018/01/12 09:12:44 listening on localhost:8080
```
The `marc-034d` server exposes the following endpoints:
#### / (or "root")
The `/` (or default) endpoint will display a handy web interface for converting MARC 034 records in to bounding boxes. For example, here's what it looks like querying for `1#$aa$b80000$dW0825500$eW0822000$fN0273000$gN0265000`:

#### /bbox
The `/bbox` endpoint will return a bounding box for a MARC 034 field as GeoJSON.
```
$> curl -s 'http://localhost:8080/bbox?034=1%23%24aa$b22000000%24dW1800000%24eE1800000%24fN0840000%24gS0700000' | python -mjson.tool
{
"bbox": [
-180,
-70,
180,
84
],
"geometry": {
"coordinates": [
[
[
-180,
-70
],
[
-180,
84
],
[
180,
84
],
[
180,
-70
],
[
-180,
-70
]
]
],
"type": "Polygon"
},
"properties": {
"marc:034": "1#$aa$b22000000$dW1800000$eE1800000$fN0840000$gS0700000"
},
"type": "Feature"
}
```
_Note the way the `034` parameter is URL-encoded._
## Docker
[Yes](Docker), for `marc-034d` at least.
```
docker build -t marc-034d .
docker run -it -p 8080:8080 -e 'MAPZEN_APIKEY=$(MAPZEN_APIKEY)' marc-034d
```
## Caveats
* There are still problems running this on `localhost` (for example from the Dockerfile on your laptop) under Firefox. I haven't had time to figure out if this is a paranoid security feature in Firefox or if I am just "doing it wrong".
* Mapzen, [iknowrite](https://mapzen.com/blog/shutdown/)? Mapzen are shutting down as of February, 2018 and this package use Mapzen tiles (and the `mapzen.js` library) for displaying maps. The good news about the shutdown is that requiring an API key will be a moot point. The bad news is that it's not clear, as of this writing, where the vector tiles are going to come from. Either way this package uses the [go-http-mapzenjs](https://github.com/whosonfirst/go-http-mapzenjs) package to bundle all the `mapzen.js` assets and hide all the details from you so if there is a need to replace the Mapzen stuff with [ some other mapping provider ] it shouldn't be a big deal. The details are [over here](https://github.com/aaronland/go-marc/blob/master/cmd/marc-034d.go#L28-L43) if you're curious. For the time being you can still [sign up for a Mapzen API key](https://mapzen.com/developers/).
## See also
* https://www.loc.gov/marc/bibliographic/bd034.html
* https://github.com/whosonfirst/go-http-mapzenjs
* https://mapzen.com/developers/
<file_sep>/Dockerfile
# https://blog.docker.com/2016/09/docker-golang/
# https://blog.golang.org/docker
# docker build -t 034d .
# docker run -it -p 8080:8080 034d
FROM golang:alpine AS build-env
RUN apk add --update alpine-sdk
ADD . /go-marc
RUN cd /go-marc; make bin
FROM alpine
COPY --from=build-env /go-marc/bin/marc-034d /marc-034d
EXPOSE 8080
CMD /marc-034d -host 0.0.0.0 -mapzen-api-key ${MAPZEN_APIKEY}
<file_sep>/http/www.go
package http
import (
"github.com/thisisaaronland/go-marc/assets/html"
"html/template"
gohttp "net/http"
)
type HTMLVars struct {
}
func WWWHandler() (gohttp.Handler, error) {
tpl, err := html.Asset("templates/html/marc-034.html")
if err != nil {
return nil, err
}
t := template.New("034")
t, err = t.Parse(string(tpl))
if err != nil {
return nil, err
}
fn := func(rsp gohttp.ResponseWriter, req *gohttp.Request) {
vars := HTMLVars{}
err := t.Execute(rsp, vars)
if err != nil {
gohttp.Error(rsp, err.Error(), gohttp.StatusInternalServerError)
return
}
}
h := gohttp.HandlerFunc(fn)
return h, nil
}
<file_sep>/http/bbox.go
package http
import (
"encoding/json"
"github.com/thisisaaronland/go-marc/fields"
"github.com/whosonfirst/go-sanitize"
_ "log"
gohttp "net/http"
"strings"
)
type GeoJSONCoordinate []float64
type GeoJSONRing []GeoJSONCoordinate
type GeoJSONPolygon []GeoJSONRing
type GeoJSONGeometry struct {
Type string `json:"type"`
Coordinates GeoJSONPolygon `json:"coordinates"`
}
type GeoJSONProperties map[string]string
type GeoJSONBoundingBox []float64
type GeoJSONFeature struct {
Type string `json:"type"`
Geometry GeoJSONGeometry `json:"geometry"`
Properties GeoJSONProperties `json:"properties"`
BoundingBox GeoJSONBoundingBox `json:"bbox"`
}
type BboxResponse struct {
MinX float64 `json:"min_x"`
MinY float64 `json:"min_y"`
MaxX float64 `json:"max_x"`
MaxY float64 `json:"max_y"`
}
func BboxHandler() (gohttp.Handler, error) {
fn := func(rsp gohttp.ResponseWriter, req *gohttp.Request) {
query := req.URL.Query()
marc_raw := query.Get("034")
marc_raw = strings.Trim(marc_raw, " ")
if marc_raw == "" {
gohttp.Error(rsp, "Missing or invalid bounding box", gohttp.StatusBadRequest)
return
}
opts := sanitize.DefaultOptions()
marc_clean, err := sanitize.SanitizeString(marc_raw, opts)
if err != nil {
gohttp.Error(rsp, err.Error(), gohttp.StatusBadRequest)
return
}
// log.Println("RAW", marc_raw)
// log.Println("CLEAN", marc_clean)
bounds, err := fields.Parse034(marc_clean)
if err != nil {
gohttp.Error(rsp, err.Error(), gohttp.StatusBadRequest)
return
}
bbox, err := bounds.BoundingBox()
if err != nil {
gohttp.Error(rsp, err.Error(), gohttp.StatusInternalServerError)
return
}
min_x := bbox.MinX()
min_y := bbox.MinY()
max_x := bbox.MaxX()
max_y := bbox.MaxY()
sw := GeoJSONCoordinate{min_x, min_y}
nw := GeoJSONCoordinate{min_x, max_y}
ne := GeoJSONCoordinate{max_x, max_y}
se := GeoJSONCoordinate{max_x, min_y}
geojson_ring := GeoJSONRing{sw, nw, ne, se, sw}
geojson_polygon := GeoJSONPolygon{geojson_ring}
geojson_geometry := GeoJSONGeometry{
Type: "Polygon",
Coordinates: geojson_polygon,
}
geojson_bbox := GeoJSONBoundingBox{min_x, min_y, max_x, max_y}
geojson_properties := GeoJSONProperties{
"marc:034": marc_clean,
}
geojson_feature := GeoJSONFeature{
Type: "Feature",
Geometry: geojson_geometry,
Properties: geojson_properties,
BoundingBox: geojson_bbox,
}
enc, err := json.Marshal(geojson_feature)
if err != nil {
gohttp.Error(rsp, err.Error(), gohttp.StatusInternalServerError)
return
}
rsp.Header().Set("Content-Type", "application/json")
rsp.Header().Set("Access-Control-Allow-Origin", "*")
rsp.Write(enc)
}
h := gohttp.HandlerFunc(fn)
return h, nil
}
<file_sep>/cmd/marc-034d.go
package main
import (
"flag"
"fmt"
"github.com/thisisaaronland/go-marc/http"
"github.com/whosonfirst/go-http-mapzenjs"
"log"
gohttp "net/http"
"os"
)
func main() {
var host = flag.String("host", "localhost", "The hostname to listen for requests on")
var port = flag.Int("port", 8080, "The port number to listen for requests on")
var api_key = flag.String("mapzen-api-key", "mapzen-xxxxxx", "A valid Mapzen API key")
flag.Parse()
www_handler, err := http.WWWHandler()
if err != nil {
log.Fatal(err)
}
opts := mapzenjs.DefaultMapzenJSOptions()
opts.APIKey = *api_key
www_mapzenjs_handler, err := mapzenjs.MapzenJSHandler(www_handler, opts)
if err != nil {
log.Fatal(err)
}
static_handler, err := http.StaticHandler()
if err != nil {
log.Fatal(err)
}
mapzenjs_assets_handler, err := mapzenjs.MapzenJSAssetsHandler()
if err != nil {
log.Fatal(err)
}
bbox_handler, err := http.BboxHandler()
if err != nil {
log.Fatal(err)
}
ping_handler, err := http.PingHandler()
if err != nil {
log.Fatal(err)
}
mux := gohttp.NewServeMux()
mux.Handle("/", www_mapzenjs_handler)
mux.Handle("/javascript/", static_handler)
mux.Handle("/css/", static_handler)
mux.Handle("/javascript/mapzen.min.js", mapzenjs_assets_handler)
mux.Handle("/javascript/tangram.min.js", mapzenjs_assets_handler)
mux.Handle("/javascript/mapzen.js", mapzenjs_assets_handler)
mux.Handle("/javascript/tangram.js", mapzenjs_assets_handler)
mux.Handle("/css/mapzen.js.css", mapzenjs_assets_handler)
mux.Handle("/tangram/refill-style.zip", mapzenjs_assets_handler)
mux.Handle("/bbox", bbox_handler)
mux.Handle("/ping", ping_handler)
address := fmt.Sprintf("%s:%d", *host, *port)
log.Printf("listening on %s\n", address)
err = gohttp.ListenAndServe(address, mux)
if err != nil {
log.Fatal(err)
}
os.Exit(0)
}
| b85e21b196c32c23bc4e45654191fc4be5b6165f | [
"JavaScript",
"Markdown",
"Makefile",
"Go",
"Dockerfile"
] | 7 | Makefile | thisisaaronland/go-marc | 88cbeb264263087dd7fda7fbf98b1314359d71cd | 2a783f0def7721725c03dd580e714606018c9533 |
refs/heads/develop | <repo_name>paulambanks/JS-Dev-Env-Docker-starter-kit<file_sep>/src/index.test.js
// An example of a passing test. Write your tests here.
import { expect } from 'chai';
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
describe('Our first test', () => {
it('should pass', () => {
expect(true).to.equal(true);
});
});
describe('index.html', () => { // eslint-disable-line
it('should say hello', (done) => { // eslint-disable-line
const options = {}
JSDOM.fromFile('./src/index.html', options).then(dom => {
const h1 = dom.window.document.getElementsByTagName('h1')[0]
expect(h1.innerHTML).to.equal('Hello World!')
done()
}).catch(done)
})
})
<file_sep>/README.md
# JavaScript Template [](https://travis-ci.org/paulambanks/JS-Dev-Env-Docker-starter-kit)
NodeJs development with Docker (Webpack 4 + ES6 + Babel 7)
## Layout
* Dockerfile (Describes how to build the Docker image)
* docker-compose.yml (Launches the node webserver on port 3000)
* src (JS application sources go here)
* src/index.html (Prints "Hello World!")
* Express.js (Web application framework for Node.js)
* ES6+ based JavaScript.
* Babel 7 and babel-loader (transpiling the ES6+ source code into ES5 style code; babel-loader has been used with webpack for compiling/transpiling purpose)
* Webpack 4 (for executing babel transpiler and bundling JavaScript files into a single file)
* Travis for CI
### Quick Commands
Starts the server in the foreground.
```bash
docker-compose up
```
Start the server in the background.
```bash
docker-compose up -d
```
Stop the server.
```bash
docker-compose down
```
Stop the server, and remove volumes, etc.
```bash
docker-compose down -f
```
Update / rebuild the docker image.
```bash
docker-compose build
```
<file_sep>/Dockerfile
FROM node:8.15.0-alpine as build
# Set the work directory
RUN mkdir /app
WORKDIR /app
# Add package.json and install *before* adding application files
COPY package*.json /app/
RUN npm install
#Expose the port
ENV SERVER_PORT 3000
EXPOSE 3000
# Add commands
CMD npm start
| 3772ab67730d89e0fb65c7101a196b03c3b44a75 | [
"JavaScript",
"Dockerfile",
"Markdown"
] | 3 | JavaScript | paulambanks/JS-Dev-Env-Docker-starter-kit | da1373ad4c45ceceff7908ddcfb122636271c5e1 | b17ed7794bc27d6f72dee9682fed50f8cfbd9292 |
refs/heads/master | <file_sep>/**
*
*/
package mamin1;
import mamin1.Student;
/**
* @author 敏儿
*@package_name:mamin1
*@file_name:Student.java
*@date-time:2017年10月15日下午4:00:07
*@location:https://github.com/1508010207/yinhang.git
*/
public class Student {//Student类
private String name;//姓名
private int age;//年龄
private String education ;//学位
public Student(String name, int age, String education) {//构造方法
super();
this.name = name;
this.age = age;
this.education = education;
}
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEducation() {
return education;
}
public void setDegree(String education) {
this.education = education;
}
public void show(){
System.out.println("姓名:" + this.getName() + ". 年龄:" + this.getAge() + ". 学位:" + this.getEducation() );
}
}
class Undergraduate extends Student{//本科生类
private String specialty;
public String getSpecialty() {
return specialty;
}
public void setSpecialty(String specialty) {
this.specialty = specialty;
}
public Undergraduate(String name, int age, String education, String specialty) {
super(name, age, education);
this.specialty = specialty;
}
public Undergraduate(String name, int age, String education) {
super(name, age, education);
}
public void show(){
System.out.println("姓名:" + this.getName() + ". 年龄:" + this.getAge() + ". 学位:" + this.getEducation() + ". 专业:" + this.getSpecialty());
}
}
class Graduate extends Student{//研究生类
private String direction;//研究方向
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public Graduate(String name, int age, String Education, String direction) {
super(name, age, Education);
this.direction = direction;
}
public Graduate(String name, int age, String Education) {
super(name, age, Education);
}
public void show(){
System.out.println("姓名:" + this.getName() + ". 年龄:" + this.getAge() + ". 学位:" + this.getEducation() + ". 研究方向:" + this.getDirection());
}
/**
* @return
*/
public String getEducation() {
// TODO Auto-generated method stub
return null;
}
}
| df175de565c2c4ad381c0edd3165b3da7134ee17 | [
"Java"
] | 1 | Java | 1508010207/yinhang | beb9fc5a3a7cca6ef809e82b101466ecd10bbffe | cd3a8ed454335b3aae02c3e97877a088280969cc |
refs/heads/master | <file_sep># # -*- coding: UTF-8 -*-
# from flask import Flask,request
# import pymysql
# import os
# import json
# from flask_cors import *
# os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
# from datetime import date, datetime
#
# app = Flask(__name__)
#
# class ComplexEncoder(json.JSONEncoder):
# def default(self, obj):
# if isinstance(obj, datetime):
# return obj.strftime('%Y-%m-%d %H:%M:%S')
# elif isinstance(obj, date):
# return obj.strftime('%Y-%m-%d')
# else:
# return json.JSONEncoder.default(self, obj)
#
# @app.route('/users', methods=["GET", "POST"])
# def users():
# # 与数据库建立连接
# connect_obj = pymysql.connect(host='192.168.127.12', user='root', password='<PASSWORD>', database='student', port=3307)
# cur = connect_obj.cursor() # 获取游标
# sql = 'select * from student'
# cur.execute(sql)
# data = cur.fetchall()
# # print(data)
# text = {}
# para = []
# for i in data:
# text = {'stu_account':i[0],'stu_password':i[1],'stu_name':i[2],'stu_sex':i[3],'stu_age':i[4],'stu_phone':i[5],'stu_weiXinName':i[6],'stu_avatar':i[7],'stu_weiXinNum':i[8],'stu_courseNum':i[9],'stu_cardDay':i[10],'stu_interest':i[11],'stu_position':i[12]}
# # print(text)
# para.append(text)
# return json.dumps(para, ensure_ascii=False)
#
# @app.route('/record', methods=["GET", "POST"])
# def record():
# # 与数据库建立连接
# connect_obj = pymysql.connect(host='192.168.127.12', user='root', password='<PASSWORD>', database='student', port=3307)
# cur = connect_obj.cursor() # 获取游标
# sql = 'select * from record'
# cur.execute(sql)
# data = cur.fetchall()
# # print(data)
# text1 = {}
# para = []
# for i in data:
# text1 = {'record_id':i[0],'stu_account':i[1],'record_time':i[2],'record_content':i[3]}
# # print(text)
# para.append(text1)
# return json.dumps(para, ensure_ascii=False,cls=ComplexEncoder)
#
# @app.route('/home', methods=["GET", "POST"])
# def home():
# # 与数据库建立连接
# connect_obj = pymysql.connect(host='192.168.127.12', user='root', password='<PASSWORD>', database='student', port=3307)
# cur = connect_obj.cursor() # 获取游标
# sql = 'select * from course'
# cur.execute(sql)
# data = cur.fetchall()
# # print(data)
# text2 = {}
# para = []
# for i in data:
# text2 = {'course_id':i[0],'course_name':i[1],'course_notice':i[2],'course_vf':i[3],'course_studyNum':i[4],'course_zanNum':i[5]}
# # print(text)
# para.append(text2)
# return json.dumps(para, ensure_ascii=False)
#
# @app.route('/course', methods=["GET", "POST"])
# def course():
# # qd_stu_account = request.values.get("stu_account")
# # 与数据库建立连接
# connect_obj = pymysql.connect(host='192.168.127.12', user='root', password='<PASSWORD>', database='student', port=3307)
# cur = connect_obj.cursor() # 获取游标
# sql = "select * from stu_course"
# cur.execute(sql)
# data = cur.fetchall()
# # print(data)
# text3 = {}
# para = []
# for i in data:
# text3 = {'stu_course_id':i[0],'stu_account':i[1],'course_id':i[2]}
# # print(text)
# para.append(text3)
# return json.dumps(para, ensure_ascii=False)
#
# if __name__ == '__main__':
# app.run()
# 与数据库建立连接
# connect_obj = pymysql.connect(host='192.168.127.12',user='root',password='<PASSWORD>',database='student',port=3307)
# cur = connect_obj.cursor() # 获取游标
# 添加数据
# sql = "insert into students VALUES(%s,%s,%s,%s,%s)"
# count = cur.execute(sql,[0,'马冬梅',20,'男','880820']) # 执行mysql语句
# connect_obj.commit() # 数据修改时,一定要有这句话
# print('成功插入',count,'条数据')
# 删除数据
# sql = "DELETE FROM students WHERE id = 4 "
# count = cur.execute(sql) # 执行mysql语句
# connect_obj.commit() # 数据修改时,一定要有这句话
# print('成功删除',count,'条数据')
# 更新数据
# sql = "UPDATE students SET name = '李四' WHERE id = 3 "
# count = cur.execute(sql) # 执行mysql语句
# connect_obj.commit() # 数据修改时,一定要有这句话
# print('成功修改',count,'条数据')
#
# sql = 'select * from students'
# count = cur.execute(sql) # 执行mysql语句
# print('共查出',count,'条数据')
# ret = cur.fetchall() # 获取结果中的所有行
#
#
# # cur.fetchmany(5) # 获取结果中的下面5行
# # cur.fetchone() # 获取结果中的下一行
#
# for i in ret:
# print(i)
#
# # 关闭连接
# cur.close()
# connect_obj.close()
from math import sin,radians,cos,asin,sqrt
def haversine(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) #radians 角度转弧度
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a)) # 反正弦
r = 6371
haversine(113.0, 10.0, 114.0, 12.0)
print(c * r)
# return c * r
<file_sep># -*- coding: UTF-8 -*-
from flask import Flask,render_template,redirect,url_for,flash,session,jsonify, request, g, abort
from flask_script import Manager,Server
from flask_wtf import Form
from flask_bootstrap import Bootstrap
from wtforms import StringField,PasswordField,SubmitField,validators,IntegerField,DateTimeField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_
import json
import pymysql
import random
from datetime import date, datetime
from decimal import Decimal
from flask_cors import *
app = Flask(__name__)
manager = Manager(app)
manager.add_command("runserver", Server(use_debugger=True))
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = "123"
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://root:123456@192.168.127.12:3307/student'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
CORS(app, supports_credentials = True) # 解决跨域问题
class UsersRecommend:
def __init__(self, uuid):
self.uuid = uuid
self.my_db = pymysql.connect(host='192.168.127.12', user='root', password='<PASSWORD>', database='student', port=3307)
self.res_data = list(self.my_db.db_ais['friends'].find({'status': {'$in': [2, -1]}}, {'friend_id': 1, 'user_id': 1})) # 查询所有用户好友关系表
self.direct_f = self.get_friends(uuid) # 用户好友
if len(self.direct_f) > 50: # 好友过多时取随机50个
self.direct_f = random.sample(self.direct_f, 50)
def recommend_f(self, pageno, pagesize):
if len(self.direct_f) > 0:
indirect_f = [{'indirect_id': x, 'relations': []} for x in self.direct_f] # 间接好友初始化
for x in self.res_data: # 遍历res_data, 统计间接好友的好友列表
if x['userId'] in self.direct_f and x['toUserId'] not in self.direct_f and x['toUserId'] != self.uuid:
indirect_f[self.direct_f.index(x['userId'])]['relations'].append(x['toUserId'])
recommends, recommends_idx = [], []
for x in indirect_f:
if len(x['relations']) > 50: # 跳过直接好友中好友过多的
continue
for y in x['relations']:
if y not in recommends_idx:
recommends_idx.append(y)
recommends.append({'uid': y, 'num': 0, 'score': 0})
recommends[recommends_idx.index(y)]['score'] += 1 # 可惩罚‘过热’用户
recommends[recommends_idx.index(y)]['num'] += 1
recommends.sort(key=lambda x: x['score'], reverse=True) # 按共同好友数排序
return [{'uid': x['uid'], 'common_friends': x['num']} for x in recommends][(pageno - 1) * pagesize:pageno * pagesize] # 分页
else: # 用户尚未添加一个好友
return []
# 获取指定用户的好友列表
def get_friends(self, usr_id):
return [x['toUserId'] for x in self.res_data if x['userId'] == usr_id]
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Decimal):
return float(o)
super(DecimalEncoder, self).default(o)
def default1(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
class Interface:
_fields = []
_rela_fields = []
def to_dict(self):
result = {key: self.__getattribute__(key) for key in self._fields}
for rf in self._rela_fields:
result[rf] = []
for item in self.__getattribute__(rf):
result[rf].append(item.to_dict())
# json.dumps(result[rf], ensure_ascii=False, cls=ComplexEncoder)
# result[rf].json(item.to_dict(),cls=ComplexEncoder)
return result
class Student(db.Model, Interface):
__tablename__ = 'student'
_fields = ['stu_account','stu_password','stu_name','stu_sex','stu_age','stu_phone','stu_weiXinName','stu_avatar','stu_weiXinNum','stu_courseNum','stu_cardDay','stu_interest','stu_position','longitude','latitude']
_rela_fields = ['Record','Society']
stu_account = db.Column(db.String,primary_key=True,nullable=False)
stu_password = db.Column(db.String,nullable=False)
stu_name = db.Column(db.String)
stu_sex = db.Column(db.Enum('男','女'),default='男')
stu_age = db.Column(db.Integer,default=18)
stu_phone = db.Column(db.String)
stu_weiXinName = db.Column(db.String)
stu_avatar = db.Column(db.String)
stu_weiXinNum = db.Column(db.String)
stu_courseNum = db.Column(db.Integer,default=0)
stu_cardDay = db.Column(db.Integer,default=0)
stu_interest = db.Column(db.String)
stu_position = db.Column(db.String,default='北京')
longitude = db.Column(db.DECIMAL(10,7))
latitude = db.Column(db.DECIMAL(10, 7))
Record = db.relationship('Record', backref='student', lazy='dynamic')
Society = db.relationship('Society', backref='student', lazy='dynamic')
class Course(db.Model, Interface):
__tablename__ = 'course'
_fields = ['course_id','course_name','course_notice','course_vf','course_studyNum','course_zanNum']
_rela_fields = ['Stu_course']
course_id = db.Column(db.Integer,primary_key=True,nullable=False)
course_name = db.Column(db.String,nullable=False)
course_notice = db.Column(db.String,nullable=False)
course_vf = db.Column(db.String)
course_studyNum = db.Column(db.Integer)
course_zanNum = db.Column(db.Integer)
Stu_course = db.relationship('Stu_course', backref='course',lazy='dynamic')
class Record(db.Model, Interface):
__tablename__ = 'record'
_fields = ['record_id','stu_account','record_time','record_content']
record_id = db.Column(db.Integer, primary_key=True, autoincrement=True,nullable=False)
stu_account = db.Column(db.String,db.ForeignKey(Student.stu_account),nullable=False)
record_time = db.Column(db.DateTime,nullable=False)
record_content = db.Column(db.String,nullable=False)
class Card(db.Model, Interface):
__tablename__ = 'card'
_fields = ['id','stu_account','card_time']
id = db.Column(db.Integer, primary_key=True, autoincrement=True,nullable=False)
stu_account = db.Column(db.String,db.ForeignKey(Student.stu_account),nullable=False)
card_time = db.Column(db.Date,nullable=False)
class Stu_course(db.Model, Interface):
__tablename__ = 'stu_course'
_fields = ['stu_course_id','stu_account','course_id']
stu_course_id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
stu_account = db.Column(db.String, db.ForeignKey(Student.stu_account), nullable=False)
course_id = db.Column(db.Integer, db.ForeignKey(Course.course_id),nullable=False)
class Society(db.Model, Interface):
__tablename__ = 'society'
_fields = ['society_id','user_id','friend_id','society_content','society_time']
# _rela_fields = ['Student']
society_id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
user_id = db.Column(db.String, nullable=False)
friend_id = db.Column(db.String, db.ForeignKey(Student.stu_account),nullable=False)
society_content = db.Column(db.String)
society_time = db.Column(db.Date)
# Student = db.relationship('Student', backref='society', lazy='dynamic')
class Chat(db.Model, Interface):
__tablename__ = 'chat'
_fields = ['chat_id','chat_type','user_id','friend_id','chat_content','chat_time']
# _rela_fields = ['Student']
chat_id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
chat_type = db.Column(db.String, nullable=False)
user_id = db.Column(db.String, nullable=False)
friend_id = db.Column(db.String, nullable=False)
chat_content = db.Column(db.String)
chat_time = db.Column(db.DateTime)
# Student = db.relationship('Student', backref='society', lazy='dynamic')
# 后台管理
# class LoginForm(Form):
# administrator_account = StringField("用户名: ",[validators.DataRequired(message="请输入有效的用户名"),])
# administrator_password = PasswordField("密码: ",validators=[validators.DataRequired(),validators.Length(min=6,message="密码大于等于6位")])
# submit = SubmitField("登录")
class Administrator(db.Model):
__tablename__='administrator'
administrator_account = db.Column(db.String,primary_key=True)
administrator_password = db.Column(db.String)
# @app.route('/', methods=['GET','POST']) # 跳转到管理员登录页面
# def index():
# return redirect(url_for('adminLogin'))
# @app.route('/adminLogin',methods=['GET','POST']) # 管理员登录页面
# def adminLogin():
# myForm = LoginForm()
# if myForm.validate_on_submit():
# uname = myForm.administrator_account.data
# pword = myForm.administrator_password.data
# if len(Administrator.query.filter(and_(Administrator.administrator_account == uname,Administrator.administrator_password==pword)).all())>0:
# session['is_login'] = True
# return redirect(url_for('adminHome',u_name=uname))
# else:
# flash("用户名或密码不正确")
# return redirect(url_for('adminLogin'))
# return render_template('adminlogin.html',form=myForm)
# @app.route('/exitlogin') # 退出管理员登录页面
# def exit_login():
# session['is_login']=False
# return redirect(url_for('adminLogin'))
# @app.route('/<string:u_name>')# 管理员首页面
# def adminHome(u_name):
# if session.get('is_login'):
# administrator = Administrator.query.filter(Administrator.administrator_account==u_name).first()
# return render_template("adminhome.html",administrator=administrator)
# else:
# return redirect(url_for('adminLogin'))
@app.route('/adminLogin', methods=['GET','POST']) # 管理员登录
def adminLogin():
administrator_account = request.json.get('administrator_account')
administrator_password = request.json.get('administrator_password')
if administrator_account and administrator_password:
administrator = Administrator.query.filter(Administrator.administrator_account == administrator_account, Administrator.administrator_password == <PASSWORD>_password).first()
if administrator:
response = jsonify({'status': '1','administrator_account':administrator_account ,'role': '0'})
# return ("1")
return response
response = jsonify({'status': '0'})
# return ("0")
return response
@app.route('/stuAdmin', methods=['GET','POST']) # 学员管理
def stuAdmin():
stuAdmins = Student.query.all()
return jsonify([stuAdmin.to_dict() for stuAdmin in stuAdmins])
@app.route('/courseAdmin', methods=['GET','POST']) # 课程管理 #学员-课程接口
def courseAdmin():
courses = Course.query.all()
return jsonify([course.to_dict() for course in courses])
@app.route('/cardAdmin', methods=['GET','POST']) # 打卡管理
def cardAdmin():
records = Student.query.join(Record, Record.stu_account == Student.stu_account).filter(Record.stu_account == Student.stu_account).all()
return jsonify([record.to_dict() for record in records])
@app.route('/addCourse', methods=['GET','POST']) # 管理员添加课程
def addCourse():
course_id = request.json.get('course_id', None)
course_name = request.json.get('course_name', None)
course_notice = request.json.get('course_notice', None)
course_vf = request.json.get('course_vf', None)
new_course = Course (course_id=course_id, course_name=course_name, course_notice=course_notice, course_vf=course_vf)
db.session.add(new_course)
db.session.commit()
response = jsonify({'status': '1'})
response.status_code = 200
return response
@app.route('/deleteCourse', methods=['GET','POST']) # 管理员删除课程
def deleteCourse():
course_id = request.json.get('course_id', None)
deletecourse = Course.query.filter(Course.course_id == course_id).first()
db.session.delete(deletecourse)
db.session.commit()
response = jsonify({'status': '1'})
response.status_code = 200
return response
#前端
@app.route('/login', methods=['GET','POST']) # 登录
def login():
stu_account = request.json.get('stu_account')
stu_password = request.json.get('stu_password')
if stu_account and stu_password:
student = Student.query.filter(Student.stu_account == stu_account, Student.stu_password == <PASSWORD>password).first()
if student:
return ("1")
# return jsonify(student.to_dict())
return ("0")
@app.route('/registered', methods=['GET','POST']) # 注册时判断用户是否存在
def registered():
stu_account = request.json.get('stu_account')
if len(Student.query.filter(Student.stu_account == stu_account).all()) > 0:
return ("1")
return ("0")
@app.route('/addStudent', methods=['GET','POST']) # 存入注册用户
def addStudent():
stu_account = request.json.get('stu_account')
stu_password = request.json.get('stu_password')
new_student = Student(stu_account=stu_account, stu_password=stu_password)
db.session.add(new_student)
db.session.commit()
return ("1")
# response = jsonify({'status': '1'})
# response.status_code = 200
# return response
@app.route('/updateStudent', methods=['GET','POST']) # 存入注册用户个人信息
def updateStudent():
stu_account = request.json.get('stu_account')
stu_name = request.json.get('stu_name')
stu_sex = request.json.get('stu_sex')
stu_age = request.json.get('stu_age')
stu_phone = request.json.get('stu_phone')
stu_position = request.json.get('stu_position')
stu_interest = request.json.get('stu_interest')
updateStu = Student.query.filter(Student.stu_account == stu_account).first()
updateStu.stu_name = stu_name
updateStu.stu_sex = stu_sex
updateStu.stu_age = stu_age
updateStu.stu_phone = stu_phone
updateStu.stu_position = stu_position
updateStu.stu_interest = stu_interest
db.session.commit()
return ("1")
@app.route('/updatePass', methods=['GET','POST']) # 重置密码
def updatePass():
stu_account = request.json.get('stu_account')
stu_password = request.json.get('stu_password')
updatePass = Student.query.filter(Student.stu_account == stu_account).first()
updatePass.stu_password = <PASSWORD>
db.session.commit()
return ("1")
@app.route('/updatePosition', methods=['GET','POST']) # 更新位置信息(经纬度)
def updatePosition():
stu_account = request.json.get('stu_account')
longitude = request.json.get('longitude')
latitude = request.json.get('latitude')
updatePos = Student.query.filter(Student.stu_account == stu_account).first()
updatePos.longitude = longitude
updatePos.latitude = latitude
db.session.commit()
return ("1")
@app.route('/home', methods=['GET','POST']) # 首页 限制课程数 13条
def home():
# courses = Course.query.limit(13)
courses = Course.query.all()
# courses = list(filter(lambda x: x.deleted == 0, courses))
return jsonify([course.to_dict() for course in courses])
@app.route('/record', methods=['GET','POST']) # 打卡记录
def record():
# records = Record.query.order_by(Record.record_time.desc()).all()
# records = Record.query.limit(20)
# courses = list(filter(lambda x: x.deleted == 0, courses))
records = Student.query.join(Record, Record.stu_account == Student.stu_account).filter(Record.stu_account == Student.stu_account).order_by(-Record.record_time).all()
return jsonify([record.to_dict() for record in records])
# return json.dumps([record.to_dict() for record in records], ensure_ascii=False,cls=ComplexEncoder)
@app.route('/addRecord', methods=['GET','POST']) # 发布打卡记录
def addRecord():
stu_account = request.json.get('stu_account', None)
record_time = request.json.get('record_time', None)
record_content = request.json.get('record_content', None)
new_record = Record(stu_account=stu_account, record_time=record_time, record_content=record_content)
db.session.add(new_record)
db.session.commit()
response = jsonify({'status': 'success'})
response.status_code = 200
return response
@app.route('/sort', methods=['GET','POST']) # 打卡排行
def sort():
sorts = Student.query.order_by(-Student.stu_cardDay).all()
return jsonify([sort.to_dict() for sort in sorts])
@app.route('/cardtime', methods=['GET','POST']) # 已签到的打卡日期
def cardtime():
stu_account = request.json.get('stu_account')
cardtimes = Card.query.filter(Card.stu_account == stu_account).all()
return jsonify([cardtime.to_dict() for cardtime in cardtimes])
@app.route('/addcardtime', methods=['GET','POST']) # 添加学员打卡日期
def addcardtime():
stu_account = request.json.get('stu_account')
card_time = request.json.get('card_time')
new_cardtime = Card(stu_account=stu_account, card_time=card_time)
db.session.add(new_cardtime)
db.session.commit()
return ("1")
@app.route('/updatecardDay', methods=['GET','POST']) # 更新打卡天数
def updatecardDay():
stu_account = request.json.get('stu_account')
updatecardDay = Student.query.filter(Student.stu_account == stu_account).first()
updatecardDay.stu_cardDay = updatecardDay.stu_cardDay + 1
db.session.commit()
return ("1")
@app.route('/mycourse', methods=['GET','POST']) # 我的课程、课程通知
def mycourse():
stu_account = request.json.get('stu_account')
mycourses = Course.query.join(Stu_course, Stu_course.course_id == Course.course_id).filter(Stu_course.stu_account == stu_account).all()
return jsonify([mycourse.to_dict() for mycourse in mycourses])
@app.route('/addstu_course', methods=['GET','POST']) # 学员自己添加学习课程到我的课程列表,更新课程列表里的学习人数,我的课程数
def addstu_course():
stu_account = request.json.get('stu_account')
course_id = request.json.get('course_id')
new_stu_course = Stu_course(stu_account=stu_account, course_id=course_id)
db.session.add(new_stu_course)
updateNum = Course.query.filter(Course.course_id == course_id).first()
updateNum.course_studyNum = updateNum.course_studyNum + 1
updateCourseNum = Student.query.filter(Student.stu_account == stu_account).first()
updateCourseNum.stu_courseNum = updateCourseNum.stu_courseNum + 1
db.session.commit()
return ("1")
@app.route('/friendList', methods=['GET','POST']) # 好友列表
def friendList():
user_id = request.json.get('stu_account')
# friendLists = Society.query.join(Student, Student.stu_account == user_id).filter(Student.stu_account == Society.friend_id).all()
friendLists = Student.query.join(Society, Society.friend_id == Student.stu_account).filter(Society.user_id == user_id and Society.friend_id == Student.stu_account).all()
return jsonify([friendList.to_dict() for friendList in friendLists])
@app.route('/firstrecommend', methods=['GET','POST']) # 获取好友列表
def firstrecommend():
user_id = request.json.get('stu_account')
friendLists = Society.query.filter(Society.user_id == user_id ).all()
friendListA = jsonify([friendList.to_dict() for friendList in friendLists])
return friendListA
@app.route('/recommend', methods=['GET','POST']) # 获取除了自己外的所有学员
def recommend():
stu_account = request.json.get('stu_account')
recommends = Student.query.filter(Student.stu_account != stu_account ).all()
return jsonify([recommend.to_dict() for recommend in recommends])
@app.route('/addfriend', methods=['GET','POST']) # 学员自己添加好友
def addfriend():
user_id = request.json.get('user_id')
friend_id = request.json.get('friend_id')
new_friend = Society(user_id=user_id, friend_id=friend_id)
db.session.add(new_friend)
new_friend1 = Society(user_id=friend_id, friend_id=user_id)
db.session.add(new_friend1)
db.session.commit()
return ("1")
@app.route('/secondrecommend1', methods=['GET','POST']) # 获取兴趣,经纬度
def secondrecommend1():
stu_account = request.json.get('stu_account')
student = Student.query.filter(Student.stu_account == stu_account).first()
return jsonify([student.to_dict()])
@app.route('/secondrecommend2', methods=['GET','POST']) # 获取与自己兴趣一致的学员
def secondrecommend2():
stu_interest = request.json.get('stu_interest')
stu_account = request.json.get('stu_account')
friendinterests = Student.query.filter(Student.stu_interest == stu_interest , Student.stu_account != stu_account ).all()
return jsonify([friendinterest.to_dict() for friendinterest in friendinterests])
@app.route('/chatcontent', methods=['GET','POST']) # 获取聊天消息
def chatcontent():
user_id = request.json.get('user_id')
friend_id = request.json.get('friend_id')
chatcontents = Chat.query.filter(Chat.user_id == user_id, Chat.friend_id == friend_id,).order_by(-Chat.chat_time).all()
return jsonify([chatcontent.to_dict() for chatcontent in chatcontents])
@app.route('/addchatcontent', methods=['GET','POST']) # 增加聊天消息
def addchatcontent():
user_id = request.json.get('user_id')
friend_id = request.json.get('friend_id')
chat_type = request.json.get('chat_type')
chat_content = request.json.get('chat_content')
chat_time = request.json.get('chat_time')
new_chatcontent = Chat(user_id=user_id, friend_id=friend_id, chat_type=chat_type, chat_content=chat_content,chat_time=chat_time)
db.session.add(new_chatcontent)
if (chat_type == 1):
chat_type1 = 0
else:
chat_type1 = 1
new_chatcontent1 = Chat(user_id=friend_id, friend_id=user_id, chat_type=chat_type1, chat_content=chat_content,chat_time=chat_time)
db.session.add(new_chatcontent1)
db.session.commit()
return ("1")
if __name__ == '__main__':
app.run()
<file_sep>DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = '<PASSWORD>' # 此处填写你的数据库密码
HOST = '192.168.127.12' # 部署到服务器不能用127.0.0.1 得用localhost
PORT = '3307'
DATABSE = 'db_info' # 此处为你建的数据库的名称
SQLALCHEMY_DATABASE_URI ="{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABSE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
| 69745fda88cb4271ffa35625c799ccf915c9ed0e | [
"Python"
] | 3 | Python | 20160918/minprogramPython | 74b7768eebe7fd22f82a6e76be4079d1ff10f6ee | 97fc47a59399da5b2c2966a1ecc4905e83eb97fc |
refs/heads/master | <repo_name>ZhiweiYi/xiyu-NLPTrainee<file_sep>/7.12/test.py
# -*- coding: utf-8 -*-
# @Time: 2019/10/23 10:40
# @Author: <NAME>
# @Software: PyCharm
print('this is my first repository!') | 0006e8a3208bbceec3878d389a52b72b6adc33e8 | [
"Python"
] | 1 | Python | ZhiweiYi/xiyu-NLPTrainee | 7f0d051079a62a042e25c9ebd5fbdc22b3fb81fe | 1971b22bd948b31661749fc927b54cdfd213f84d |
refs/heads/master | <file_sep># this is a simple model example
# check https://datamapper.org/getting-started.html
require 'data_mapper'
require 'sinatra'
require 'dm-migrations'
class Exchange
include DataMapper::Resource
property :id, Serial # An auto-increment integer key
property :AmountFrom, Text , required: true # A varchar type string, for short strings
property :From, Text , required: true # A text block, for longer string data.
property :To, Text , required: true # A text block, for longer string data.
property :AmountTo, Text , required: true # A varchar type string, for short strings
property :done_at, DateTime , required: true # A DateTime, for any date you might like.
end
DataMapper::Logger.new($stdout, :debug)
DataMapper.finalize
DataMapper.auto_migrate!
DataMapper.auto_upgrade!
<file_sep># Klarx_Challenge
# Klarx_Challenge
<file_sep>source 'https://rubygems.org'
gem 'money-currencylayer-bank'
gem "shotgun", "0.9"
gem "cucumber", "1.2.1"
gem "capybara", "1.1.2"
gem "rspec", "2.10.0"
gem 'sinatra'
gem "data_mapper", "1.2.0"
gem 'httparty'
gem 'mysql2'
gem 'dm-mysql-adapter'
gem "rest-client"
gem "require_all", "~> 3.0"
<file_sep>require 'json'
require 'money/bank/currencylayer_bank'
class ApplicationController < Sinatra::Base
# This configuration part will inform the app where to search for the views and from where it will serve the static files
configure do
set :views, "app/views"
set :public_dir, "public"
end
get '/' do
erb :index
end
get '/dash' do
erb :print
end
post '/todo' do
# Minimal requirements
mclb = Money::Bank::CurrencylayerBank.new
mclb.access_key = '<KEY>'
# Update rates (get new rates from remote if expired or access rates from cache)
# Force update rates from remote and store in cache
# mclb.update_rates(true)
# (optional)
# Set the base currency for all rates. By default, USD is used.
# CurrencylayerBank only allows USD as base currency for the free plan users.
# (optional)
# Set the seconds after than the current rates are automatically expired
# by default, they never expire, in this example 1 day.
# (optional)
# Use https to fetch rates from CurrencylayerBank
# CurrencylayerBank only allows http as connection for the free plan users.
mclb.update_rates # Update rates (get new rates from remote if expired or access rates from cache)
Money.default_bank = mclb
Money.locale_backend = :i18n
I18n.enforce_available_locales = false
AmountFrom=params['AmountFrom'].to_i
from1=params['EURO']
from2=params['CHF']
from3=params['USD']
to1=params['EURO1']
to2=params['CHF1']
to3=params['USD1']
if from1.to_s=="on"
from="EUR"
elsif from2.to_s=="on"
from="CHF"
elsif from3.to_s=="on"
from="USD"
end
if to1.to_s=="on"
to="EUR"
elsif to2.to_s=="on"
to="CHF"
elsif to3.to_s=="on"
to="USD"
end
AmountTo=Money.new( AmountFrom* 100, from.to_s).exchange_to(to).format
done=Time.now
@post = Exchange.create(
:AmountFrom => AmountFrom.to_s,
:From =>from,
:To => to,
:AmountTo => AmountTo.to_s,
:done_at => Time.now
)
# Or new gives you it back unsaved, for more operations
@post.save
def global
@@variable=AmountTo
end
redirect "/dash"
end
get '/history' do
@todos = Exchange.all
erb :history
end
end | 7eede467a7c76c570433835cab6dc0f72e06f914 | [
"Markdown",
"Ruby"
] | 4 | Ruby | souheyltoumi/Klarx_Challenge | 64f2c56a91fa6ae70e8cfb12a9bed06700192336 | c685f1d4db6ee0323f065b0993094282994fde2b |
refs/heads/master | <file_sep># sanketswamy.github.io
<file_sep>function SubmitForm() {
document.getElementById('Thankyou').classList.remove('hidden');
document.getElementById('form').classList.add('hidden');
}
document.getElementById("submit").onclick = SubmitForm; | d5a857404e2285995347fac50ad64385a6dd1b9b | [
"Markdown",
"JavaScript"
] | 2 | Markdown | sanketswamy/sanketswamy.github.io | d2ab7875cd65408b3ba5de1cd0b05f65d98cd439 | bd179136597102efba1c9076be4bf2e299678d9b |
refs/heads/master | <file_sep># turbo-oauth
<file_sep>local oauth2 = {
_VERSION = "v1.0.0",
_DESCRIPTION = "OAuth2 for Turbo.lua",
_URL = "https://github.com/luastoned/turbo-oauth",
_LICENSE = [[Copyright (c) 2015 @LuaStoned]],
}
-- Always set me when using SSL, before loading framework.
TURBO_SSL = true
local turbo = require("turbo")
local function request(method, url, params, headers)
local options = {
method = method,
params = params,
on_headers = function(self)
for k, v in pairs(headers or {}) do
self:add(k, v)
end
end,
}
local res = coroutine.yield(turbo.async.HTTPClient():fetch(url, options))
if (res.error) then
error(res.error)
end
return res.body
end
local function sha1(str, key, raw)
return turbo.hash.HMAC(key, str, raw)
end
local function base64(str)
return turbo.escape.base64_encode(str)
end
-- Parameter encoding according to RFC3986
-- http://tools.ietf.org/html/rfc3986#section-2.3
-- http://oauth.net/core/1.0a/#encoding_parameters
local function encodeParam(str)
return string.gsub(tostring(str), "[^-._~%w]", function(char)
return string.format("%%%02x", char:byte()):upper()
end)
end
local function decodeParam(str)
str = string.gsub(tostring(str), "+", " ")
str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
str = string.gsub(str, "\r\n", "\n")
return str
end
-- oauth2
function oauth2:getAccessToken(grantType, extraArg)
local arg = {
grant_type = grantType or "client_credentials",
}
if (extraArg and type(extraArg) == "table") then
for key, val in pairs(extraArg) do
if (val ~= nil) then
arg[key] = tostring(val)
end
end
end
local res = self:request("POST", self.accessUrl, arg)
local tbl = turbo.escape.json_decode(res)
self.tokenType = decodeParam(tbl.token_type)
self.accessToken = decodeParam(tbl.access_token)
return {res, self.tokenType, self.accessToken}
end
function oauth2:request(method, url, arg)
local params = {
}
if (arg and type(arg) == "table") then
for key, val in pairs(arg) do
if (val ~= nil) then
params[key] = tostring(val)
end
end
end
local headers = {}
headers["Authorization"] = self:getAuthorizationHeader()
for key, val in pairs(self.headers or {}) do
headers[key] = val
end
return request(method, url, params, headers)
end
function oauth2:getAuthorizationHeader()
if (self.accessToken) then
return string.format("Bearer %s", encodeParam(self.accessToken))
else
return string.format("Basic %s", string.gsub(base64(self.consumerKey .. ":" .. self.consumerSecret), "\r\n", ""))
end
end
local function createClient(consumerKey, consumerSecret, arg)
local tbl = {
consumerKey = consumerKey,
consumerSecret = consumerSecret,
}
for key, val in pairs(arg) do
tbl[key] = val
end
setmetatable(tbl, oauth2)
return tbl
end
local meta = {
__call = function(tbl, ...)
return createClient(unpack({...}))
end,
}
oauth2.__index = oauth2
setmetatable(oauth2, meta)
return oauth2
<file_sep>local oauth = {
_VERSION = "v1.0.0",
_DESCRIPTION = "OAuth for Turbo.lua",
_URL = "https://github.com/luastoned/turbo-oauth",
_LICENSE = [[Copyright (c) 2015 @LuaStoned]],
}
-- Always set me when using SSL, before loading framework.
TURBO_SSL = true
local turbo = require("turbo")
local function request(method, url, params, headers)
local options = {
method = method,
params = params,
on_headers = function(self)
for k, v in pairs(headers or {}) do
self:add(k, v)
end
end,
}
local res = coroutine.yield(turbo.async.HTTPClient():fetch(url, options))
if (res.error) then
error(res.error)
end
return res.body
end
local function sha1(str, key, raw)
return turbo.hash.HMAC(key, str, raw)
end
local function base64(str)
return turbo.escape.base64_encode(str)
end
local function generateNonce()
return sha1(tostring(math.random()) .. tostring(os.time()), "magic_key")
end
local function generateTimestamp()
return tostring(os.time())
end
local function isParam(str)
local params = {
oauth_callback = true,
oauth_consumer_key = true,
oauth_nonce = true,
oauth_signature_method = true,
oauth_token = true,
oauth_timestamp = true,
oauth_verifier = true,
oauth_version = true,
scope = true,
}
return params[str]
end
-- Parameter encoding according to RFC3986
-- http://tools.ietf.org/html/rfc3986#section-2.3
-- http://oauth.net/core/1.0a/#encoding_parameters
local function encodeParam(str)
return string.gsub(tostring(str), "[^-._~%w]", function(char)
return string.format("%%%02x", char:byte()):upper()
end)
end
local function decodeParam(str)
str = string.gsub(tostring(str), "+", " ")
str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
str = string.gsub(str, "\r\n", "\n")
return str
end
-- oauth
function oauth:getRequestToken(callbackUrl)
local arg = {
oauth_callback = callbackUrl or self.tokenReady,
}
local res = self:request("POST", self.requestUrl, arg)
self.requestToken = decodeParam(res:match("oauth_token=([^&]+)"))
self.requestTokenSecret = decodeParam(res:match("oauth_token_secret=([^&]+)"))
if (self.authorizeUrl) then
self.tokenUrl = self.authorizeUrl .. "?oauth_token=" .. encodeParam(self.requestToken)
end
return {res, self.requestToken, self.requestTokenSecret, self.tokenUrl}
end
function oauth:getAccessToken(verifier)
local arg = {
oauth_verifier = verifier,
}
local res = self:request("POST", self.accessUrl, arg)
self.accessToken = decodeParam(res:match("oauth_token=([^&]+)"))
self.accessTokenSecret = decodeParam(res:match("oauth_token_secret=([^&]+)"))
return {res, self.accessToken, self.accessTokenSecre}
end
function oauth:request(method, url, arg)
local params = {
oauth_version = "1.0",
oauth_nonce = generateNonce(),
oauth_timestamp = generateTimestamp(),
oauth_signature_method = "HMAC-SHA1",
oauth_consumer_key = self.consumerKey,
oauth_token = self.accessToken or self.requestToken,
oauth_token_secret = self.accessTokenSecret or self.requestTokenSecret,
}
local tokenSecret = self.accessTokenSecret or self.requestTokenSecret
if (arg and type(arg) == "table") then
for key, val in pairs(arg) do
if (val ~= nil) then
params[key] = tostring(val)
end
end
end
params.oauth_token_secret = nil
local headers = {}
local signature = self:getSignature(method, url, params, tokenSecret)
headers["Authorization"] = self:getAuthorizationHeader(params, signature)
for key, val in pairs(self.headers or {}) do
headers[key] = val
end
for key, val in pairs(params) do
if (isParam(key)) then
params[key] = nil
end
end
return request(method, url, params, headers)
end
function oauth:getAuthorizationHeader(params, signature)
local header = {}
for key, val in pairs(params) do
if (isParam(key)) then
table.insert(header, string.format("%s=\"%s\"", key, encodeParam(val)))
end
end
table.insert(header, "oauth_signature=\"" .. encodeParam(signature) .. "\"")
table.sort(header, function(a, b) return a < b end)
return string.format("OAuth %s", table.concat(header, ", "))
end
function oauth:getSignature(method, url, params, tokenSecret)
tokenSecret = tokenSecret or ""
-- oauth-encode each key and value, and get them set up for a Lua table sort
local keys_and_values = {}
for key, val in pairs(params) do
table.insert(keys_and_values, {
key = encodeParam(key),
val = encodeParam(val),
})
end
-- sort by key first, then value
table.sort(keys_and_values, function(a, b) return a.key == b.key and (a.val < b.val) or (a.key < b.key) end)
-- now combine key and value into key=value
local key_value_pairs = {}
for _, rec in pairs(keys_and_values) do
table.insert(key_value_pairs, rec.key .. "=" .. rec.val)
end
local signatureBase = string.format("%s&%s&%s", method, encodeParam(url), encodeParam(table.concat(key_value_pairs, "&")))
local signatureKey = string.format("%s&%s", encodeParam(self.consumerSecret), encodeParam(tokenSecret))
-- Now have our text and key for HMAC-SHA1 signing
local hmac_binary = sha1(signatureBase, signatureKey, true)
local hmac_b64 = base64(hmac_binary)
return hmac_b64
end
local function createClient(consumerKey, consumerSecret, arg)
local tbl = {
consumerKey = consumerKey,
consumerSecret = consumerSecret,
}
for key, val in pairs(arg) do
tbl[key] = val
end
setmetatable(tbl, oauth)
return tbl
end
local meta = {
__call = function(tbl, ...)
return createClient(unpack({...}))
end,
}
oauth.__index = oauth
setmetatable(oauth, meta)
return oauth
| 81b24efb12ab6c75c13b910ff8202ef600139ed6 | [
"Markdown",
"Lua"
] | 3 | Markdown | luastoned/turbo-oauth | 6dbe93c007ea87a553efae8821f4b8224d31489d | 8b73af7af8e23d44e329b40aecb028c3ca6fc29b |
refs/heads/master | <repo_name>dciccale/dotfiles<file_sep>/.bash_aliases
# vim: ft=sh
################################################################################
# Easier navigation
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
################################################################################
# IP addresses
alias ip="dig +short myip.opendns.com @resolver1.opendns.com"
alias localip="ipconfig getifaddr en1"
alias ips="ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1'"
################################################################################
# Cocos 2dx
# Create cocos2d-x multi-platform project
cocos2dxproj() {
if [[ -z "$1" || -z "$2" ]]; then
echo "provide project and package name"
return 0
fi
if [ -z "$3" ]; then
LANG="cpp"
else
LANG="$3"
fi
cd ~/Downloads/cocos2d-x-2.1.4/tools/project-creator/
python create_project.py -project $1 -package $2 -language ${LANG}
cd ../../projects/$1
open .
}
alias cocos2dxproj=cocos2dxproj
################################################################################
# Xcode cleanup
cleanxcode() {
cd ~/Library/Developer/Xcode/DerivedData/
rm -rf *
}
alias cleanxcode=cleanxcode
################################################################################
# Blackberry 10 dev shortcuts
bbdeploy() {
/Developer/SDKs/Research\ In\ Motion/BlackBerry\ 10\ WebWorks\ SDK\ 1.0.4.5/ \
dependencies/tools/bin/blackberry-deploy -installApp -password $1 -device \
$2 -package $3
}
alias bbdeploy=bbdeploy
################################################################################
# Open file in a current opened mac vim or just a new mac vim window
# command: Run command with arguments ignoring any shell function named command.
mvim() {
if [[ $# > 0 ]]; then
command mvim --remote-silent "$@"
else
command mvim
fi
}
alias mvim=mvim
alias m=mvim
alias vim="/Applications/MacVim.app/Contents/MacOS/Vim $*"
################################################################################
# MISC
alias title="printf '\033]0;%s\007'"
# Create a dir and cd into it
md() {
mkdir -p "$@" && cd "$_";
}
alias md=md
alias o=open
# Quick cd home
home() {
cd ~/$@
}
alias home=home
# Reloads my bashrc
alias reload='. $MYBASHRC; printf "\n${BLUE}.bashrc reloaded!\n${RESET}"'
# Go back to previous path
alias back="cd - &>/dev/null"
# List only directories
alias lsd="ls -d */"
alias cl="clear"
alias ex="exit"
alias ls="ls -G"
alias c="pygmentize -O style=monokai -f console256 -g"
alias g="git"
alias apachelogs="tail -f /var/log/apache2/error_log"
pr() {
local repo=`git remote -v | grep -m 1 "(push)" | sed -e "s/.*github.com[:/]\(.*\)\.git.*/\1/"`
local branch=`git name-rev --name-only HEAD`
open https://github.com/$repo/pull/new/$branch
}
alias fixcam="sudo killall VDCAssistant"
# Print http status every n seconds
# n defaults to 1s
# usage:
# http-ping google.com .5 (500 milliseconds)
# http-ping google.com 2 (2 seconds)
http-ping() {
n=1 && (($#>1)) && n=$2
while true
do
curl -o /dev/null --silent --head --write-out '%{http_code}\n' $1
sleep ${n}
done
}
weather() {
curl -4 wttr.in/$1
}
alias welcome="say -v Vicki I am pleased to introduce you to Denis, Co-Founder of Zenfulfillment! give him a warm welcome."
<file_sep>/.vim/templates/template.js
/*
* Template file
*/
'use strict';
<file_sep>/README.md
# dotfiles
Here are some of my dotfile configurations for git and vim.
## Installation
Drop these dotfiles in your home directory just by doing:
```bash
$ git clone https://github.com/dciccale/dotfiles.git ~/
```
## Vim plugins installation
1 - Install Vundle for plugin management:
```bash
$ git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
```
2 - Open vim and run the following command to install the plugins used:
```
:PlugInstall
```
Or if using my mappings just type `,bi`.
### Plugin updates
Each time you want to update any plugin, vundle does it for you, just run this command in vim:
```
:PlugUpdate
```
Or if keeping my mappings just do `,bu`.
cheers.
<file_sep>/.bashrc
# Source: http://github.com/dciccale/dotfiles/blob/master/.bashrc
export TERM=xterm-256color
export EDITOR="mvim"
export FIGNORE=DS_Store
# colors
PURPLE="$(tput setaf 5)"
DARKGREY="$(tput setaf 8)"
WHITE="$(tput setaf 7)"
YELLOW="$(tput setaf 3)"
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
BLUE="$(tput setaf 4)"
RESET="$(tput sgr0)"
# load bash aliases
if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases; fi
export MOAI_BIN="${HOME}/Downloads/moai-sdk/bin/osx"
PATH=/usr/local/mysql/bin:$PATH
PATH=$MOAI_BIN:$PATH
PATH=/usr/local/git/bin:/usr/local/sbin:$PATH
PATH=/usr/local/bin:$PATH
PATH=${HOME}/tizen-sdk/tools/ide/bin:$PATH
PATH=${HOME}/ant/bin:$PATH
PATH=/usr/local/php5/bin:$PATH
PATH=/usr/local/sbin:$PATH
PATH=${HOME}/.yarn/bin:$PATH
PATH="$PATH:`yarn global bin`"
PATH=${HOME}/git/gitinspector:$PATH
# PATH=~/Downloads/android:$PATH
export GOROOT="/usr/local/opt/go/libexec"
export GOPATH="${HOME}/go"
PATH=$GOROOT/bin:$GOPATH/bin:$PATH
# PATH=${HOME}/.rvm/bin:$PATH
# . ~/.rvm/scripts/rvm
export MONGO_PATH=/usr/local/mongodb
PATH=$PATH:$MONGO_PATH/bin
# export docker variables if it is running
docker-machine env default &>/dev/null
IS_DOCKER_RUNNING=$?
if [ $IS_DOCKER_RUNNING -eq 0 ]; then
eval $(docker-machine env default --shell=bash)
fi
export TUTUM_USER=dciccale
export TUTUM_APIKEY=<KEY>043407c694f
function parse_git_dirty() {
git diff --quiet --ignore-submodules HEAD &>/dev/null; [ $? -eq 1 ] && echo "*"
}
checkpull() {
[ $(git rev-parse HEAD) != $(git rev-parse @{u}) ] && echo "⇣"
}
function parse_git_branch() {
# check if we're in a git repo
git rev-parse --is-inside-work-tree &>/dev/null || return
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1$(parse_git_dirty)/"
}
function prompt() {
# http://apple.stackexchange.com/questions/49835/how-to-make-mac-terminal-restore-working-directories-when-restarting#answer-50334
# call default prompt
update_terminal_cwd
LEFT=${PWD/$HOME/'~'} # current dir
RIGHT=$(parse_git_branch) # git branch
COLS=$(($(tput cols)-${#LEFT}+${#PURPLE})) # calculated columns
# print -Pn "\e7\e[A\e[1G\e["asd"C%F{cyan}⇣%f\e8"
P=$(printf '%s%*s%s%s' "${YELLOW}${LEFT}" ${COLS} "${PURPLE}${RIGHT}")
printf "\n${P}${RESET}\n\n"
# echo -en "\n${P}${RESET}\n\n"
}
PROMPT_COMMAND=prompt
# PS1="\[${DARKGREY}\]❯\[${RESET}\] "
PS1="\[${RED}\]❯\[${YELLOW}\]❯\[${GREEN}\]❯\[${RESET}\] "
PS2="\[${RED}\]❯\[${RESET}\] "
## Tizen SDK configuration
# This is generated by Tizen SDK. Please do not modify by yourself.
# Set sdb environment path
export PATH=$PATH:${HOME}/tizen-sdk/tools
## End Tizen SDK configuration
# Export my .bashrc file path
export MYBASHRC=${HOME}/.bashrc
# Export my .aliases file path
export MYALIASES=${HOME}/.bash_aliases
### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
export PATH="$HOME/.yarn/bin:$PATH"
<file_sep>/.osx
#!/usr/bin/env bash
OSX=$(test "`uname`" == "Darwin" && echo "x")
if [[ OSX ]]; then
# Ask for the administrator password upfront
sudo -v
# Keep-alive: update existing `sudo` time stamp until `.osx` has finished
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
############################################################################
# General UI/UX #
############################################################################
# Disable the sound effects on boot
sudo nvram SystemAudioVolume=" "
# disable window animations
sudo defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool NO
# disable the “Are you sure you want to open this application?” dialog
defaults write com.apple.LaunchServices LSQuarantine -bool false
# disable opening and closing window animations
sudo defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool false
# disable Resume system-wide
sudo defaults write NSGlobalDomain NSQuitAlwaysKeepsWindows -bool false
# disable auto-correct
sudo defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false
# disable Finder animations
defaults write com.apple.finder DisableAllAnimations -bool true
# disable disk image verification
defaults write com.apple.frameworks.diskimages skip-verify -bool true
defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true
defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true
# disable the warning when changing a file extension
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
# prevent Time Machine from prompting to use new hard drives as backup volume
# defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true
# Restart automatically if the computer freezes
systemsetup -setrestartfreeze on
# Disable the “Are you sure you want to open this application?” dialog
defaults write com.apple.LaunchServices LSQuarantine -bool false
# Disable Notification Center and remove the menu bar icon
launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2> /dev/null
############################################################################
# Screen #
############################################################################
# Enable subpixel font rendering on non-Apple LCDs
defaults write NSGlobalDomain AppleFontSmoothing -int 2
# Require password immediately after sleep or screen saver begins
defaults write com.apple.screensaver askForPassword -int 1
defaults write com.apple.screensaver askForPasswordDelay -int 0
# Save screenshots to ~/Screenshots
mkdir -p "${HOME}/Screenshots"
defaults write com.apple.screencapture location -string "${HOME}/Screenshots"
# Save screenshots in PNG format (other options: BMP, GIF, JPG, PDF, TIFF)
defaults write com.apple.screencapture type -string "png"
############################################################################
# SSD-specific tweaks #
############################################################################
# Disable hibernation (speeds up entering sleep mode)
sudo pmset -a hibernatemode 0
# Remove the sleep image file to save disk space
sudo rm /private/var/vm/sleepimage
# Create a zero-byte file instead…
sudo touch /private/var/vm/sleepimage
# …and make sure it can’t be rewritten
sudo chflags uchg /private/var/vm/sleepimage
# Disable the sudden motion sensor as it’s not useful for SSDs
sudo pmset -a sms 0
############################################################################
# Finder #
############################################################################
# Finder: allow quitting via ⌘ + Q; doing so will also hide desktop icons
defaults write com.apple.finder QuitMenuItem -bool true
# Finder: disable window and Get Info animations
defaults write com.apple.finder DisableAllAnimations -bool true
# Finder: show all filename extensions
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
# Finder: allow text selection in Quick Look
defaults write com.apple.finder QLEnableTextSelection -bool true
# Finder: display full path as Finder window title
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
# When performing a search, search the current folder by default
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"
# Finder: automatically open a new window when a volume is mounted
defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool true
defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool true
defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool true
# Enable snap-to-grid for icons on the desktop and in other icon views
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
# Increase grid spacing for icons on the desktop and in other icon views
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist
# Increase the size of icons on the desktop and in other icon views
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:iconSize 64" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:iconSize 64" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:iconSize 64" ~/Library/Preferences/com.apple.finder.plist
# Use columns view in all Finder windows by default
# Four-letter codes for the other view modes: `icnv`, `Nlsv`, `Flwv`
defaults write com.apple.finder FXPreferredViewStyle -string "clmv"
# General: enable the warning before emptying the Trash
defaults write com.apple.finder WarnOnEmptyTrash -bool true
# Show the ~/Library folder
chflags nohidden ~/Library
############################################################################
# Trackpad, mouse, keyboard, Bluetooth accessories, and input #
############################################################################
# Trackpad: enable tap to click for this user and for the login screen
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true
defaults -currentHost write NSGlobalDomain com.apple.mouse.tapBehavior -int 1
defaults write NSGlobalDomain com.apple.mouse.tapBehavior -int 1
# Increase sound quality for Bluetooth headphones/headsets
defaults write com.apple.BluetoothAudioAgent "Apple Bitpool Min (editable)" -int 40
# Enable full keyboard access for all controls
# (e.g. enable Tab in modal dialogs)
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3
# General: automatically illuminate built-in MacBook keyboard in low light
defaults write com.apple.BezelServices kDim -bool true
# Turn off keyboard illumination when computer is not used for 5 minutes
defaults write com.apple.BezelServices kDimTime -int 300
# Use scroll gesture with the Ctrl (^) modifier key to zoom
defaults write com.apple.universalaccess closeViewScrollWheelToggle -bool true
defaults write com.apple.universalaccess HIDScrollZoomModifierMask -int 262144
# Follow the keyboard focus while zoomed in
defaults write com.apple.universalaccess closeViewZoomFollowsFocus -bool true
# Disable press-and-hold for keys in favor of key repeat
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
# Set a blazingly fast keyboard repeat rate
defaults write NSGlobalDomain KeyRepeat -int 0
############################################################################
# Dock, Dashboard, and hot corners #
############################################################################
# Dock: minimize windows into their application's icon
defaults write com.apple.dock minimize-to-application -bool true
# Speed up Mission Control animations
defaults write com.apple.dock expose-animation-duration -float 0.1
# Dock: make icons of hidden applications translucent
defaults write com.apple.dock showhidden -bool true
# Set the icon size of Dock items to 48 pixels
defaults write com.apple.dock tilesize -int 36
# Don’t automatically rearrange Spaces based on most recent use
defaults write com.apple.dock mru-spaces -bool false
# Remove the auto-hiding Dock delay
defaults write com.apple.dock autohide-delay -float 0
# Remove the animation when hiding/showing the Dock
defaults write com.apple.dock autohide-time-modifier -float 0
# Automatically hide and show the Dock
defaults write com.apple.dock autohide -bool true
############################################################################
# Safari & WebKit #
############################################################################
# Privacy: don’t send search queries to Apple
defaults write com.apple.Safari UniversalSearchEnabled -bool false
defaults write com.apple.Safari SuppressSearchSuggestions -bool true
# Press Tab to highlight each item on a web page
defaults write com.apple.Safari WebKitTabToLinksPreferenceKey -bool true
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2TabsToLinks -bool true
# Show the full URL in the address bar (note: this still hides the scheme)
defaults write com.apple.Safari ShowFullURLInSmartSearchField -bool true
# Set Safari’s home page to `about:blank` for faster loading
defaults write com.apple.Safari HomePage -string "about:blank"
# Prevent Safari from opening ‘safe’ files automatically after downloading
defaults write com.apple.Safari AutoOpenSafeDownloads -bool false
# Hide Safari’s bookmarks bar by default
defaults write com.apple.Safari ShowFavoritesBar -bool false
# Hide Safari’s sidebar in Top Sites
defaults write com.apple.Safari ShowSidebarInTopSites -bool false
# Disable Safari’s thumbnail cache for History and Top Sites
defaults write com.apple.Safari DebugSnapshotsUpdatePolicy -int 2
# Enable Safari’s debug menu
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true
# Make Safari’s search banners default to Contains instead of Starts With
defaults write com.apple.Safari FindOnPageMatchesWordStartsOnly -bool false
# Remove useless icons from Safari’s bookmarks bar
defaults write com.apple.Safari ProxiesInBookmarksBar "()"
# Enable the Develop menu and the Web Inspector in Safari
defaults write com.apple.Safari IncludeDevelopMenu -bool true
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled -bool true
# Add a context menu item for showing the Web Inspector in web views
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true
############################################################################
# Address Book, Dashboard, iCal, TextEdit, and Disk Utility #
############################################################################
# Use plain text mode for new TextEdit documents
defaults write com.apple.TextEdit RichText -int 0
# Open and save files as UTF-8 in TextEdit
defaults write com.apple.TextEdit PlainTextEncoding -int 4
defaults write com.apple.TextEdit PlainTextEncodingForWrite -int 4
############################################################################
# Transmission.app #
############################################################################
# Use `~/Documents/Torrents` to store incomplete downloads
defaults write org.m0k.transmission UseIncompleteDownloadFolder -bool true
defaults write org.m0k.transmission IncompleteDownloadFolder -string "${HOME}/Documents/Torrents"
# Don’t prompt for confirmation before downloading
defaults write org.m0k.transmission DownloadAsk -bool false
# Trash original torrent files
defaults write org.m0k.transmission DeleteOriginalTorrent -bool true
# Hide the donate message
defaults write org.m0k.transmission WarningDonate -bool false
# Hide the legal disclaimer
defaults write org.m0k.transmission WarningLegal -bool false
############################################################################
# Kill affected applications #
############################################################################
for app in "Dock" "Finder" "SystemUIServer"; do
killall "${app}" > /dev/null 2>&1
done
echo "Done. Note that some of these changes require a logout/restart to take effect."
else
echo "Skipping ~/.osx evaluation..."
fi
<file_sep>/Brewfile
tap "bbc/audiowaveform"
tap "heroku/brew"
tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/cask-fonts"
tap "homebrew/cask-versions"
tap "homebrew/core"
tap "homebrew/services"
tap "mongodb/brew"
brew "giflib"
brew "libpng"
brew "webp"
brew "aom"
brew "argocd"
brew "sqlite"
brew "xz"
brew "python@3.10", link: false
brew "asciinema"
brew "bitcoin"
brew "bzip2"
brew "glib"
brew "pkg-config"
brew "libxcb"
brew "libx11"
brew "pixman"
brew "python@3.9", link: false
brew "cairo"
brew "erlang"
brew "elixir"
brew "fd"
brew "guile"
brew "unbound"
brew "gnutls"
brew "harfbuzz"
brew "little-cms2"
brew "libass"
brew "srt"
brew "tesseract"
brew "ffmpeg"
brew "gd"
brew "gdk-pixbuf"
brew "gobject-introspection"
brew "jpeg", link: true
brew "kustomize"
brew "pango"
brew "librsvg"
brew "luv"
brew "node@16"
brew "mongosh"
brew "neovim"
brew "node@14"
brew "openjdk"
brew "postgresql@14"
brew "pyenv"
brew "redis"
brew "ripgrep"
brew "the_silver_searcher"
brew "tmux"
brew "wget"
brew "zlib"
brew "bbc/audiowaveform/audiowaveform"
brew "heroku/brew/heroku"
brew "mongodb/brew/mongodb-community"
cask "adoptopenjdk8"
cask "font-fira-code"
| 6d0814dfdcd40209e6f8b3069fc2b9c49a0f5fae | [
"JavaScript",
"Ruby",
"Markdown",
"Shell"
] | 6 | Shell | dciccale/dotfiles | 41aca59e3c420bf2fe71a1edf0450ae4218d1698 | 16c1f0daef63307102aac6cddb22d6b2a72eb158 |
refs/heads/master | <repo_name>avandrevitor/S9<file_sep>/Interfaces/iBusiness.php
<?php
/**
* @package S9\Interfaces
*/
namespace S9\Interfaces;
/**
* Interface de Negócio da S9
*/
interface iBusiness{
/**
* Construct
* @param array $args
*/
public function __construct(array $args=array());
/**
* @param int Identificação do Objeto no Banco de Dados
*/
public function setId($id);
/**
* @return int Identificação do Objeto no Banco de Dados
*/
public function getId();
/**
* @return string Representação em formato String do Objeto
*/
public function __toString();
/**
* @return array Representação em formato Array do Objeto recursivamente
*/
public function toArray();
/**
* @return string Representação em formato Json de um Objeto
*/
public function toJson();
/**
* @return string Representação em formato XML de um Objeto
*/
public function toXML();
}<file_sep>/Model/DAO.php
<?php
/**
* @package \S9\Model
*/
namespace S9\Model;
use \S9\Engine\MapperEngine,
\S9\Pattern\Logging;
/**
* Classe que Representa o Pattern DAO - Data Access Object
* - Tem dependencia do Zend_Db (v1.11.*) para funcionamento
*/
class DAO{
/**
* Configurações de Acesso por Modulo
* @var string
*/
protected $module_config = null;
/**
* Dados de Acesso ao Database.
* @var \Zend_Config
*/
protected $config;
/**
* A Instancia do MapperEngine
* @var S9\Engine\MapperEngine
*/
protected $oMapper;
/**
* Instancia do Logging
* @var \S9\Pattern\Logging
*/
protected $log;
/**
* Construct
* @param array $config Configurações para acesso a dados
* @return void
*/
public function __construct($config = array()) {
if(empty($config)){
$this->config = $this->getConfigs();
}else{
if(is_array($config)){
$this->config = $config;
}
}
$this->oMapper = new MapperEngine();
}
/**
* Obter Configurações
* @return array
*/
public function getConfigs($item = 'db'){
if(!is_null($this->module_config)){
return include(S9_MODULE_PATH."/{$this->module_config}/configs/{$item}.php");
}
return include(S9_APP_PATH."/configs/{$item}.php");
}
/**
* Obtem o Logging
* @return \S9\Pattern\Logging
*/
protected function getLog(){
if(is_null($this->log)){
$this->log = Logging::getInstance($this->getConfigs('log'));
}
return $this->log;
}
/**
* Obtem um objeto Adapter Abstract para realizar consultas.
* @return \Zend_Db_Adapter_Abstract
*/
public function getAdapter(){
$config = $this->config;
return \Zend_Db::factory($config[S9_APP_ENV]['adapter'], $config[S9_APP_ENV]['params']);
}
/**
* Cria o registro do banco
* @param mixed $table
* @param array $bind padrão chave=>valor.
* @return boolean|int Em caso de suceso retorna o id inserido, em caso de
* erro retorna FALSE;
*/
public function create($table,array $bind){
$oAdapter = $this->getAdapter();
try{
$oAdapter->insert($table, $bind);
$result = (int) $oAdapter->lastInsertId();
}catch(\Zend_Db_Exception $oException){
$this->getLog()->register($oException->getMessage());
$result = FALSE;
}
return $result;
}
/**
* Atualiza o registro no banco
* @param mixed $table
* @param array $bind
* @param mixed $where
* @return boolean
*/
public function update($table,array $bind,$where){
$oAdapter = $this->getAdapter();
try{
//removendo id (primeiro item)
array_shift($bind);
$result = $oAdapter->update($table, $bind, $where);
if(is_int($result)){
return true;
}else{
return false;
}
}catch(\Zend_Db_Exception $oException){
$this->getLog()->register($oException->getMessage());
$result = FALSE;
}
return $result;
}
/**
* Detela registros seguindo uma condição where
* @param mixed $table
* @param mixed $where
* @return boolean
*/
public function delete($table,$where=''){
$oAdapter = $this->getAdapter();
try{
$result = $oAdapter->delete($table, $where);
if(is_int($result)){
return true;
}else{
return false;
}
}catch(\Zend_Db_Exception $oException){
$this->getLog()->register($oException->getMessage());
$result = FALSE;
}
return $result;
}
/**
* Faz um select All em uma tabela
* @param string $from
* @return array
*/
public function selectAll($from){
try{
$oAdapter = $this->getAdapter();
return $oAdapter->fetchAll($oAdapter->quote($oAdapter->select()->from($from)));
}catch(\Zend_Db_Exception $oException){
$this->getLog()->register($oException->getMessage());
return false;
}
}
/**
* Faz um select pelo Id
* @param string $from
* @param int $id
* @return array bind
*/
public function selectById($from,$id){
try{
$oAdapter = $this->getAdapter();
$where = 'id = ? ';
$sql = $oAdapter->select()->from($from)->where($where, $id)->assemble();
$statement = $oAdapter->quoteInto($sql,$id, 'INTEGER');
$result = $oAdapter->fetchRow($statement);
}catch(\Zend_Db_Exception $oException){
$this->getLog()->register($oException->getMessage());
$result = FALSE;
}
return $result;
}
/**
* Define o mapeador para uma determinada Entidade
* @param string $classe Entidade a ser mapeada
* @param array $mapperObject lista de atributos da classe
* @param array $mapperDB lista de campos da tabela
*/
public function setMapper($classe,$mapperObject,$mapperDB){
if(!is_object($this->oMapper)){
$this->oMapper = new MapperEngine();
}
$this->oMapper->setMap($classe, array(
'object' => $mapperObject,
'db' => $mapperDB
));
}
/**
* Retorna a instancia criada do Mapper
* @return \S9\Engine\MapperEngine
*/
public function getMapper(){
return $this->oMapper;
}
/**
* Obtem o mapeamento de persistencia para uma registro
* @param S9\Engine\MapperEngine $mapper Instancia do MapperEngine
* @param object $oObjeto
* @return array
*/
public function unmaker(MapperEngine $mapper, $oObjeto){
$map = $mapper->getMapTo(get_class($oObjeto), 'db');
return $mapper->getRegister($map, $oObjeto->toArray());
}
/**
* Obtem o mapeamento de persistencia para um objeto
* @param S9\Engine\MapperEngine $mapper Instancia do MapperEngine
* @param array $values dados do objeto
* @return object uma instancia do objeto da classe passada com os valores setados.
*/
public function remaker(MapperEngine $mapper, $classe, array $values){
$map = $mapper->getMapTo($classe, 'object');
return $mapper->getObject($classe, $map, $values);
}
/**
* Ordena uma matriz por um campo chave contido no array da matriz
* @param array $lista matriz a ser ordernada
* @param string|int $index chave do array para ordernação
* @return array array ordernado
*/
public function ordernarPor(array $lista,$index){
$resultado = array();
foreach($lista as $item){
if(!array_key_exists($index,$item)){
return $lista;
}
$resultado[$item[$index]] = $item;
}
return $resultado;
}
}<file_sep>/Engine/MapperEngine.php
<?php
namespace S9\Engine;
use S9\Interfaces\iMapperEngine;
class MapperEngine implements iMapperEngine{
/**
* @var \ArrayObject
*/
protected $maps;
public function __construct(array $args = array()) {
$this->maps = new \ArrayObject($args);
}
/**
* Set Map class business
* @param string $index name class business
* @param array $map array with mapping
*/
public function setMap($index,array $map){
$this->maps->offsetSet($index, $map);
}
/**
* Get Map to business or dao
* @param string $index
* @param array $map
*/
public function getMapTo($index,$to){
if($this->maps->offsetExists($index)){
$map = $this->maps->offsetGet($index);
if(in_array($to, array('db','object'))){
return $map[$to];
}
return FALSE;
}else{
return FALSE;
}
}
/**
* Verifica se existe um objeto na coleção e adiciona o relacionamento correto.
* @param array $values
* @return array
*/
protected function putRelationship(array $values){
foreach($values as &$value){
if(is_object($value)){
$value = $value->getId();
}
}
return $values;
}
/**
*
* @param string $class
* @param array $map
* @param array $values
* @return \class
*/
public function getObject($class,$map,$values){
return new $class(array_combine($map,$values));
}
/**
*
* @param array $map
* @param array $values
* @return array
*/
public function getRegister($map,$values){
return array_combine($map, $this->putRelationship($values));
}
}<file_sep>/Pattern/Email.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
class Email{
/**
* Codificacao UTF8
* @var string
*/
const UTF8 = "UTF-8";
/**
* Codificação ISO
* @var string
*/
const ISO88591 = "ISO-8859-1";
/**
* Flag que define se o email pode possuir HTML ou não
* @var boolean
*/
protected $htmlEnable = TRUE;
/**
* Destinatário
* @var \ArrayObject
*/
protected $to;
/**
* Cabeçalhos
* @var \ArrayObject
*/
protected $headers;
/**
* Assunto do Email
* @var string
*/
protected $subject;
/**
* Conteúdo do Email
* @var string
*/
protected $content;
/**
* Destinatário
* @var string
*/
protected $from;
/**
* Construct
*/
public function __construct(){
$this->to = new \ArrayObject(array());
$this->headers = new \ArrayObject(array(
"MIMETYPE" => "MIME-Version: 1.1",
"CHARSET" => "Content-Type: {$this->getContentType()}; charset=utf-8",
"RETURNPATH" => "Return-Path: [email] ",
"ERROSTO" => "Errors-To: [email]",
"REPLAYTO" => "Reply-To: [email]",
"XMAILER" => "X-Mailer: S9 INFORMATICA",
"PRIORITY" => array(
"X-Priority:" => "1 ",
"X-MSMail-Priority:" => "High",
"Importance:" => "High"
)
));
}
/**
* Obtém a Flag de definição se pode enviar conteúdo HTML
* @return boolean
*/
public function getHtmlEnable() {
return $this->htmlEnable;
}
/**
* Define se pode ser enviado conteudo HTML
* @param boolean $htmlEnable
*/
public function setHtmlEnable($htmlEnable=TRUE) {
$this->htmlEnable = $htmlEnable;
}
/**
* Retorna o Tipo do Conteúdo
* Se $htmlEnable for TRUE então TEXT/HTML se não TEXT/PLAIN
* @return string
*/
protected function getContentType(){
if($this->getHtmlEnable()){
return "text/html";
}
return "text/plain";
}
/**
* Obtém o assunto do Email
* @return string
*/
public function getSubject() {
return $this->subject;
}
/**
* Define o assunto do Email
* @param string $subject
*/
public function setSubject($subject) {
$this->subject = (string) $subject;
}
/**
* Obtém o conteúdo do Email
* @return string
*/
public function getContent() {
return $this->content;
}
/**
* Define o conteúdo do Email
* @param string $content
*/
public function setContent($content) {
$this->content = (string) $content;
}
/**
* Obtém uma coleção de Destinatários
* @return \ArrayObject
*/
public function getTo() {
return $this->to;
}
/**
* Define uma Coleção de Destinatários
* @param \ArrayObject $to
*/
public function setTo(\ArrayObject $to) {
$this->to = $to;
}
/**
* Obtém o Remetente
* @return string
*/
public function getFrom() {
return $this->from;
}
/**
* Define o Charset
* @param string $charset
*/
public function setCharset($charset=self::UTF8){
$this->addHeader("CHARSET","Content-Type: {$this->getContentType()}; charset={$charset}");
}
/**
* Define o Remetente
* @param string $from
*/
public function setFrom($from) {
$this->from = strip_tags($from);
$this->addHeader("FROM","From: {$this->from}");
}
/**
* Adiciona um Destinatário
* @param mixed $index
* @param string $value email
*/
public function addTo($index,$value){
$this->to->offsetSet($index,strip_tags($value));
}
/**
* Obtém Todos os Headers
* @return \ArrayObject
*/
public function getHeaders() {
return $this->headers;
}
/**
* Adiciona um Header
* @param string $index
* @param string $value
*/
protected function addHeader($index,$value){
$this->headers->offsetSet($index, $value);
}
/**
* Remover um Header
* @param string $index
*/
protected function removeHeader($index){
if($this->headers->offsetExists($index)){
$this->headers->offsetUnset($index);
}
}
/**
* Envia o Email
* @return boolean
*/
public function send(){
try{
#Definindo Destinatário
$to = implode(",",$this->getTo()->getArrayCopy());
#Definindo Headers
$oItHeaders = $this->getHeaders()->getIterator();
$headers = "";
while($oItHeaders->valid()){
$current = $oItHeaders->current();
if(is_array($current)){
foreach($current as $k=>$item){
$headers .= $k.$item."\r\n";
}
}else{
$headers .= str_replace("[email]",$this->getFrom(), $current)."\r\n";
}
$oItHeaders->next();
}
return $this->execute($to, $this->getSubject(), $this->getContent(), $headers);
}catch(\Exception $oException){
Logging::getInstance()->register("S9\PATTERN\EMAIL ERROR: [{$oException->getMessage()}]");
return false;
}
}
/**
* Realiza a ação de disparar o email
* @param string $to
* @param string $subject
* @param string $message
* @param string $headers
* @param string $params
* @return boolean
* @throws \Exception Se não conseguir disparar o email uma Exception e lançada
*/
protected function execute($to,$subject,$message,$headers,$params=null){
if(!mail($to, $subject, $message, $headers, $params)){
throw new \Exception("Erro no envio de email para [{$to}] , com assunto : {$subject}");
}
return true;
}
}<file_sep>/Pattern/FileUpload.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
/**
* Classe de Upload de Arquivos
*/
class FileUpload extends Controller{
/**
* Nome do arquivo
* @var string
*/
protected $name;
/**
* Arquivo de upload
* @var array
*/
protected $fileupload;
/**
* Caminho do Diretorio para Upload
* @var string
*/
protected $pathUpload;
/**
* Tamanho máximo do Arquivo
* @var int
*/
protected $size;
/**
* Exibe mensagem de Erro no Upload
* @var string
*/
protected $error;
/**
* Extensões permitidas
* @var \ArrayObject
*/
protected $extension;
/**
* Construct
* @param file|array $fileupload
*/
public function __construct($fileupload) {
parent::__construct();
$this->fileupload = $fileupload;
$this->name = $fileupload["name"];
}
/**
* Obtém nome do Arquivo feito upload
* @return string
*/
public function getName(){
return $this->name;
}
/**
* Define o nome do Arquivo feito upload
* @param string $name
*/
protected function setName($name){
$this->name = $name;
}
/**
* Obtém Instancia do Arquivo de upload
* @return file|array
*/
public function getFileUpload() {
return $this->fileupload;
}
/**
* Define Instancia do Arquivo de upload
* @param file|array $fileupload
*/
public function setFileUpload($fileupload) {
$this->fileupload = $fileupload;
}
/**
* Obtém o diretorio de upload dos arquivos
* @return string
*/
public function getPathUpload() {
return $this->pathUpload;
}
/**
* Define o diretorio de upload dos arquivos
* @param string $pathUpload
*/
public function setPathUpload($pathUpload) {
$this->pathUpload = $pathUpload;
}
/**
* Obtém o Tamanho Máximo para o Arquivo
* @return int
*/
public function getSize() {
return $this->size;
}
/**
* Define o Tamanho Máximo para o Arquivo
* @param int $size
*/
public function setSize($size) {
$this->size = $size;
}
/**
* Obtém a mensagem de eror do upload
* @return string
*/
public function getMessageError(){
return $this->error;
}
/**
* Define a mensagem de erro do upload
* @param string $error
*/
public function setMessageError($error){
$this->error = $error;
}
/**
* Obtém uma coleção de extensões permitidas
* @return \ArrayObject
*/
public function getExtension() {
return $this->extension;
}
/**
* Define uma coleção de extensões permitidas
* @param \ArrayObject $extension
*/
public function setExtension(\ArrayObject $extension) {
$this->extension = $extension;
}
/**
* Adiciona uma extensão permitida
* @param string|int $index
* @param string $extension
*/
public function addExtension($index,$extension){
$this->extension->offsetSet($index, $extension);
}
/**
* Obtém um extensão permitida
* @param string|int $index
* @return string
*/
public function getExtesion($index){
if($this->extension->offsetExists($index)){
return $this->extension->offsetGet($index);
}
}
/**
* Faz o Upload
*/
public function doUpload(){
try{
$file = $this->getFileUpload();
$extension = $this->getFileExtension();
$filename = base64_encode(rand(1,100).time()).".".$extension;
$this->setName($filename);
$result = move_uploaded_file($file["tmp_name"], $this->getPathUpload().DIRECTORY_SEPARATOR.$filename);
if(function_exists("chmod")){
if(is_callable("chmod")){
chmod(realpath($this->getPathUpload().DIRECTORY_SEPARATOR.$filename), 0755);
}
}
return $result;
}catch(\Exception $oException){
$this->getLog()->register($oException);
return false;
}
}
/**
* Verifica se ocorreu algum erro
* @return boolean
* @throws \Exception
*/
public function check(){
try{
if($this->isValid()){
if($this->checkSize()){
if($this->checkExtension()){
if($this->checkMimeTypes()){
return true;
}else{
$this->checkError();
throw new \Exception("Error in file type");
}
}else{
$this->checkError();
throw new \Exception("Error in type extension");
}
}else{
$this->checkError();
throw new \Exception("Error oversized");
}
}else{
$this->checkError();
throw new \Exception("Error loading");
}
return false;
}catch(\Exception $oException){
throw new \Exception($oException->getMessage());
return false;
}
}
/**
* Verifica se é o upload e válido
* @return boolean
*/
public function isValid(){
$file = $this->getFileUpload();
return is_uploaded_file($file['tmp_name']);
}
/**
* Verifica o error do upload e define a mensagem de erro.
* @param file $file
* @return boolean
*/
public function checkError(){
$file = $this->getFileUpload();
$error = ( ! isset($file['error'])) ? 4 : $file['error'];
switch ($error){
case UPLOAD_ERR_INI_SIZE:
$this->setMessageError('upload_file_exceeds_limit');
break;
case UPLOAD_ERR_FORM_SIZE:
$this->setMessageError('upload_file_exceeds_form_limit');
break;
case UPLOAD_ERR_PARTIAL:
$this->setMessageError('upload_file_partial');
break;
case UPLOAD_ERR_NO_FILE:
$this->setMessageError('upload_no_file_selected');
break;
case UPLOAD_ERR_NO_TMP_DIR:
$this->setMessageError('upload_no_temp_directory');
break;
case UPLOAD_ERR_CANT_WRITE:
$this->setMessageError('upload_unable_to_write_file');
break;
case UPLOAD_ERR_EXTENSION:
$this->setMessageError('upload_stopped_by_extension');
break;
default:
$this->setMessageError('upload_no_file_selected');
break;
}
return FALSE;
}
/**
* Verifica se a extensão do arquivo esta entre as extensões permitidas
* @param file $file
* @return boolean
*/
public function checkExtension(){
$extension = $this->getFileExtension();
$colExtension = $this->getExtension()->getArrayCopy();
return in_array($extension, $colExtension);
}
/**
* Obtém a extensão do arquivo
* @return string
*/
public function getFileExtension(){
$file = $this->getFileUpload();
return strtolower(end(explode('.', $file['name'])));
}
/**
* Verifica o mime type do arquivo
* @return boolean
*/
public function checkMimeTypes(){
$fileExtension = $this->getFileExtension();
$fileMimeType = $this->getMimeTypeFile();
$oIMines = $this->getMimeTypes()->getIterator();
$oIExtension = $this->getExtension()->getIterator();
$valid = new \ArrayIterator();
while($oIExtension->valid()){
$current = $oIExtension->current();
if($oIMines->offsetExists($current)){
$valid->offsetSet($current, $oIMines->offsetGet($current));
}
$oIExtension->next();
}
if($valid->offsetExists($fileExtension)){
$item = $valid->offsetGet($fileExtension);
if(is_array($item)){
if(in_array($fileMimeType,$item)){
return true;
}else{
$this->setMessageError("error_mime_type");
return false;
}
}else{
if($fileMimeType == $item){
return true;
}else{
$this->setMessageError("error_mime_type");
return false;
}
}
}else{
$this->setMessageError("error_mime_type");
return false;
}
}
/**
* Verifica o Tamanho do arquivo
* @return boolean
*/
public function checkSize(){
$file = $this->getFileUpload();
if($file["size"]<=$this->getSize()){
return true;
}
return false;
}
/**
* Obtém a Mime Type do Arquivo
* @return string
* @throws \Exception
*/
public function getMimeTypeFile() {
$file = $this->getFileUpload();
if (!function_exists("finfo_file")){
throw new \Exception("Erro resource finfo_file");
}
$manipulador = finfo_open(FILEINFO_MIME);
return array_shift(explode(";",finfo_file($manipulador, $file["tmp_name"])));
}
/**
* Obtém uma coleção de MimeTypes conhecidas
* @return \ArrayObject
*/
public function getMimeTypes() {
return new \ArrayObject(array(
'hqx' => array('application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'),
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'),
'bin' => array('application/macbinary', 'application/mac-binary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'),
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => array('application/octet-stream', 'application/x-msdownload'),
'class' => 'application/octet-stream',
'psd' => array('application/x-photoshop', 'image/vnd.adobe.photoshop'),
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/x-download', 'binary/octet-stream'),
'ai' => array('application/pdf', 'application/postscript'),
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/excel', 'application/download', 'application/vnd.ms-office', 'application/msword'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'),
'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-zip', 'application/zip'),
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => array('application/x-httpd-php', 'application/php', 'application/x-php', 'text/php', 'text/x-php', 'application/x-httpd-php-source'),
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => array('application/x-javascript', 'text/plain'),
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed', 'application/s-compressed', 'multipart/x-zip'),
'rar' => array('application/x-rar', 'application/rar', 'application/x-rar-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
'aif' => array('audio/x-aiff', 'audio/aiff'),
'aiff' => array('audio/x-aiff', 'audio/aiff'),
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'),
'bmp' => array('image/bmp', 'image/x-windows-bmp'),
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'png' => array('image/png', 'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => array('text/css', 'text/plain'),
'html' => array('text/html', 'text/plain'),
'htm' => array('text/html', 'text/plain'),
'shtml' => array('text/html', 'text/plain'),
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => array('application/xml', 'text/xml', 'text/plain'),
'xsl' => array('application/xml', 'text/xsl', 'text/xml'),
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => array('video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'),
'movie' => 'video/x-sgi-movie',
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip'),
'dot' => array('application/msword', 'application/vnd.ms-office'),
'dotx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip'),
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => array('application/json', 'text/json'),
'pem' => array('application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'),
'p10' => array('application/x-pkcs10', 'application/pkcs10'),
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7m' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => array('application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'),
'crl' => array('application/pkix-crl', 'application/pkcs-crl'),
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => array('application/pkix-cert', 'application/x-x509-ca-cert'),
'3g2' => 'video/3gpp2',
'3gp' => 'video/3gp',
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => 'video/mp4',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => array('video/x-ms-wmv', 'video/x-ms-asf'),
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => 'audio/ogg',
'kmz' => array('application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'),
'kml' => array('application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'),
'ics' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => array('application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'),
'cdr' => array('application/cdr', 'application/coreldraw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'),
'wma' => array('audio/x-ms-wma', 'video/x-ms-asf'),
'jar' => array('application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed')
));
}
}<file_sep>/Pattern/Filter.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
/**
* Classe Responsável por criar filtro de XSS e SQL
*/
class Filter{
/**
* Higienização a entrada input contra XSS e SQL
* @param mixed $input pode receber tanto string quanto um array
* @return mixed retorna o conteudo recebido em $input higienitizado
*/
public function sanitization($input){
if(is_array($input)){
foreach ($input as &$item){
$item = $this->sanitization($item);
}
return $input;
}
//Higienização
$input = str_replace("'", "'", $input);
$input = str_replace('"', '"', $input);
$input = str_replace('<', '<', $input);
$input = str_replace('>', '>', $input);
$input = str_replace('/', '/', $input);
$input = str_replace('\\', '\', $input);
$input = str_replace('*', '*', $input);
$input = str_replace('-', '-', $input);
$input = str_replace("javascript:", "", $input);
// $input = htmlentities($input, ENT_QUOTES);
return $input;
// return trim($this->xss_clean($input));
}
/**
* XSS filter
*
* This was built from numerous sources
* (thanks all, sorry I didn't track to credit you)
*
* It was tested against *most* exploits here: http://ha.ckers.org/xss.html
* WARNING: Some weren't tested!!!
* Those include the Actionscript and SSI samples, or any newer than Jan 2011
*
*
* TO-DO: compare to SymphonyCMS filter:
* https://github.com/symphonycms/xssfilter/blob/master/extension.driver.php
* (Symphony's is probably faster than my hack)
*/
public function xss_clean($data){
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
do
{
// Remove really unwanted tags
$old_data = $data;
$data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);
// we are done...
return $data;
}
/**
* A utility function to manage nested array structures, checking
* each value for possible XSS. Function returns boolean if XSS is
* found.
*
* @param array $array
* An array of data to check, this can be nested arrays.
* @return boolean
* True if XSS is detected, false otherwise
*/
protected function detectXSSInArray(array $array) {
foreach($array as $value) {
if(is_array($value)) {
return self::detectXSSInArray($value);
}
else {
if(self::detectXSS($value) === TRUE) return TRUE;
}
}
return FALSE;
}
/**
* Given a string, this function will determine if it potentially an
* XSS attack and return boolean.
*
* @param string $string
* The string to run XSS detection logic on
* @return boolean
* True if the given `$string` contains XSS, false otherwise.
*/
protected function detectXSS($string) {
$contains_xss = FALSE;
// Skip any null or non string values
if(is_null($string) || !is_string($string)) {
return $contains_xss;
}
// Keep a copy of the original string before cleaning up
$orig = $string;
// URL decode
$string = urldecode($string);
// Convert Hexadecimals
$string = preg_replace('!(&#|\\\)[xX]([0-9a-fA-F]+);?!e','chr(hexdec("$2"))', $string);
// Clean up entities
$string = preg_replace('!(�+[0-9]+)!','$1;',$string);
// Decode entities
$string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
// Strip whitespace characters
$string = preg_replace('!\s!','',$string);
// Set the patterns we'll test against
$patterns = array(
// Match any attribute starting with "on" or xmlns
'#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>?#iUu',
// Match javascript:, livescript:, vbscript: and mocha: protocols
'!((java|live|vb)script|mocha|feed|data):(\w)*!iUu',
'#-moz-binding[\x00-\x20]*:#u',
// Match style attributes
'#(<[^>]+[\x00-\x20\"\'\/])style=[^>]*>?#iUu',
// Match unneeded tags
'#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>?#i'
);
foreach($patterns as $pattern) {
// Test both the original string and clean string
if(preg_match($pattern, $string) || preg_match($pattern, $orig)){
$contains_xss = TRUE;
}
if ($contains_xss === TRUE) return TRUE;
}
return FALSE;
}
public function checkXSS($value){
if(is_array($value)){
return $this->detectXSSInArray($value);
}else{
return $this->detectXSS($value);
}
}
}<file_sep>/Pattern/Request.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
//use S9\Pattern\Filter;
/**
* Classe Request
*/
class Request{
/**
* Dados do Server
* @var \ArrayObject
*/
protected $data;
/**
* Valores recebidos no Request Http
* @var \ArrayObject
*/
protected $params;
/**
* Tipo de Iteração
* @var int ARRAYOBJECT
*/
const FECTH_ARRAY_OBJECT = 1;
/**
* Tipo de Iteração
* @var int ARRAY
*/
const FECTH_ARRAY = 2;
/**
* Construct
*/
public function __construct() {
$this->data = new \ArrayObject($_SERVER);
$this->params = new \ArrayObject(array_merge($_POST,$_GET,$_FILES,$_REQUEST));
$this->load();
}
/**
* Obtem um item da variavel Server
* @param int|string $index
* @return boolean
*/
public function getItem($index){
if($this->data->offsetExists($index)){
return $this->data->offsetGet($index);
}
return false;
}
/**
* Define um item na variavel Server
* @param int|string $index
* @param mixed $value
*/
public function setItem($index,$value){
$this->data->offsetSet($index, $value);
}
/**
* Obtem um param enviado via Request Http
* @param int|string $index
* @return mixed|boolean
*/
public function getParam($index){
if($this->params->offsetExists($index)){
return $this->params->offsetGet($index);
}
return false;
}
/**
* Define um param junto com os outros enviados via Request Http
* @param int|string $index
* @param mixed $value
*/
public function setParam($index,$value){
$this->params->offsetSet($index, urldecode($value));
}
/**
* Obtem todos os parametros enviados via Request Http
* @return \ArrayObject
*/
public function getAllParams($fetchMode=Request::FECTH_ARRAY_OBJECT){
$params = $this->params->getArrayCopy();
return $this->fetchMode($this->checkItem($params),$fetchMode);
}
/**
* Obtém Todos os Parametros Recebidos por POST
* @return \ArrayObject
*/
public function getPostParams($fetchMode=Request::FECTH_ARRAY){
return $this->fetchMode($this->checkItem($_POST),$fetchMode);
}
/**
* Obtém Todos os Parametros Recebidos por $_GET
* @return \ArrayObject
*/
public function getGetParams($fetchMode=Request::FECTH_ARRAY){
return $this->fetchMode($this->checkItem($_GET),$fetchMode);
}
/**
* Obtém Todos os Parametros Recebidos por $_FILES
* @return \ArrayObject
*/
public function getFilesParams($fetchMode=Request::FECTH_ARRAY){
return $this->fetchMode($this->checkItem($_FILES),$fetchMode);
}
/**
* Realiza um Fecth com tipo passado.
* @param array $data
* @param int $fecthMode
* @return \ArrayObject|array
*/
private function fetchMode(array $data,$fecthMode=Request::FECTH_ARRAY){
if($fecthMode==Request::FECTH_ARRAY_OBJECT){
return new \ArrayObject($data);
}
return $data;
}
/**
* Carrega os dados das variaveis Globais
*/
public function load(){
$uri = $this->getItem("REQUEST_URI");
$default = array("MODULE","CONTROLLER","ACTION");
//Removendo Sujeira da URL
$uri = str_replace("&", "/", $uri);
$uri = str_replace("?", "/", $uri);
$uri = str_replace("=", "/", $uri);
$explodeURI = explode("/",$uri);
//Eliminando Elementos Vazios do Request, causados por /
$explodeURI = array_filter($explodeURI);
if(!empty($explodeURI)){
$explodeURI = array_combine(range(0, count($explodeURI)-1),$explodeURI);
}
$total = (count($explodeURI)>3) ? count($explodeURI) : count($default);
for($i=0;$i<$total;$i++){
if($i<=2){
if(isset($explodeURI[$i])){
$this->setItem($default[$i], $this->checkItem($explodeURI[$i]));
}else{
$this->setItem($default[$i], null);
}
}else{
$param = $this->checkItem($explodeURI[$i]);
if(isset($explodeURI[$i+1])){
$value = $this->checkItem($explodeURI[$i+1]);
}else{
$value = null;
}
$this->setParam($param, $value);
$i++;
}
}
}
/**
* Checa se o item não está em branco se estiver seta com null
* @param array|string $item
* @return null
*/
private function checkItem($item){
if(is_array($item)){
foreach ($item as &$i){
$i = $this->checkItem($i);
}
return $item;
}
if(is_numeric($item) && $item==0){
return 0;
}
if(!empty($item)){
return trim($item);
}else{
return null;
}
}
/**
* Verifica se é GET
* @return boolean retorna TRUE se for GET FALSE se não for
*/
public function isGet(){
return ($this->getItem("REQUEST_METHOD")=="GET")? TRUE : FALSE;
}
/**
* Verifica se é POST
* @return boolean retorna TRUE se for POST FALSE se não for
*/
public function isPost(){
return ($this->getItem("REQUEST_METHOD")=="POST")? TRUE : FALSE;
}
/**
* Verifica se é Ajax
* @return boolean retorna TRUE se for Ajax FALSE se não for
*/
public function isAjax(){
$flag = $this->getItem("HTTP_X_REQUESTED_WITH");
if(!empty($flag) && strtolower($flag) == "xmlhttprequest"){
return TRUE;
}else{
return FALSE;
}
}
/**
* Obtém a URI da Requisição
* @return string
*/
public function getURI(){
return $this->getItem("REQUEST_URI");
}
}<file_sep>/Pattern/FrontController.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
use \S9\Pattern\Controller,
\S9\Pattern\Router,
\S9\Pattern\Logging as Logging;
/**
* Classe FrontController
*/
class FrontController extends Controller{
/**
* Construct
*/
public function __construct(\S9\Pattern\Request $oRequest = null) {
parent::__construct($oRequest);
}
/**
* Método Main
* @throws \Exception Se ação não existir ou ocorrer algum erro no Request
*/
public function index(){
try{
$oRouter = new Router();
$oRequest = $oRouter->analyzer($this->getRequest());
if($oRequest instanceof Request){
$classController = $oRequest->getItem("CONTROLLER");
$objectController = new $classController($oRequest);
$action = $oRequest->getItem("ACTION");
if(in_array($action, get_class_methods($classController))){
$objectController->$action();
}else{
throw new \Exception("Ops! Ação não pode ser realizada. [URL:{$this->getRequest()->getItem("REQUEST_URI")}] ");
}
}else{
throw new \Exception("Ops! Error Modulo ou Controller não existe. [URL:{$this->getRequest()->getItem("REQUEST_URI")}] ");
}
}catch (\Exception $oException){
$this->getLog()->register($oException->getMessage(),Logging::ERR);
$this->redirect("/error404");
}
}
}<file_sep>/Pattern/View.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
use S9\Pattern\Logging;
/**
* Classe View
*/
class View{
/**
* Diretorios de Views
* @var \ArrayObject
*/
protected $paths;
/**
* Coleção de Texto de Idioma
* @var \ArrayObject
*/
protected $language;
/**
* Construct
*/
public function __construct(){
$this->paths = new \ArrayObject(array());
}
/**
* Obtém a Coleção de Textos para o Idioma definido
* @return \ArrayObject
*/
public function getLanguage(){
if(is_null($this->language)){
$this->language = new \ArrayObject($this->getConfigs('language'));
}
return $this->language;
}
/**
* Obter Configurações
* @return array
*/
public function getConfigs($item){
if(empty($item)){
return FALSE;
}
if(!file_exists(S9_APP_PATH."/configs/{$item}.php")){
return new \ArrayObject(array());
}
return include(S9_APP_PATH."/configs/{$item}.php");
}
/**
* Obtem uma lista de diretorios de views
* @return \ArrayObject
*/
public function getPaths() {
return $this->paths;
}
/**
* Define uma lista com diretorios de views
* @param \ArrayObject $paths
*/
public function setPaths($paths) {
$this->paths = $paths;
}
/**
* Obtem o caminho de um diretorio
* @param string $index
* @return boolean
*/
public function getDirectory($index){
if($this->paths->offsetExists($index)){
return $this->paths->offsetGet($index);
}
return false;
}
/**
* Define uma caminho para um diretorio
* @param string $index
* @param string $value
*/
public function setDirectory($index,$value){
$this->paths->offsetSet($index, $value);
}
/**
* Load - carrega uma view para o buffer interno de saída.
* @param $filename String Nome do Arquivo que deve ser carregado
* @param $vars_views Array Coleção de variaveis que vai ser repassado para a view.
* @return String Retorna o que foi carregado para buffer de saída.
*/
public function load($filename,$vars_views=array(),$extension=".php"){
ob_start();
$this->renderizar($filename, $vars_views,$extension);
$buffer = ob_get_contents();
@ob_end_clean();
return $buffer;
}
/**
* Renderizar - Ao contrario do Load, carrega uma view, mas não impede a saída do buffer.
* @param $filename String Nome do Arquivo que deve ser carregado
* @param $vars_views Array Coleção de variaveis que vai ser repassado para a view.
* @param $extnsion Extensão do Arquivo.
* @return boolean Retorna False em caso de Error e Printa conteúdo em caso de Sucesso.
*/
public function renderizar($view,$vars_views=array(),$extension=".php"){
try{
if(is_array($vars_views)){
$vars_views["oLanguage"] = $this->getLanguage();
$vars_views["oFilter"] = new Filter();
extract($vars_views);
}
$no_exists = true;
$oIteraitor = $this->getPaths()->getIterator();
while($oIteraitor->valid()){
$filename = $oIteraitor->current().DIRECTORY_SEPARATOR.$view.$extension;
if(file_exists($filename)){
echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($filename))));
$no_exists = false;
break;
}
$oIteraitor->next();
}
if($no_exists){
throw new \Exception("#404 - File not found. XP [{$filename}]");
}
}catch(\Exception $oException){
$this->getLog()->register($oException->getMessage(), Logging::CRIT);
return false;
}
}
/**
* Obtem a Instancia de Logging passando as configurações de acesso ao bd
* @param array $config configurações de acesso ao bd são obrigadorias apenas da primeira vez.
* @throws \Exception se na primeira vez que esse método for chamado não for passado os dados de configuração.
* @return \S9\Pattern\Logging Retorna uma instancia de Logging
*/
protected function getLog(){
return Logging::getInstance();
}
/**
* Cria o Elemento Páginadorq
* @param int $totalDeRegistros
* @param int $numeroPorPagina
* @param int $numeroDaPagina
* @return string Retorna o HTML com o Paginador montador
*/
public function paginador($totalDeRegistros,$numeroPorPagina,$numeroDaPagina,$limite=null,$inicio_fim=false){
try{
$inicio = $fim = $anterior = $proxima = "";
$max_paginas = $paginas = ceil($totalDeRegistros/$numeroPorPagina);
if(!is_null($limite) && $limite<$paginas ){
$anterior = $pagina - 1;
$anterior = "<li><a href=?pg={$anterior}>Anterior</a></li>";
$proximo = $pagina + 1;
$proximo = "<li><a href=?pg={$proximo}>Próximo</a></li>";
$paginas = $limite + ($pagina-1);
$p = $pagina;
}else{
$p = 1;
}
if($inicio_fim){
$inicio = "<li><a href=?pg=1><i class=\"icon-fast-backward\"></i></a></li>";
$fim = "<li><a href=?pg={$max_paginas}><i class=\"icon-fast-forward\"></i></a></li>";
}
$pagination = "<div class=\"pagination\"><ul>";
if($p!=1){
$pagination .= $inicio;
$pagination .= $anterior;
}
for(;$p<=$paginas && $p<=$max_paginas;$p++){
$pagination .= "<li";
$pagination .= ($p==$pagina) ? " class=\"active\">" : ">";
$pagination .= "<a href='?pg={$p}'>{$p}</a></li>";
}
if($max_paginas - $pagina >= $limite){
$pagination .= $proximo;
$pagination .= $fim;
}
$pagination .= "</ul>";
return $pagination;
}catch(\Exception $oException){
$this->getLog()->register($oException->getMessage(),Logging::ERR);
echo $oException->getMessage();
}
}
/**
* Monta o conteudo de um elemento Select (<select>) recebendo por parametro um array com os options
* @param array $arrayDeOptions
* @param arraykeys
* @return string
*/
public function montarSelect(array $arrayDeOptions,$selecionado=null,$arraykeys=null){
$return = "";
if(is_null($arraykeys)){
$arraykeys = array('0','1');
}
if(is_null($selecionado)){
$selecionado = array(0);
}else{
if(!is_array($selecionado)){
$selecionado = array($selecionado);
}
}
foreach($arrayDeOptions as &$registro){
$return .= "<option value='".$registro[$arraykeys[0]];
if(in_array($registro[$arraykeys[0]], $selecionado)){
$return .= "' selected=\"selected\">";
}else{
$return .= "'>";
}
$return .= $registro[$arraykeys[1]]."</option>";
}
return $return;
}
public function montarGroupRadios(array $arrayDeRadios,$name,$selecionado=null){
$return = "";
if(empty($arrayDeRadios)){
return false;
}
if(is_null($name) || empty($name)){
return false;
}
$id = "options".ucwords($name);
if(is_null($selecionado)){
$selecionado = 0;
}
$loop = count($arrayDeRadios);
for($i=0;$i<$loop;$i++){
$return .= "<label class=\"radio\">";
$return .= "<input type=\"radio\" name=\"{$name}\" id=\"{$id}{$i}\" value=\"{$i}\"";
if($i==$selecionado){
$return .= " checked=\"checked\" />";
}else{
$return .= "/ >";
}
$return .= $arrayDeRadios[$i];
$return .= "</label>";
}
return $return;
}
/**
* Faz load de $filename para uma tag style, $filename pode ser um arquivo ou um array de arquivos
* @param string|array $filename Nome do Arquivo
* @example $filename Pode ser um arquivo ou um array de arquivos
* $filename = "css/my_style";
* $filename = array("css/my_style","css/animation","css/defaut_site","...");
* @param string $media Tipo de Mídia
* @link http://www.w3schools.com/tags/tag_style.asp Detalhes da Tag de Style
* @link http://www.w3schools.com/tags/att_style_media.asp Detalhes sobre o Atributo Media
* @example $media possiveis valores:
* all Default. Suitable for all devices
* aural Speech synthesizers
* braille Braille feedback devices
* handheld Handheld devices (small screen, limited bandwidth)
* projection Projectors
* print Print preview mode/printed pages
* screen Computer screens
* tty Teletypes and similar media using a fixed-pitch character grid
* tv Television type devices (low resolution, limited scroll ability)
*/
public function cssInline($filename){
#Specifies the MIME type of the style sheet
$type = "text/css";
if(!is_array($filename)){
$filename = array($filename);
}
$final = "";
foreach($filename as $item){
$final .= $this->load($item,null,".css");
}
$tag_style = "<style type='{$type}'>";
$tag_style .= $final;
$tag_style .= "</style>";
return $tag_style;
}
/**
* Faz load de $filename para uma tag script, $filename pode ser um arquivo ou um array de arquivos
* @param string|array $filename Nome do Arquivo
* @param string $charset Tipo de codificação suportada, por padrão é UTF-8.
* Existe a possibilidade de carregar js com codificação ISO-8859-1.
* @link http://www.w3schools.com/tags/att_script_charset.asp Descrição dos charsets suportados
* @param string $type MIME TYPE do arquivo, por padrão é text/javascript,
* mas pode existir a necessidade de carregar outro MIME TYPE. verifique as
* referências.
* @link http://www.w3schools.com/tags/att_script_type.asp Descrição dos MIME TYPES suportados
* @example $type MIME TYPES disponiveis para js:
* text/javascript (this is default)
* text/ecmascript
* application/ecmascript
* application/javascript
* text/vbscript
*/
public function jsInline($filename,$charset="UTF-8",$type="text/javascript"){
if(!is_array($filename)){
$filename = array($filename);
}
$final = "";
foreach($filename as $item){
$final .= $this->load($item,null,".js");
}
$tag_script = "<script type='{$type}' charset='{$charset}'>";
$tag_script .= $final;
$tag_script .= "</script>";
return $tag_script;
}
}<file_sep>/Pattern/Logging.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
/**
* Classe Logging
* - Funciona como Wrap para o Zend_Log com Zend_Log_Write_Db
*/
final class Logging{
/**
* A Instancia do Objeto criado
* @var \S9\Pattern\Session
*/
protected static $instance;
const EMERG = 0; // Emergency: system is unusable
const ALERT = 1; // Alert: action must be taken immediately
const CRIT = 2; // Critical: critical conditions
const ERR = 3; // Error: error conditions
const WARN = 4; // Warning: warning conditions
const NOTICE = 5; // Notice: normal but significant condition
const INFO = 6; // Informational: informational messages
const DEBUG = 7; // Debug: debug messages
/**
*
* @var array
*/
protected $config;
/**
* Construct
* @param array $config
*/
protected function __construct(array $config = array()) {
$this->config = $config;
}
/**
* Obtem a Instancia de Logging
* @return \S9\Pattern\Logging
*/
public static function getInstance(array $config = array()){
if(!isset(self::$instance)){
if(empty($config)){
$config = include_once(S9_APP_PATH.DIRECTORY_SEPARATOR."configs".DIRECTORY_SEPARATOR."log.php");
}
self::$instance = new self($config);
}
return self::$instance;
}
/**
* Obtem um objeto Adapter Abstract para realizar consultas.
* @return \Zend_Db_Adapter_Abstract
*/
protected function getAdapter(){
$config = $this->config;
return \Zend_Db::factory($config[S9_APP_ENV]['adapter'], $config[S9_APP_ENV]['params']);
}
/**
* Obtem um objeto Write Db
* @return \Zend_Log_Writer_Db
*/
protected function getWriteLog(){
$columnMapping = array('priority'=>'priority','message'=> 'message','date_time_create'=>'timestamp');
return new \Zend_Log_Writer_Db($this->getAdapter(),'logging',$columnMapping);
}
/**
* Obtem um objeto Zend_Log
* @return \Zend_Log
*/
protected function getLog(){
$logger = new \Zend_Log($this->getWriteLog());
$logger->setTimestampFormat("d/m/Y H:i:s");
return $logger;
}
/**
* Registra um Log de acordo com a prioridade
* @param string $message
* @param int $priority
*/
public function register($message, $priority=Logging::DEBUG){
$oLogger = $this->getLog();
$oLogger->log($message, $priority);
}
}<file_sep>/tests/index.php
<?php
require_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."Pattern".DIRECTORY_SEPARATOR."Filter.php");
$time = microtime(true);
$attacks = file(dirname(__FILE__).DIRECTORY_SEPARATOR.'xss');
$oFilter = new \S9\Pattern\Filter();
$asserts = $falses = $line = 0;
foreach($attacks as $attack){
if(!empty($attack)){
$line++;
$result = $oFilter->checkXSS($attack);
($result)? $asserts++: $falses++;
print ($result)? ".": "F";
}
}
$time2 = microtime(true);
print "\nN. Testes:\t\t".$line;
print "\nAcertos:\t\t".$asserts;
print "\nErros:\t\t\t".$falses;
print "\n% Cobertura:\t\t". (($asserts*100)/$line). " %";
print "\nTempo:\t\t\t".($time2 - $time)." segs";
print "\nUso de RAM:\t\t".((memory_get_usage(TRUE))/1024)."kb\n\n";<file_sep>/Pattern/CURL.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
/**
* Classe CURL é um Wrapper para o recurso curl_* do php
* O PHP suporta libcurl, uma biblioteca criada por <NAME>,
* que permite que você conecte-se e comunique-se com diferentes tipos de servidor
* usando diferentes tipos de protocolos. libcurl atualmente suporte os protocolos
* http, https, ftp, gopher, telnet, dict, file, e ldap. libcurl também suporta
* certificados HTTPS, HTTP POST, HTTP PUT, upload via FTP (podendo também ser
* feito com a extensão ftp do PHP), upload HTTP por formulário, proxies,
* cookies, e autenticação com usuário e senha.
*/
class CURL{
protected $instance;
public function __construct(){
if(!function_exists('curl_init')){
throw new \BadFunctionCallException("DEPENDÊNCIAS NÃO INSTALADAS, POR FAVOR VERIFIQUE.");
}
}
/**
* Define um parametro para envio na comunicação
* @param resource $option Option deve ser um resource válido para CURL
* verifique no link http://www.php.net/manual/pt_BR/function.curl-setopt.php
* tipos de resource válidos como argumento para está função
* @param string|int $value
* @return boolean
*/
public function setOption($option,$value){
try{
return curl_setopt($this->instance, $option, $value);
}catch(\Exception $oException){
error_log("Erro na definição de Opções do S9\Patter\Curl. Erro:".$oException->getMessage());
return false;
}
}
/**
* Executa e retorna o conteúdo recebido
* @return string
*/
public function execute(){
return curl_exec($this->instance);
}
/**
* Inicia uma comunicação
*/
public function begin(){
$this->instance = curl_init();
}
/**
* Finaliza uma comunicação
*/
public function end(){
curl_close($this->instance);
}
}
<file_sep>/README.md
S9
======
@description Respositorio de classes de utilização padrão da S9 Informática. Código gerados e padronizados pela equipe.
@requirements PHP 5.3.+
@version alpha
@features MVC, ACL, LOG, DAO[ORM Simples (1-1)], Interfaces Business, Route.
<file_sep>/DB/Logging/logging.sql
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS;
DROP SCHEMA IF EXISTS `s9inf297_logging` ;
CREATE SCHEMA IF NOT EXISTS `s9inf297_logging` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
SHOW WARNINGS;
USE `s9inf297_logging` ;
-- -----------------------------------------------------
-- Table `s9inf297_logging`.`s9inf297_logging`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `s9inf297_logging`.`logging` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`priority` INT NOT NULL ,
`message` TEXT NOT NULL COMMENT 'EMERG = 0; // Emergency: system is unusable\nALERT = 1; // Alert: action must be taken immediately\nCRIT = 2; // Critical: critical conditions\nERR = 3; // Error: error conditions\nWARN = 4; // Warning: warning conditions\nNOTICE = 5; // Notice: normal but significant condition\nINFO = 6; // Informational: informational messages\nDEBUG = 7; // Debug: debug messages' ,
`date_time_create` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
SHOW WARNINGS;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/Pattern/Router.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
use \S9\Pattern\Request,
\S9\Model\DAO;
/**
* Classe Router
*/
class Router{
/**
* Resource
* @var \S9\Model\DAO|\ArrayObject
*/
protected $resources;
/**
* Construct
*/
public function __construct(){
$resources = $this->getConfigs();
if($resources instanceof DAO){
$this->resources = $resources;
}else if(is_array($resources)){
$this->resources = new \ArrayObject($resources);
}else{
throw new \InvalidArgumentException("Arquivo de configuração da Route incorreto ou não criado.");
}
}
/**
* Obtem uma Rota a partir do indice
* @param string $index
* @return string|boolean
*/
public function get($index){
if($this->resources instanceof \S9\Model\DAO){
$oAdapter = $this->resources->getAdapter();
return $oAdapter->fetchRow(
$oAdapter->quoteInto("SELECT a.name AS 'ALIAS',
r.module AS 'MODULE',
r.controller AS 'CONTROLLER',
r.action AS 'ACTION',
r.params AS 'PARAMS',
r.permission AS 'PERMISSION'
FROM alias a, route r
WHERE a.id = r.id_alias AND a.name = ?", strtolower($index)));
}else if($this->resources instanceof \ArrayObject){
if($this->resources->offsetExists($index)){
return $this->resources->offsetGet($index);
}
return false;
}else{
return false;
}
}
/**
* Define uma Rota relacionada com um indice
* @param string $index
* @param string $value
*/
public function add($index,$value){
$this->resources->offsetSet($index, $value);
}
/**
* Obtem as rotas cadastradas no arquivo de configuração
* @return mixed
*/
public function getConfigs(){
return include S9_CONFIG_PATH . '/router.php';
}
/**
* Analise a url comparando se existe uma roda cadastrada. retorna um
* Request tratado
* @param \S9\Pattern\Request $oRequest
* @return \S9\Pattern\Request tratado
*/
public function analyzer(Request $oRequest){
$URI = $oRequest->getURI();
$route = $this->get($URI);
#Não é uma Route válido
if(!$route){
$controller = implode("\\",array($oRequest->getItem("MODULE"),"Controller",array_shift(array_reverse(explode("\\",$oRequest->getItem("CONTROLLER"))))));
if(!class_exists($controller)){
$oRequest->setItem("MODULE", "Padrao");
$oRequest->setItem("CONTROLLER", "Padrao\Controller\Error");
$oRequest->setItem("ACTION", "error404");
return $oRequest;
}else{
$oRequest->setItem("CONTROLLER", $controller);
}
if(!$oRequest->getItem("ACTION")){
$oRequest->setItem("ACTION","index");
}
return $oRequest;
}else{
$controller = implode("\\",array($route["MODULE"],"Controller",$route["CONTROLLER"]));
if(!class_exists($controller)){
$oRequest->setItem("MODULE", "Padrao");
$oRequest->setItem("CONTROLLER", "Padrao\Controller\Error");
$oRequest->setItem("ACTION", "error404");
return $oRequest;
}else{
$oRequest->setItem("MODULE", $route["MODULE"]);
$oRequest->setItem("CONTROLLER", $controller);
$oRequest->setItem("ACTION", $route["ACTION"]);
if(isset($route["PARAMS"])){
$route["PARAMS"] = unserialize($route["PARAMS"]);
foreach($route["PARAMS"] as $key=>$value){
$oRequest->setParam($key, $value);
}
}
if(isset($route["PERMISSION"])){
$route["PERMISSION"] = unserialize($route["PERMISSION"]);
$oRequest->setItem("PERMISSION", $route["PERMISSION"]);
}
return $oRequest;
}
}
}
}<file_sep>/Interfaces/iMapperEngine.php
<?php
namespace S9\Interfaces;
interface iMapperEngine{
/**
* Set Map class business
* @param string $index name class business
* @param array $map array with mapping
*/
public function setMap($index, array $map);
/**
* Get Map to business or dao
* @param string $index
* @param array $map
*/
public function getMapTo($index,$to);
/**
*
* @param string $class
* @param array $map
* @param array $values
* @return \class
*/
public function getObject($class,$map,$values);
/**
*
* @param array $map
* @param array $values
* @return array
*/
public function getRegister($map,$values);
}<file_sep>/Pattern/Session.php
<?php
/**
* @package S9\Pattern
*/
namespace S9\Pattern;
use S9\Pattern\Request;
/**
* Classe de Representação da Session no PHP
* - Implementa Design Pattern Singleton, objeto deve ser obtido pelo método getInstance()
*/
final class Session{
/**
* A Instancia do Objeto criado
* @var \S9\Pattern\Session
*/
protected static $instance;
/**
* A Identificação da Sessao
* @var int
*/
protected $id;
/**
* Path do caminhao de armazenamento dos arquivos Sessions
* @var string
*/
protected $sessionPath;
/**
* Path do caminhao de armazenamento dos arquivos cookies
* @var string
*/
protected $sessionCookiePath;
/**
* Nome da Session
* @var string
*/
protected $sessionName;
/**
* Tempo de Expiração do Cache da Session
* @var int valor em minutos
*/
protected $sessionCacheExpire;
/**
* Configuraçẽos de Sessão
* @var array
*/
protected $configs;
/**
* Construct
* @throws \Exception Lança uma Exception se não conseguiu iniciar a sessão
*/
protected function __construct() {
$this->boot();
$start = session_start();
if(!$start){
throw new \Exception("Sessão não pode ser inicializada.");
}
$this->id = session_id();
$this->setValue("time",time());
}
/**
* Destroi a Sessão
* @return boolean
*/
public function destruct(){
return session_destroy();
}
/**
* Obtem a Instancia de Session
* @return \S9\Pattern\Session
*/
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
/**
* Carregas as Configurações de Sessão da Aplicação
* @return array
*/
public function getConfigs(){
if(is_null($this->configs)){
$this->configs = $config = include_once(S9_APP_PATH.DIRECTORY_SEPARATOR."configs".DIRECTORY_SEPARATOR."config.php");
if(isset($this->configs["SESSION"])){
$this->configs = $this->configs["SESSION"];
}
}
return $this->configs;
}
/**
* Armaneza um valor na Session
* @param int|string $index Um indice que faz referencia ao valor para futura recuperação
* @param mixed $value Qualquer valor que deseje guardar
*/
public function setValue($index,$value){
$_SESSION[$index] = base64_encode(serialize($value));
}
/**
* Obtem o valor armazenado anteriormente de acordo com indice que definiu
* @param int|string $index indice de para localização do valor
* @return mixed|boolean em caso de sucesso retorna o conteudo armazenado em caso de falha retorna false.
*/
public function getValue($index){
if(isset($_SESSION[$index]) && !empty($_SESSION[$index])){
return unserialize(base64_decode($_SESSION[$index]));
}
return false;
}
/**
* Elimia um valor armazenado a partir do indice que foi guardado.
* @param int|string $index
* @return void
*/
public function clearValue($index){
unset($_SESSION[$index]);
}
/**
* Obtem identificação da Session
* @return int
*/
public function getId() {
return (int) $this->id;
}
/**
* Define a identificação da Session
* @param int $id
*/
public function setId($id) {
$this->id = (int) $id;
}
/**
* Carrega as configurações inicias definidas no php.ini
*/
protected function boot(){
$oRequest = new Request();
$configs = $this->getConfigs();
$sessionName = md5($configs["key"].$oRequest->getItem("REMOTE_ADDR").$oRequest->getItem("HTTP_USER_AGENT"));
$sessionPath = (isset($configs["save_path"])) ? $configs["save_path"] : ini_get('session.save_path');
$sessionCookiePath = (isset($configs["cookie_path"])) ? $configs["cookie_path"] : ini_get('session.cookie_path');
$sessionCacheExpire = (isset($configs["cache_expire"])) ? $configs["cache_expire"] : ini_get('session.cache_expire');
$this->setSessionName($sessionName);
$this->setSessionPath($sessionPath);
$this->setSessionCookiePath($sessionCookiePath);
$this->setSessionCacheExpire($sessionCacheExpire);
#Desabilita o Acesso via Javascript aos Cookies da Sessions
#http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly
$this->defineParams("session.cookie_httponly",TRUE);
}
/**
* Define Parametros de Inicialiazação da Session
* @param string $index
* @param midex $value
* @return boolean
*/
protected function defineParams($index,$value){
return ini_set($index,$value);
}
/**
* Obtem o caminho do diretorio de armazenamento das Sessions
* @return string
*/
public function getSessionPath() {
return (string) $this->sessionPath;
}
/**
* Define o caminho do diretorio de armanzenamento das Sessions
* @param string $sessionPath caminho do diretorio para armanzenamento das Sessions
* @return void
*/
public function setSessionPath($sessionPath) {
$this->sessionPath = $sessionPath;
ini_set('session.save_path', $this->sessionPath);
}
/**
* Obtem o caminho do diretorio de armazenamento do cookie das Sessions
* @return string
*/
public function getSessionCookiePath() {
return (string) $this->sessionCookiePath;
}
/**
* Define o caminho do diretorio de armanzenamento do cookie das Sessions
* @param type $sessionCookiePath
*/
public function setSessionCookiePath($sessionCookiePath) {
$this->sessionCookiePath = $sessionCookiePath;
ini_set('session.cookie_path', $this->sessionCookiePath);
}
/**
* Obtem o nome da Session
* @return string
*/
public function getSessionName() {
return $this->sessionName;
}
/**
* Define o nome da Session
* @param string $sessionName
* @return void
*/
public function setSessionName($sessionName) {
$this->sessionName = $sessionName;
ini_set('session.name', $this->sessionName);
}
/**
* Obtem o tempo em minutos de expiração do cache da Session
* @return int
*/
public function getSessionCacheExpire() {
return $this->sessionCacheExpire;
}
/**
* Define o tempo em minutos da expiração do cache da Session
* @param int $sessionCacheExpire
*/
public function setSessionCacheExpire($sessionCacheExpire) {
$this->sessionCacheExpire = $sessionCacheExpire;
session_cache_expire($this->sessionCacheExpire);
}
/**
* Obtem o status da Sessão
* @return boolean
*/
public function getStatus(){
return (($this->getValue("time")+$this->getSessionCacheExpire())>time()) ? TRUE : FALSE;
}
}<file_sep>/Pattern/Controller.php
<?php
/**
* @package \S9\Pattern
*/
namespace S9\Pattern;
use \S9\Pattern\Request,
\S9\Pattern\Router,
\S9\Pattern\Logging;
/**
* Classe Controller
*/
class Controller{
/**
* Instancia do Request
* @var \S9\Pattern\Request
*/
protected $oRequest;
/**
* Instancia do Logging
* @var \S9\Pattern\Logging
*/
protected $oLog;
/**
* Configurações do Modulo
* @var string
*/
protected $module_config = null;
/**
* Construct
*/
public function __construct(Request $oRequest=null){
if(is_null($oRequest)){
$oRouter = new Router();
$this->oRequest = $oRouter->analyzer(new Request());
}else{
$this->oRequest = $oRequest;
}
}
/**
* Obtem o Request
* @return \S9\Pattern\Request
*/
public function getRequest() {
return $this->oRequest;
}
/**
* Define o Request
* @param \S9\Pattern\Request $oRequest
*/
public function setRequest(Request $oRequest) {
$this->oRequest = $oRequest;
}
/**
* Redireciona para a url passada
* @param string $url
*/
public function redirect($url){
header("location: ".$url);
exit;
}
/**
* Obtem a Instancia de Logging passando as configurações de acesso ao bd
* @param array $config configurações de acesso ao bd são obrigadorias apenas da primeira vez.
* @throws \Exception se na primeira vez que esse método for chamado não for passado os dados de configuração.
* @return \S9\Pattern\Logging Retorna uma instancia de Logging
*/
protected function getLog(){
return Logging::getInstance();
}
/**
* Apresenta uma mensagem de Erro e define um HEADER de acordo com o tipo
* informado.
* @param string $titulo Titulo da mensagem de apresentação
* @param string $mensagem Mensagem da apresentação
* @param int $type Número do HTTP Mensagem
* @return string Uma mensagem de erro montada.
*/
public function error($titulo=null,$mensagem="",$type=404){
$httpMessage = $this->getHttpMessage($type);
header($httpMessage);
$dados = array("titulo"=>$titulo);
if(is_null($titulo)){
$dados["titulo"] = $httpMessage;
}
$dados["mensagem"] = $mensagem;
return $this->getView()->renderizar('Error/error',$dados);
}
/**
* Retorna um mensagem de acordo com o código do HTTP
* @param int $status
* @return string
*/
public function getHttpMessage($status){
$http = array(
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',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
$message = "HTTP/1.1: ";
if(array_key_exists($status, $http)){
$message.= "{$status} ".$http[$status];
}else{
$message.= "500 ".$http[500];
}
return $message;
}
/**
* Obtem um objeto View
* @return \S9\Pattern\View
*/
protected function getView(){
$oView = new View();
$oView->setDirectory("APP",S9_APP_PATH."/view/");
$oView->setDirectory("Padrao", S9_MODULE_PATH."/Padrao/View");
return $oView;
}
/**
* Obter Configurações
* @return array
*/
public function getConfigs($item){
if(empty($item)){
return FALSE;
}
if(!is_null($this->module_config)){
return include(S9_MODULE_PATH."/{$this->module_config}/configs/{$item}.php");
}
return include(S9_APP_PATH."/configs/{$item}.php");
}
} | 96086cf1324a398d67d434c0dd7ff154f65a6199 | [
"Markdown",
"SQL",
"PHP"
] | 18 | PHP | avandrevitor/S9 | 4cc5f2d660b0822dbd532c7829ad580730ca83d6 | db9c67c7850f14f33f4e6c2c70faee92f06471cd |
refs/heads/master | <repo_name>yldzoguzkaan/LabirentOyunu<file_sep>/main.c
#include <stdio.h>
#include <stdlib.h>
struct node{
int row;
int col;
struct node *next;
struct node *prew;
};
struct node* newNode(int i,int j){
struct node* dugum=(struct node*)malloc(sizeof(struct node));
dugum->row=i;
dugum->col=j;
dugum->next=NULL;
dugum->prew=NULL;
return dugum;
}
struct node* kok = NULL;
void addStack(struct node** kok,int i,int j){
struct node* dugum= newNode(i,j);
dugum->next=*kok;
dugum->prew=NULL;
*kok=dugum;
printf("(%d,%d) yoluna sahip dugum eklendi\n",i+1,j+1);
}
int isEmpty(struct node *kok){
return !kok;
}
void delStack(struct node** kok,int x,int y,int matris[x][y]){
if(isEmpty(*kok)){
printf("Cikis yolu yoktur!!\n");
writeMatris(x,y,matris);
return -1;
}
struct node* alinacak = *kok;
*kok = (*kok)->next;
//(*kok)->prew=*kok;
int alinani = alinacak->row;
int alinanj = alinacak->col;
printf("(%d,%d) yoluna sahip dugum alindi\n",alinani+1,alinanj+1);
free(alinacak);
}
void writeMatris(int x,int y,int matris[x][y]);
void isExit(int gX,int gY,int cX,int cY,int x,int y,int matris[x][y]);
void foundRotate(int x,int y,int matris[x][y],int gX,int gY,int cX,int cY);
int main()
{
srand(time(NULL));
int satir,sutun;
hata0:
printf("Matrisin satir sayisini girin:");
scanf("%d",&satir);
printf("Matrisin sutun sayisini girin:");
scanf("%d",&sutun);
if(satir>25 || sutun>25){
printf("Lutfen satir ve sutun sayisini 25'ten buyuk girmeyin!\n");
goto hata0;
}
int labirent[satir][sutun];
int i,j;
printf(" ");
for(i=0;i<sutun;i++){
printf(" %d",i+1);
}
printf("\n\n");
for(i=0;i<satir;i++){
printf("%-2d -->",i+1);
for(j=0;j<sutun;j++){
labirent[i][j]=rand()%2;
printf(" %d",labirent[i][j]);
}
printf(" <-- %2d",i+1);
printf("\n");
}
printf("\n\n");
printf(" ");
for(i=0;i<sutun;i++){
printf(" %d",i+1);
}
printf("\n\n");
int gX,gY;
int cX,cY;
printf("1'ler yol 0'lar duvardir!!\n");
hata1:
printf("Labirente satir giris degeri giriniz:");
scanf("%d",&gX);
gX--;
printf("Labirente sutun giris degeri giriniz:");
scanf("%d",&gY);
gY--;
if(labirent[gX][gY]==0){
printf("Duvardan giremezsin!!\n");
goto hata1;
}
hata3:
printf("Labirente satir cikis degeri giriniz:");
scanf("%d",&cX);
cX--;
printf("Labirente sutun cikis degeri giriniz:");
scanf("%d",&cY);
cY--;
if(labirent[cX][cY]==0){
printf("Duvardan cikamazsin!!\n");
goto hata3;
}
printf("gX=%d\ngY=%d\ncX=%d\ncY=%d\n",gX,gY,cX,cY);
/****/
int index=(gX*sutun)+gY;
labirent[gX][gY]=2;
foundRotate(satir,sutun,labirent,gX,gY,cX,cY);
return 0;
}
void foundRotate(int x,int y,int matris[x][y],int gX,int gY,int cX,int cY){
isExit(gX,gY,cX,cY,x,y,matris);
//sag
if(matris[gX][gY+1] == 1)
{
matris[gX][gY+1]=2;
addStack(&kok,gX,gY+1);
foundRotate(x,y,matris,gX,gY+1,cX,cY);
}
//asagi
if(matris[gX+1][gY] == 1)
{
matris[gX+1][gY]=2;
addStack(&kok,gX+1,gY);
foundRotate(x,y,matris,gX+1,gY,cX,cY);
}
//yukari
if(matris[gX-1][gY] == 1)
{
matris[gX-1][gY]=2;
addStack(&kok,gX-1,gY);
foundRotate(x,y,matris,gX-1,gY,cX,cY);
}
//sol
if(matris[gX][gY-1] == 1)
{
matris[gX][gY-1]=2;
addStack(&kok,gX,gY-1);
foundRotate(x,y,matris,gX,gY-1,cX,cY);
}
if(matris[gX+1][gY] != 1 && matris[gX][gY+1] != 1 && matris[gX-1][gY] != 1 && matris[gX][gY-1] != 1)
{
matris[gX][gY]=3;
delStack(&kok,x,y,matris);
}
}
void isExit(int gX,int gY,int cX,int cY,int x,int y,int matris[x][y]){
if(gX==cX && gY==cY){
printf("Cikisa geldin!\n");
writeMatris(x,y,matris);
}
}
void writeMatris(int x,int y,int matris[x][y]){
/**Matrisin yollu hali**/
int i,j;
for(i=0;i<x;i++){
for(j=0;j<y;j++){
printf("%5d",matris[i][j]);
}
printf("\n");
}
exit(1);
}
<file_sep>/readme.adoc
# LabirentOyunu
*Projenin amacı C dilinde, bağlantılı liste (link list) ve yığın (stack) kullanılarak rastgele oluşturulan labirentler üzerinden çıkışa ulaştıran kodun yazımıdır.*
Proje İsterleri: +
Kullanıcıdan matris boyutu (labirentin boyutu) istenilecektir. Matrisin maksimum boyutu ekranda görünecek kadar olmalıdır. +
Matris değerleri rastgele (1 veya 0) üretilecektir, 1 yol var 0 ise yol yok şeklinde olacaktır. +
Üretilen matris ekranda gösterilecektir. +
Kullanıcıdan labirentin giriş ve çıkış kapıları istenilecektir. +
Bağlantılı liste ve yığın kullanılarak çıkış yolu bulunmaya çalışılacaktır. Çıkış yolunun tespiti için yığın yapısı kullanarak labirent içinde dolaşması gerekmektedir. +
Bulunulan yol ekranda gösterilecek, yolun bulunamaması durumunda “yol yok” mesajı verilecektir. +
Labirent için grafiksel gösterim öğrencilere bağlıdır. Kullanıcı dostu bir arayüz olması değerlendirmeye etki edecektir. +
image::1.PNG[Giriş,width=75%]
| 9326835c729353c45c1141651f9988d1e2cb596f | [
"C",
"AsciiDoc"
] | 2 | C | yldzoguzkaan/LabirentOyunu | e5ef75f1ee9228e855b85b435f65a1a8ed8828e4 | 59faae7d7221efeb1e9dfeb205f338b4a0e8c8cb |
refs/heads/master | <file_sep>namespace Projeto.Dominio.Mercadorias.Entity
{
public enum MercadoriaTipo
{
Caixa = 1,
Galao = 2,
Tambor = 3,
Container = 4,
}
}<file_sep>using Projeto.Dominio.Veiculos.Entities;
using Projeto.Dominio.Veiculos.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Projeto.Dominio.Teste.Mocks
{
public class VeiculoMock : IVeiculoRepository
{
List<Veiculo> veiculos = new List<Veiculo>();
public VeiculoMock()
{
int tipo = 1;
for (int i = 0; i < 20; i++)
{
veiculos.Add(new Veiculo($"Veiculo {i + 1}", (VeiculoTipo)Enum.ToObject(typeof(VeiculoTipo), i), 60 * i + 1));
++tipo;
if (tipo == 5)
tipo = 1;
}
}
public void Adicionar(Veiculo veiculo)
{
veiculos.Add(veiculo);
}
public void Atualizar(Veiculo veiculo)
{
var old = veiculos.FirstOrDefault(t => t.Id == veiculo.Id);
if (old != null)
{
int index = veiculos.IndexOf(old);
veiculos[index] = veiculo;
}
else
throw new InvalidOperationException($"Veículos não localizada para o Id {veiculo.Id}");
}
public Veiculo BuscarPordId(Guid Id)
{
return veiculos.FirstOrDefault(t => t.Id == Id);
}
public IQueryable<Veiculo> ObterVeiculos()
{
return veiculos.AsQueryable();
}
public void Remover(Veiculo veiculo)
{
var old = veiculos.FirstOrDefault(t => t.Id == veiculo.Id);
if (old != null)
{
int index = veiculos.IndexOf(old);
veiculos.RemoveAt(index);
}
else
throw new InvalidOperationException($"Veículo não localizada para o Id {veiculo.Id}");
}
}
}
<file_sep>using Projeto.Dominio.Mercadorias.Entity;
using System;
using System.Linq;
using Xunit;
namespace Projeto.Dominio.Teste
{
public class MercadoriaTest
{
Mercadoria mercadoria = null;
[Fact]
[Trait("Entity", "Mercadoria")]
public void DeveRetornarMercadoriaValida()
{
//Arrange
mercadoria = new Mercadoria(MercadoriaTipo.Caixa, 15, true);
//Act
bool valido = mercadoria.EhValido();
//Assert
Assert.True(valido);
Assert.NotEqual(Guid.Empty, mercadoria.Id);
Assert.Equal(MercadoriaTipo.Caixa, mercadoria.Tipo);
Assert.Equal(15, mercadoria.Peso);
Assert.True(mercadoria.Fragil);
}
[Fact]
[Trait("Entity", "Mercadoria")]
public void DeveRetornarMercadoriaInvalidaSeTipoNaoInformado()
{
//Arrange
mercadoria = new Mercadoria(0, 15, true);
//Act
bool valido = mercadoria.EhValido();
//Assert
Assert.False(valido);
Assert.True(mercadoria.ValidationResult.Errors.All(t => t.PropertyName == nameof(mercadoria.Tipo)));
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[Trait("Entity", "Mercadoria")]
public void DeveRetornarMercadoriaInvalidaSeQuantidadeForaRange(double peso)
{
//Arrange
mercadoria = new Mercadoria(MercadoriaTipo.Container, peso, true);
//Act
bool valido = mercadoria.EhValido();
//Assert
Assert.False(valido);
Assert.True(mercadoria.ValidationResult.Errors.All(t => t.PropertyName == nameof(mercadoria.Peso)));
}
}
}
<file_sep>using Moq;
using Projeto.Dominio.Mercadorias.Entity;
using Projeto.Dominio.Teste.Mocks;
using Projeto.Dominio.Transporte.Repository;
using Projeto.Dominio.Veiculos.Entities;
using System.Collections.Generic;
using Xunit;
using Projeto.Dominio.Veiculos.Repository;
using System.Linq;
using Projeto.Dominio.Transporte.Commands;
using System;
using Projeto.Dominio.Transporte.Sagas;
using System.Threading;
namespace Projeto.Dominio.Teste
{
public class ViagemSagaTest
{
MercadoriaMock mercadoriaRepository = new MercadoriaMock();
VeiculoMock veiculoRepository = new VeiculoMock();
Mock<IViagemRepository> viagemRepository = new Mock<IViagemRepository>();
[Fact]
[Trait("Saga", "ViagemSaga")]
public void NovaViagemCommandDeveGerarViagem()
{
//Arrange
Veiculo veiculo = veiculoRepository.ObterVeiculos().BuscarPorCapacidadeMaxima(4000).OrderBy(t => t.CapaxidadeMaxima).LastOrDefault();
IEnumerable<Mercadoria> mercadorias = mercadoriaRepository.ObterMercadorias().Take(5);
NovaViagemCommand novaViagemCommand = new NovaViagemCommand(veiculo.Id, "SAO PAULO", "RIO DE JANEIRO", mercadorias.Select(t => t.Id));
ViagemSaga saga = new ViagemSaga(mercadoriaRepository, veiculoRepository, viagemRepository.Object);
//Act
CancellationToken token = new CancellationToken();
Guid viagemId = saga.Handle(novaViagemCommand, token).Result;
//Assert
Assert.NotEqual(Guid.Empty, viagemId);
Assert.False(saga.ExisteErros);
Assert.False(saga.ExisteAlerta);
}
[Fact]
[Trait("Saga", "ViagemSaga")]
public void NovaViagemCommandDeveGerarViagemCommAlerta()
{
//Arrange
Veiculo veiculo = veiculoRepository.ObterVeiculos().BuscarPorCapacidadeMaxima(4000).OrderBy(t => t.CapaxidadeMaxima).LastOrDefault();
List<Mercadoria> mercadorias = mercadoriaRepository.ObterMercadorias().Take(5).ToList();
mercadorias.Add(new Mercadoria(MercadoriaTipo.Tambor, 20, false));
NovaViagemCommand novaViagemCommand = new NovaViagemCommand(veiculo.Id, "<NAME>", "RIO DE JANEIRO", mercadorias.Select(t => t.Id));
ViagemSaga saga = new ViagemSaga(mercadoriaRepository, veiculoRepository, viagemRepository.Object);
//Act
CancellationToken token = new CancellationToken();
Guid viagemId = saga.Handle(novaViagemCommand, token).Result;
//Assert
Assert.NotEqual(Guid.Empty, viagemId);
Assert.False(saga.ExisteErros);
Assert.True(saga.ExisteAlerta);
}
[Fact]
[Trait("Saga", "ViagemSaga")]
public void NovaViagemCommandNaoDeveGerarViagem()
{
//Arrange
Veiculo veiculo = new Veiculo("HERCULES", VeiculoTipo.Aviao, 10000);
List<Mercadoria> mercadorias = mercadoriaRepository.ObterMercadorias().Take(5).ToList();
NovaViagemCommand novaViagemCommand = new NovaViagemCommand(veiculo.Id, "<NAME>", "RIO DE JANEIRO", mercadorias.Select(t => t.Id));
ViagemSaga saga = new ViagemSaga(mercadoriaRepository, veiculoRepository, viagemRepository.Object);
//Act
CancellationToken token = new CancellationToken();
Guid viagemId = saga.Handle(novaViagemCommand, token).Result;
//Assert
Assert.Equal(Guid.Empty, viagemId);
Assert.True(saga.ExisteErros);
Assert.False(saga.ExisteAlerta);
}
}
}
<file_sep>using FluentValidation;
using Projeto.Dominio.Veiculos.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto.Dominio.Veiculos.Validations
{
public class VeiculoEstaConsistente : AbstractValidator<Veiculo>
{
public VeiculoEstaConsistente()
{
RuleFor(t => t.Id)
.NotEmpty().WithMessage("Id não informado");
RuleFor(t => t.Nome)
.NotEmpty().WithMessage("Nome não informado")
.Length(2, 20).WithMessage("Nome deve ter entre 2 e 20 caractéres");
RuleFor(t => t.Tipo)
.IsInEnum().WithMessage("Tipo inválido");
RuleFor(t => t.CapaxidadeMaxima)
.NotEmpty().WithMessage("Quantidade não informada")
.GreaterThan(0).WithMessage("Quantidade deve ser maior que zero");
}
}
}
<file_sep>using Projeto.Dominio.Veiculos.Entities;
using System;
using System.Linq;
using Xunit;
namespace Projeto.Dominio.Teste
{
public class VeiculosTest
{
Veiculo veiculo = null;
[Fact]
[Trait("Entity", "Veiculo")]
public void DeveRetornarUmVeiculoValido()
{
//Arrange
veiculo = new Veiculo("<NAME>", VeiculoTipo.Navio, 1000000);
//Act
bool valido = veiculo.EhValido();
//Assert
Assert.True(valido);
Assert.NotEqual(Guid.Empty, veiculo.Id);
Assert.Equal("<NAME>", veiculo.Nome);
Assert.Equal(VeiculoTipo.Navio, veiculo.Tipo);
Assert.Equal(1000000, veiculo.CapaxidadeMaxima);
}
[Theory()]
[InlineData("")]
[InlineData(null)]
[InlineData("A")]
[InlineData("AAAAAAAAAAAAAAAAAAAAA")]
[Trait("Entity", "Veiculo")]
public void DeveRetornarUmVeiculoInvalidoPorNome(string nome)
{
//Arrange
veiculo = new Veiculo(nome, VeiculoTipo.Caminhao, 100000);
//Act
bool valido = veiculo.EhValido();
//Assert
Assert.False(valido);
Assert.True(veiculo.ValidationResult.Errors.All(t=> t.PropertyName == nameof(veiculo.Nome)));
}
[Fact]
[Trait("Entity", "Veiculo")]
public void DeveRetornarUmVeiculoInvalidoPoTipo()
{
//Arrange
veiculo = new Veiculo("TREM", 0, 100000);
//Act
bool valido = veiculo.EhValido();
//Assert
Assert.False(valido);
Assert.Single(veiculo.ValidationResult.Errors);
Assert.True(veiculo.ValidationResult.Errors.All(t => t.PropertyName == nameof(veiculo.Tipo)));
}
[Fact]
[Trait("Entity", "Veiculo")]
public void DeveRetornarUmVeiculoInvalidoPorQuantidade()
{
//Arrange
veiculo = new Veiculo("TREM", VeiculoTipo.Aviao, 0);
//Act
bool valido = veiculo.EhValido();
//Assert
Assert.False(valido);
Assert.True(veiculo.ValidationResult.Errors.All(t => t.PropertyName == nameof(veiculo.CapaxidadeMaxima)));
}
}
}
<file_sep>using FluentValidation.Results;
using Projeto.Dominio.Transporte.Entity;
using Projeto.Dominio.Veiculos.Validations;
using System;
namespace Projeto.Dominio.Veiculos.Entities
{
public class Veiculo
{
public Veiculo(string nome, VeiculoTipo tipo, int capacidadeMaxima)
{
Id = Guid.NewGuid();
Nome = nome;
Tipo = tipo;
CapaxidadeMaxima = capacidadeMaxima;
}
public Guid Id { get; private set; }
public string Nome { get; private set; }
public VeiculoTipo Tipo { get; private set; }
public double CapaxidadeMaxima { get; private set; }
public ValidationResult ValidationResult { get; private set; }
public bool EhValido()
{
ValidationResult = new VeiculoEstaConsistente().Validate(this);
return ValidationResult.IsValid;
}
public Viagem NovaViagem(string Origem, string Destino)
{
return new Viagem(this, Origem, Destino);
}
}
}
<file_sep>using Projeto.Dominio.Mercadorias.Entity;
using Projeto.Dominio.Transporte.Entity;
using Projeto.Dominio.Veiculos.Entities;
using System;
using System.Linq;
using Xunit;
namespace Projeto.Dominio.Teste
{
public class ViagemTest
{
Viagem viagem;
[Fact]
[Trait("Entity","Viagem")]
public void ObterViagemValida()
{
//Arrange
Veiculo veiculo = new Veiculo("AR LINE", VeiculoTipo.Aviao, 60000);
//Act
viagem = veiculo.NovaViagem("Canada", "Brasil");
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Container, 4000, false));
bool valida = viagem.EhValida();
//Assert
Assert.True(valida);
Assert.NotEqual(Guid.Empty, viagem.Id);
Assert.Equal(veiculo.Id, viagem.TransportadorId);
Assert.Equal(veiculo.CapaxidadeMaxima, viagem.CapacidadeMaxima);
Assert.Equal(5800, viagem.CapacidadeAtual);
Assert.Equal("Canada", viagem.Origem);
Assert.Equal("Brasil", viagem.Destino);
}
[Fact]
[Trait("Entity", "Viagem")]
public void ObterViagemInvalidaPorQuantidadeAcimaDoSuportavel()
{
//Arrange
Veiculo veiculo = new Veiculo("AR LINE", VeiculoTipo.Caminhao, 1000);
//Act
viagem = veiculo.NovaViagem("Canada", "Brasil");
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
viagem.AdicionarMercadoria(new Mercadoria(MercadoriaTipo.Tambor, 600, false));
bool valida = viagem.EhValida();
//Assert
Assert.False(valida);
Assert.True(viagem.ValidationResult.Errors.All(t => t.PropertyName == nameof(viagem.CapacidadeAtual)));
}
[Fact]
[Trait("Entity", "Viagem")]
public void ObterViagemInvalidaPorQuantidadeMercadoriaZero()
{
//Arrange
Veiculo veiculo = new Veiculo("AR LINE", VeiculoTipo.Caminhao, 1000);
//Act
viagem = veiculo.NovaViagem("Canada", "Brasil");
bool valida = viagem.EhValida();
//Assert
Assert.False(valida);
Assert.True(viagem.ValidationResult.Errors.All(t => t.PropertyName == nameof(viagem.CapacidadeAtual)));
}
}
}
<file_sep>using MediatR;
using System;
using System.Collections.Generic;
namespace Projeto.Dominio.Transporte.Commands
{
public class NovaViagemCommand : IRequest<Guid>
{
public NovaViagemCommand(Guid veiculoId, string origem, string destino, IEnumerable<Guid> mercadorias)
{
VeiculoId = veiculoId;
Origem = origem;
Destino = destino;
Mercadorias = mercadorias;
}
public Guid VeiculoId { get; private set; }
public string Origem { get; private set; }
public string Destino { get; private set; }
public IEnumerable<Guid> Mercadorias { get; private set; }
}
}
<file_sep>using FluentValidation;
using Projeto.Dominio.Transporte.Entity;
namespace Projeto.Dominio.Transporte.Validations
{
public class ViagemEstaConsistente : AbstractValidator<Viagem>
{
public ViagemEstaConsistente()
{
RuleFor(t => t.Id)
.NotEmpty().WithMessage("Id não informado");
RuleFor(t => t.TransportadorId)
.NotEmpty().WithMessage("Transportador não informado");
RuleFor(t => t.CapacidadeMaxima)
.NotEmpty().WithMessage("Capacidade máxima não informada");
RuleFor(t => t.Origem)
.NotEmpty().WithMessage("Origem não informada")
.Length(2, 20).WithMessage("Origem deve ter entre 2 e 20 caractéres");
RuleFor(t => t.Destino)
.NotEmpty().WithMessage("Destino não informada")
.Length(2, 20).WithMessage("Destino deve ter entre 2 e 20 caractéres");
RuleFor(t => t.CapacidadeAtual)
.GreaterThan(0).WithMessage("Informe ao menos uma mercadoria para a viagem")
.Custom((prop, ctx) =>
{
Viagem viagem = ctx.ParentContext.InstanceToValidate as Viagem;
if (prop > viagem.CapacidadeMaxima)
ctx.AddFailure("Capacidade atual está acima da máxima permitida");
});
}
}
}
<file_sep>using Projeto.Dominio.Mercadorias.Entity;
using System;
using System.Linq;
namespace Projeto.Dominio.Mercadorias.Repository
{
public interface IMercadoriaRepository
{
void Adicionar(Mercadoria mercadoria);
void Atualizar(Mercadoria mercadoria);
void Remover(Mercadoria mercadoria);
Mercadoria BuscarPordId(Guid Id);
IQueryable<Mercadoria> ObterMercadorias();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
using Projeto.Dominio.Mercadorias.Entity;
using Projeto.Dominio.Transporte.Validations;
using Projeto.Dominio.Veiculos.Entities;
namespace Projeto.Dominio.Transporte.Entity
{
public class Viagem
{
private List<Mercadoria> mercadorias = new List<Mercadoria>();
public Viagem(Veiculo veiculo, string origem, string destino)
{
Id = Guid.NewGuid();
TransportadorId = veiculo.Id;
CapacidadeMaxima = veiculo.CapaxidadeMaxima;
Origem = origem;
Destino = destino;
}
public Guid Id { get; private set; }
public Guid TransportadorId { get; private set; }
public string Origem { get; private set; }
public string Destino { get; private set; }
public double CapacidadeMaxima { get; private set; }
public double CapacidadeAtual { get { return mercadorias.Sum(t => t.Peso); } }
public ValidationResult ValidationResult { get; private set; }
public void AdicionarMercadoria(Mercadoria mercadoria)
{
mercadorias.Add(mercadoria);
}
public bool EhValida()
{
ValidationResult = new ViagemEstaConsistente().Validate(this);
return ValidationResult.IsValid;
}
}
}
<file_sep>using Projeto.Dominio.Mercadorias.Entity;
using System.Linq;
namespace Projeto.Dominio.Mercadorias.Repository
{
public static class MercadoriaRepositoryExtension
{
public static IQueryable<Mercadoria> BuscarPorTipo(this IQueryable<Mercadoria> query, MercadoriaTipo tipo)
{
return query.Where(t => t.Tipo == tipo);
}
public static IQueryable<Mercadoria> BuscarFrageis(this IQueryable<Mercadoria> query, bool fragil = true)
{
return query.Where(t => t.Fragil == fragil);
}
}
}
<file_sep>using Projeto.Dominio.Transporte.Entity;
using System;
using System.Linq;
namespace Projeto.Dominio.Transporte.Repository
{
public interface IViagemRepository
{
void Adicionar(Viagem viagem);
void Atualizar(Viagem viagem);
void Remover(Viagem viagem);
IQueryable<Viagem> BuscarViagens();
Viagem BuscarPordId(Guid Id);
}
}
<file_sep>using Projeto.Dominio.Veiculos.Entities;
using System.Linq;
namespace Projeto.Dominio.Veiculos.Repository
{
public static class VeiculoRepositoryExtension
{
public static IQueryable<Veiculo> BuscarPorTipo(this IQueryable<Veiculo> query, VeiculoTipo tipo)
{
return query.Where(t => t.Tipo == tipo);
}
public static IQueryable<Veiculo> BuscarPorCapacidadeMaxima(this IQueryable<Veiculo> query, double AteCapacidadeMaxima)
{
return query.Where(t => t.CapaxidadeMaxima <= AteCapacidadeMaxima);
}
}
}
<file_sep># Testes
Projeto para demonstrar a aplicação de TDD, utilizando-se de conceitos como Red, Green e Refactore, BabyStep e Mocks.
# Frameworks utilizados
Framework de teste: <b>xUnit</b>
```
https://github.com/xunit/xunit
https://xunit.github.io/
```
Framework de mock: <b>moq</b>
```
https://github.com/moq/moq4
```
Framework de validação: <b>fluent validation</b>
```
https://github.com/JeremySkinner/FluentValidation
```
Framework de mediação para comandos e mensagens: <b>MeditR</b>
```
https://github.com/jbogard/MediatR
```
# Configuração Inicial
Para executar a aplicação, é necessário restaurar o Nuget do projeto.
1. Para executar os testes vá no menu Testar > Executar > Todos os Testes ou <b>CRTL + R, A</b>
2. Para visualizar a tela de teste vá ao menu Testar > Janelas > Gerenciador de Testes ou <b>CRTL + E, T </b>
Com isso, a aplicação estará pronta para ser executada.
# Próximos Passos
Refatoração do código para incluir algumas novas funcionalidades com base em regras de negócio
1. As mercadorias poderão ser informadas posteriormente, não necessitando informa-las na criação da viagem
2. As mercadorias deverão ser informadas junto com o documento do cliente
3. As mercadorias deverão ser agrupadas pelo documento do cliente
4. Não deverá existir mais de uma viagem para o mesmo veiculo do tipo Trem ou Navio no mesmo dia
<file_sep>using Projeto.Dominio.Veiculos.Entities;
using System;
using System.Linq;
namespace Projeto.Dominio.Veiculos.Repository
{
public interface IVeiculoRepository
{
void Adicionar(Veiculo veiculo);
void Atualizar(Veiculo veiculo);
void Remover(Veiculo veiculo);
Veiculo BuscarPordId(Guid Id);
IQueryable<Veiculo> ObterVeiculos();
}
}
<file_sep>
namespace Projeto.Dominio.Veiculos.Entities
{
public enum VeiculoTipo
{
Caminhao = 1,
Navio = 2,
Aviao = 3,
Trem = 4,
}
}<file_sep>using Projeto.Dominio.Mercadorias.Entity;
using Projeto.Dominio.Mercadorias.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Projeto.Dominio.Teste.Mocks
{
public class MercadoriaMock : IMercadoriaRepository
{
List<Mercadoria> mercadorias = new List<Mercadoria>();
public MercadoriaMock()
{
int tipo = 1;
for (int i = 0; i < 50; i++)
{
mercadorias.Add(new Mercadoria((MercadoriaTipo)Enum.ToObject(typeof(MercadoriaTipo), tipo), 50 * (i + 1), i % 2 == 0));
++tipo;
if (tipo == 5)
tipo = 1;
}
}
public void Adicionar(Mercadoria mercadoria)
{
mercadorias.Add(mercadoria);
}
public void Atualizar(Mercadoria mercadoria)
{
var old = mercadorias.FirstOrDefault(t => t.Id == mercadoria.Id);
if (old != null)
{
int index = mercadorias.IndexOf(old);
mercadorias[index] = mercadoria;
}
else
throw new InvalidOperationException($"Mercadoria não localizada para o Id {mercadoria.Id}");
}
public Mercadoria BuscarPordId(Guid Id)
{
return mercadorias.FirstOrDefault(t => t.Id == Id);
}
public IQueryable<Mercadoria> ObterMercadorias()
{
return mercadorias.AsQueryable();
}
public void Remover(Mercadoria mercadoria)
{
var old = mercadorias.FirstOrDefault(t => t.Id == mercadoria.Id);
if (old != null)
{
int index = mercadorias.IndexOf(old);
mercadorias.RemoveAt(index);
}
else
throw new InvalidOperationException($"Mercadoria não localizada para o Id {mercadoria.Id}");
}
}
}
<file_sep>using FluentValidation.Results;
using Projeto.Dominio.Mercadorias.Validations;
using System;
namespace Projeto.Dominio.Mercadorias.Entity
{
public class Mercadoria
{
public Mercadoria(MercadoriaTipo tipo, double peso, bool fragil)
{
Id = Guid.NewGuid();
Tipo = tipo;
Peso = peso;
Fragil = fragil;
}
public Guid Id { get; private set; }
public MercadoriaTipo Tipo { get; private set; }
public double Peso { get; private set; }
public bool Fragil { get; private set; }
public ValidationResult ValidationResult { get; private set; }
public bool EhValido()
{
ValidationResult = new MercadoriaEstaConsistente().Validate(this);
return ValidationResult.IsValid;
}
}
}
<file_sep>using MediatR;
using Projeto.Dominio.Mercadorias.Repository;
using Projeto.Dominio.Transporte.Commands;
using Projeto.Dominio.Transporte.Repository;
using Projeto.Dominio.Veiculos.Entities;
using Projeto.Dominio.Veiculos.Repository;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Projeto.Dominio.Transporte.Sagas
{
public class ViagemSaga : ISagaNotification,
IRequestHandler<NovaViagemCommand, Guid>
{
readonly IMercadoriaRepository mercadoriaRepository;
readonly IVeiculoRepository veiculoRepository;
readonly IViagemRepository viagemRepository;
private List<string> erros = new List<string>();
private List<string> alertas = new List<string>();
public ViagemSaga(IMercadoriaRepository mercadoriaRepository, IVeiculoRepository veiculoRepository, IViagemRepository viagemRepository)
{
this.veiculoRepository = veiculoRepository;
this.mercadoriaRepository = mercadoriaRepository;
this.viagemRepository = viagemRepository;
}
public bool ExisteErros => erros.Count > 0;
public bool ExisteAlerta => alertas.Count > 0;
public Task<Guid> Handle(NovaViagemCommand request, CancellationToken cancellationToken)
{
erros.Clear();
alertas.Clear();
Veiculo veiculo = veiculoRepository.BuscarPordId(request.VeiculoId);
if (veiculo == null)
{
erros.Add($"Veiculo não localizado para o Id {request.VeiculoId}");
return Task.FromResult(Guid.Empty);
}
var viagem = veiculo.NovaViagem(request.Origem, request.Destino);
foreach (var mercadoriaId in request.Mercadorias)
{
var mercadoria = mercadoriaRepository.BuscarPordId(mercadoriaId);
if (mercadoria == null)
{
alertas.Add($"Mercadoria não localizada para o Id {mercadoriaId}");
continue;
}
viagem.AdicionarMercadoria(mercadoria);
}
if (!viagem.EhValida())
{
foreach (var erro in viagem.ValidationResult.Errors)
erros.Add($"O campo {erro.PropertyName} esta invalido: {erro.ErrorMessage}");
return Task.FromResult(Guid.Empty);
}
viagemRepository.Adicionar(viagem);
return Task.FromResult(viagem.Id);
}
public IEnumerable<string> ObterAlertas()
{
return alertas;
}
public IEnumerable<string> ObterErros()
{
return erros;
}
}
}
<file_sep>using FluentValidation;
using Projeto.Dominio.Mercadorias.Entity;
namespace Projeto.Dominio.Mercadorias.Validations
{
public class MercadoriaEstaConsistente : AbstractValidator<Mercadoria>
{
public MercadoriaEstaConsistente()
{
RuleFor(t => t.Id)
.NotEmpty().WithMessage("Id não informado");
RuleFor(t => t.Tipo)
.IsInEnum().WithMessage("Tipo não informado");
RuleFor(t => t.Peso)
.NotEmpty().WithMessage("Peso não informado")
.GreaterThan(0).WithMessage("Peso deve ser maior que zero"); ;
}
}
}
<file_sep>using System.Collections.Generic;
namespace Projeto.Dominio
{
public interface ISagaNotification
{
bool ExisteErros { get; }
bool ExisteAlerta { get; }
IEnumerable<string> ObterErros();
IEnumerable<string> ObterAlertas();
}
}
| 88342af6f890d202f920ba81064686308e2ae740 | [
"Markdown",
"C#"
] | 23 | C# | Angelicogfa/TDD-Sample | 79756ffbb34c060713a2142074bb8b8f865355c9 | 2fa4f7ae84091b7551e5365109143d9a9cd0e930 |
refs/heads/main | <repo_name>pankaj7822/pdf_utils<file_sep>/imagetopdf.py
# Python3 program to convert image to pfd
# using img2pdf library
# importing necessary libraries
import img2pdf
from PIL import Image
import os
images_path=sorted([os.path.join("images",f) for f in os.listdir("images")])
print(images_path)
# storing image path
for img_path in images_path:
# img_path = "LL_17074010_page-0007.jpg"
# storing pdf path
pdf_path = os.path.join("images_pdf",img_path[7:-4]+"pdf")
# opening image
image = Image.open(img_path)
# converting into chunks using img2pdf
pdf_bytes = img2pdf.convert(image.filename)
# opening or creating pdf file
file = open(pdf_path, "wb")
# writing pdf files with chunks
file.write(pdf_bytes)
# closing image file
image.close()
# closing pdf file
file.close()
# output
print("Successfully made pdf file")<file_sep>/generaterandom.py
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
p=id_generator(1000, "6793YUIO")
text_file = open("Output.txt", "w")
text_file.write(p)
text_file.close()<file_sep>/getimages.py
from pdf2image import convert_from_path,convert_from_bytes
import os
import PyPDF2
from PIL import Image
import tempfile
pdf_file="example.pdf"
dpi=150
quality=100
pdf = PyPDF2.PdfFileReader(pdf_file,"rb")
p = pdf.getPage(0)
w_in_user_space_units = p.mediaBox.getWidth()
h_in_user_space_units = p.mediaBox.getHeight()
# 1 user space unit is 1/72 inch
# 1/72 inch ~ 0.352 millimeters
# pixels = inches * PPI
# p.mediaBox.getWidth() returns width in user space unit
w = float(p.mediaBox.getWidth())*dpi/72.0
h = float(p.mediaBox.getHeight())*dpi/72.0
print(w,h)
# Store Pdf with convert_from_path function
images=convert_from_path(pdf_file,dpi=dpi,size=(w,h),fmt="jpeg",jpegopt={
"quality": quality,
"progressive": True,
"optimize": True
})
for i in range(len(images)):
save_path=os.path.join("images",'page'+ str(i+1) +'.jpeg')
im=images[i]
im.save(save_path, 'JPEG',quality=quality,dpi=(dpi, dpi))
print("Sucessfuly Saved ",save_path)<file_sep>/createdirs.py
import os
dirs=["final","images","images_pdf","text_pdf"]
for d in dirs:
if not os.path.exists(d):
os.mkdir(d)<file_sep>/createfinal.py
import os
import shutil
image_pdf_index=[1,2]
text_pdf_index=[3,4]
f=sorted(os.listdir("images_pdf"))
g=sorted(os.listdir("text_pdf"))
image_pdf_paths=[os.path.join("images_pdf",f[i-1]) for i in image_pdf_index]
text_pdf_paths=[os.path.join("text_pdf",g[j-1]) for j in text_pdf_index]
for i in range(len(image_pdf_paths)):
original=image_pdf_paths[i]
target=os.path.join("final",f[image_pdf_index[i]-1])
shutil.copyfile(original, target)
for i in range(len(text_pdf_paths)):
original=text_pdf_paths[i]
target=os.path.join("final",g[text_pdf_index[i]-1])
shutil.copyfile(original, target)<file_sep>/mergepdf.py
from PyPDF2 import PdfFileMerger
import os
pdfs = list(os.listdir("final"))
pdf_paths=sorted([os.path.join("final",f) for f in pdfs])
merger = PdfFileMerger()
for pdf in pdf_paths:
merger.append(pdf)
merger.write("result.pdf")
merger.close()<file_sep>/splitpdf.py
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
inputpdf = PdfFileReader(open("example.pdf", "rb"))
for i in range(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(i))
f_name=os.path.join("text_pdf","page"+str(i+1)+".pdf")
with open(f_name, "wb") as outputStream:
output.write(outputStream)<file_sep>/README.md
# pdf_processing
pip3 install pdf2image
pip3 install PyPDF2
pip3 install img2pdf
rename your pdf file as example.pdf and place in root dir
(for creating all the relevant directories if they don't exist)
python3 createdirs.py
(get images in images directory)
python3 getimages.py
(get images pdf)
python3 imagetopdf.py
(get text pdf)
python3 splitpdf.py
after putting relevant files in final dir
python3 mergepdf.py<file_sep>/runall.py
exec(open("createdirs.py").read())
exec(open("getimages.py").read())
exec(open("imagetopdf.py").read())
exec(open("splitpdf.py").read())
exec(open("createfinal.py").read())
exec(open("mergepdf.py").read()) | a15f3f0e4d6ef65b504b1c818b0c09150ddda614 | [
"Markdown",
"Python"
] | 9 | Python | pankaj7822/pdf_utils | 6ac02b2a9ab811e1b380728075779e952da292b2 | eb67a9a101800deb751e8497d0de140b0e2dec3d |
refs/heads/master | <file_sep><?php namespace App\Http\Commands;
/**
* Class FilterByEmergency
* @package App\Http\Commands
*/
class FilterByEmergency extends FilterByCity
{
/**
* @return \Illuminate\Database\Query|mixed
*/
public function handle()
{
$emergency = array_get($this->filters, 'emergency', false);
$query = $this->query;
if ($emergency) {
$query = $query->where("emergency", true);
}
return $query;
}
}<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [
'uses' => 'Controller@showHomePage',
'as' => 'show_homepage'
]);
Route::get('/login', [
'uses' => 'UserController@showLoginPage',
'as' => 'show_login'
]);
Route::post('/login',[
'uses' => 'UserController@login',
'as' => 'process_login'
]);
Route::post('/saveChanges',[
'uses' => 'UserController@saveChanges',
'as' => 'saveChanges'
]);
Route::post('/saveChangesVet',[
'uses' => 'UserController@saveChangesVet',
'as' => 'saveChangesVet'
]);
Route::get('/register', [
'uses' => 'UserController@showRegisterPage',
'as' => 'show_register'
]);
Route::post('/register', [
'uses' => 'UserController@register',
'as' => 'process_register'
]);
Route::get('/search', [
'uses' => 'VetController@showAllVetPage',
'as' => 'show_all_vet'
]);
Route::get('/services', [
'uses' => 'ServiceController@showAllServicesPage',
'as' => 'show_all_service'
]);
Route::get('/dashboard',[
'uses' => 'UserController@showDashbord',
'as' => 'show_dashbord',
'middleware' => [\App\Http\Middleware\CheckAuth::class]
]);
Route::get('/appointment', [
'uses' => 'ServiceController@showAddAppointmentPage',
'as' => 'add_appointment'
]);
Route::get('/vet/{id}',[
'uses' => 'VetController@showVet',
'as' => 'show_vet'
]);
Route::post('/add-appointment',[
'uses' => 'UserController@processAppointment',
'as' => 'process_appointment'
]);
Route::get('/confirm-appointment/{id}', [
'uses' => 'UserController@confirmAppointment',
'as' => 'confirm_appointment'
]);
Route::get('/cancel-appointment/{id}', [
'uses' => 'UserController@cancelAppointment',
'as' => 'cancel_appointment'
]);
Route::get('/logout',[
'uses' => 'UserController@logout',
'as' => 'user_logout'
]);
Route::get('/show-services',[
'uses' => 'ServiceController@showService',
'as' => 'show_service'
]);
Route::post('/add-service',[
'uses' => 'ServiceController@addService',
'as' => 'add_service'
]);
Route::get('/delete-service/{id}',[
'uses' => 'UserController@deleteService',
'as' => 'delete_service'
]);
Route::post('/modify-service/{id}',[
'uses' => 'UserController@modifyService',
'as' => 'modify_service'
]);
Route::post('/save-emergency/{id}',[
'uses' => 'UserController@saveEmergency',
'as' => 'save_emergency'
]);
Route::get('/emergency',[
'uses' => 'VetController@showEmergency',
'as' => 'show_emergency'
]);
Route::get('/add-animal',[
'uses' => 'UserController@addAnimalPage',
'as' => 'add_animal'
]);
Route::post('/add-animal',[
'uses' => 'UserController@addAnimalProcess',
'as' => 'add_animal_process'
]);
Route::get('/delete-animal/{i}',[
'uses' => 'UserController@deleteAnimal',
'as' => 'delete_animal'
]);
<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AdministratorsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('administrators')->insert([
'user_id' => '1',
'address' => "Eroilor 2",
'schedule' => '12-15',
'phone' => '0282882',
'phoneF' => '021821',
'firm_name' => 'firm srll',
'emergency' => '1',
'emergency_schedule' => '00-24',
]);
DB::table('administrators')->insert([
'user_id' => '2',
'address' => "Eroilor 2",
'schedule' => '12-15',
'phone' => '0282882',
'phoneF' => '021821',
'firm_name' => 'firm srll',
'emergency' => '1',
'emergency_schedule' => '00-24',
]);
DB::table('administrators')->insert([
'user_id' => '3',
'address' => "Eroilor 2",
'schedule' => '12-15',
'phone' => '0282882',
'phoneF' => '021821',
'firm_name' => 'firm srll',
'emergency' => '1',
'emergency_schedule' => '00-24',
]);
DB::table('administrators')->insert([
'user_id' => '4',
'address' => "Eroilor 2",
'schedule' => '12-15',
'phone' => '0282882',
'phoneF' => '021821',
'firm_name' => 'firm srll',
'emergency' => '1',
'emergency_schedule' => '00-24',
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Admin;
use App\Animal;
use App\Appointment;
use App\Client;
use App\Race;
use App\Service;
use App\Specie;
use App\User;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
class UserController extends Controller
{
//
public function showLoginPage(){
if(\Auth::check()){
return redirect(route('show_dashbord'));
}
return view('login');
}
public function showRegisterPage(){
if(\Auth::check()){
return redirect(route('show_dashbord'));
}
return view('register');
}
public function login(Request $request){
$rules = array(
'username' => 'required|',
'password' => '<PASSWORD>'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::to(route("show_login"))
->withErrors($validator)
->withInput(Input::except('password'));
}
else {
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::attempt($userdata)){
return redirect(route("show_homepage"));
}
else {
return redirect(route("show_login"))->withInput()->withErrors(new MessageBag([
'logging' => [
'Datele introduse nu sunt corecte'
]
]));
}
}
}
public function saveChanges(){
$actual_user = \Auth::user();
$actual_user->name = Input::get('name');
$actual_user->email = Input::get('email');
if(Input::get('password') != "")
$actual_user->password = <PASSWORD>(Input::get('password'));
$actual_user->client->phone = Input::get('phone');
$actual_user->client->save();
$actual_user->save();
return redirect(route('show_dashbord'));
}
public function saveChangesVet(){
$actual_user = \Auth::user();
if(Input::get('password') != "")
$actual_user->password = Hash::make(Input::get('<PASSWORD>'));
$actual_user->admin->address = (!is_null(Input::get("addressVet"))) ? Input::get("addressVet") : "";
$actual_user->admin->schedule = (!is_null(Input::get("scheduleVet"))) ? Input::get("scheduleVet") : "";
$actual_user->admin->phone = (!is_null(Input::get("phoneVet"))) ? Input::get("phoneVet") : "";
$actual_user->admin->phoneF = (!is_null(Input::get("phoneFVet"))) ? Input::get("phoneFVet") : "";
$actual_user->admin->firm_name = (!is_null(Input::get("firmNameVet"))) ? Input::get("firmNameVet") : "";
$actual_user->admin->save();
$actual_user->save();
return redirect(route('show_dashbord'));
}
public function showDashbord(){
if(\Auth::user()->profile_type) {
$user_appointments = \Auth::user()->client->appointments;
$animals = \Auth::user()->client->animals;
return view('dashbord',[
'user_appointments' => $user_appointments,
'animals' => $animals,
'actualUser' => \Auth::user()
]);
}
$appointments = \Auth::user()->admin->appointments;
$services = \Auth::user()->admin->services;
return view('dashbord',[
'appointments' => $appointments,
'services' => $services,
'admin' => \Auth::user()
]);
}
public function register(Request $request){
$rules = array(
'user_type' => 'required|',
'name' => 'required|',
'email' => 'required|',
'county' => 'required|',
'city' => 'required|',
'username' => 'required|',
'password' => '<PASSWORD>'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::to(route("show_register"))
->withErrors($validator)
->withInput(Input::except('password'));
}
else {
$userdata = array(
'profile_type' => Input::get('user_type'),
'name' => Input::get('name'),
'email' => Input::get('email'),
'county' => Input::get('county'),
'city' => Input::get('city'),
'username' => Input::get('username'),
'password' => Input::get('<PASSWORD>'),
);
$user = new User($userdata);
if($user->profile_type == 1){
$client = new Client();
$client->phone = '';
$client->gender = '';
}
else {
$admin = new Admin();
$admin->address = "";
$admin->schedule = "";
$admin->phone = "";
$admin->phoneF = "";
$admin->firm_name = "";
$admin->emergency = false;
$admin->emergency_schedule = "";
}
$user->password = <PASSWORD>($request->get('password'));
$message = "";
$messageSucces = "";
try {
$user->save();
if($user->profile_type == 1){
$client->user_id = $user->id;
$client->save();
}
else {
$admin->user_id = $user->id;
$admin->save();
}
$messageSucces= "Contul a fost creat cu succes! Va rugam sa va logati";
return redirect(route('show_login'));
}
catch (QueryException $exception)
{
$message = "Mai exista un cont cu acest e-mail sau cu acest username!";
}
return redirect(route("show_register"))->withInput()->withErrors(new MessageBag([
'registeringWithError' => [
$message
],
'registeringSuccess' => [
$messageSucces
]
]));
}
}
public function confirmAppointment($id)
{
$appointment = Appointment::find($id);
if (!$appointment) {
abort(404);
}
$appointment->confirmation = true;
$appointment->save();
return back();
}
public function logout(){
\Auth::logout();
return redirect(route('show_homepage'));
}
public function processAppointment(Request $request)
{
$rules = array(
// 'pet' => 'required|',
'vet' => 'required|'
// 'service' => 'required|',
// 'data' => 'required|',
// 'hour' => 'required|'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to(route("add_appointment"))
->withErrors($validator);
} else {
$appointmentdata = array(
'admin_id' => Input::get('vet'),
'animal_id' => Input::get('pet'),
'service_id' => Input::get('service'),
'date' => Input::get('data'),
'hour' => Input::get('hour'),
'client_id' => \Auth::user()->client->id,
'medic_id' => 1
);
$appointment = new Appointment($appointmentdata);
$message = "";
$messageSucces = "";
try {
$appointment->save();
$messageSucces = "Programarea a fost adaugata cu succes!";
} catch (QueryException $exception) {
$message = "Eroare query";
}
return redirect(route("add_appointment"))->withInput()->withErrors(new MessageBag([
'registeringWithError' => [
$message
],
'registeringSuccess' => [
$messageSucces
]
]));
}
}
public function cancelAppointment($id)
{
$appointment = Appointment::find($id);
if (!$appointment) {
abort(404);
}
$appointment->delete();
return back();
}
public function modifyService($id){
$service = Service::find($id);
if (!$service) {
abort(404);
}
$service->name = Input::get('modifyServiceName');
$service->admin()->updateExistingPivot($service, ['price' => Input::get('modifyServicePrice')], false);
$service->save();
return back();
}
public function deleteService($id){
$service = Service::find($id);
if (!$service) {
abort(404);
}
$service->delete();
return back();
}
public function saveEmergency($id){
$admin = Admin::find($id);
if (!$admin) {
abort(404);
}
$admin->emergency = Input::get('emergency');
$admin->emergency_schedule = (!is_null(Input::get("emergency_program"))) ? Input::get("emergency_program") : "";
$admin->save();
return redirect(route('show_dashbord'));
}
public function addAnimalPage(){
$species = Specie::all();
$races = Race::all();
return view('animals',[
'species' => $species,
'races' => $races
]);
}
public function deleteAnimal($id){
$animal = Animal::find($id);
$animal->delete();
return redirect(route('show_dashbord'));
}
public function addAnimalProcess(){
$animal = new \App\Animal();
$animal->client_id = \Auth::user()->client->id;
$animal->name = (!is_null(Input::get("name"))) ? Input::get("name") : "";
$animal->date_of_birth = (!is_null(Input::get("data"))) ? Input::get("data") : "";
$animal->gender = (!is_null(Input::get("gender"))) ? Input::get("gender") : "";
$animal->specie_id = Input::get('specie');
$animal->race_id = Input::get("race");
$animal->color = (!is_null(Input::get("color"))) ? Input::get("color") : "";
$animal->particular_signs = (!is_null(Input::get("particular_signs"))) ? Input::get("particular_signs") : "";
$animal->identification_code = (!is_null(Input::get("identification_code"))) ? Input::get("identification_code") : "";
try{
$animal->save();
return redirect(route('show_dashbord'));
}
catch(Exception $e){
echo "eroare";
}
return redirect(route('add_animal'));
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class UsersServicesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users_services')->insert([
'admin_id' => 1,
'service_id' => 1,
'price' => 20
]);
DB::table('users_services')->insert([
'admin_id' => 1,
'service_id' => 2,
'price' => 20
]);
DB::table('users_services')->insert([
'admin_id' => 1,
'service_id' => 3,
'price' => 20
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
// $this->call(UsersTableSeeder::class);
// $this->call(AdministratorsTableSeeder::class);
// $this->call(CityTableSeeder::class);
// $this->call(CountyTableSeeder::class);
// $this->call(MedicsTableSeeder::class);
// $this->call(ServicesTableSeeder::class);
// $this->call(UsersMedicsTableSeeder::class);
// $this->call(UsersServicesTableSeeder::class);
// $this->call(AnimalTableSeeder::class);
// $this->call(SpecieTableSeeder::class);
// $this->call(RaceTableSeeder::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Admin;
use App\City;
use App\County;
use App\Http\Commands\FilterByCity;
use App\Http\Commands\FilterByCounty;
use App\Http\Commands\FilterByEmergency;
use App\Http\Commands\FilterByService;
use Illuminate\Http\Request;
class VetController extends Controller
{
public function showVet($id){
$vet = Admin::find($id);
if (!$vet) {
abort(404);
}
return view('cabinet', [
'vet' => $vet
]);
}
public function showAllVetPage(Request $request, Admin $model){
$search = $request->get('searchName');
$filters = [
"county" => $request->get("county"),
"city" => $request->get("city"),
"service" => $request->get("service"),
"emergency" => $request->get("emergency"),
];
$query = $model->newQuery();
//Filter through the Command pattern
$query = dispatch_now(new FilterByCounty($query, $filters));
$query = dispatch_now(new FilterByCity($query, $filters));
$query = dispatch_now(new FilterByService($query, $filters));
$query = dispatch_now(new FilterByEmergency($query, $filters));
if(strlen($search) > 0) {
$query = $query->whereHas('user', function($q) use ($search) {
return $q->where('name', 'like', '%'.$search.'%');
});
}
return view('search_cabinet',[
'vets' => $query->get(),
'search' => $search,
]);
}
public function showEmergency(){
$vets = Admin::where('emergency',true)->get();
return view('emergency',[
'vets' => $vets
]);
}
//
}
<file_sep><?php
use Illuminate\Database\Seeder;
class SpecieTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('species')->insert([
'name' => 'Pechinez',
]);
DB::table('species')->insert([
'name' => 'Rotwailler',
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class ServicesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('services')->insert([
'name' => 'Service 1'
]);
DB::table('services')->insert([
'name' => 'Service 2'
]);
DB::table('services')->insert([
'name' => 'Service 3'
]);
DB::table('services')->insert([
'name' => 'Service 4'
]);
DB::table('services')->insert([
'name' => 'Service 5'
]);
}
}
<file_sep><?php namespace App\Http\Commands;
/**
* Class FilterByCity
* @package App\Http\Commands
*/
class FilterByCity extends FilterByCounty
{
/**
* @return \Illuminate\Database\Query|mixed
*/
public function handle()
{
$city = array_get($this->filters, "city", null);
$query = $this->query;
if (!is_null($city) && 0 < strlen($city)) {
$query = $query->whereHas("user", function ($q) use ($city) {
return $q->where("city", $city);
});
}
return $query;
}
}<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Admin extends Model
{
protected $table = 'administrators';
public function user()
{
return $this->hasOne(User::class, 'id');
}
public function services(){
return $this->belongsToMany(Service::class, 'users_services', 'admin_id', 'service_id')->withPivot(['price']);
}
public function appointments(){
return $this->hasMany(Appointment::class, 'admin_id');
}
//
}
<file_sep><?php
use Illuminate\Database\Seeder;
class CountyTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('county')->insert([
'name' => 'Cluj'
]);
DB::table('county')->insert([
'name' => 'Prahova'
]);
DB::table('county')->insert([
'name' => 'Mures'
]);
DB::table('county')->insert([
'name' => 'Ilfov'
]);
DB::table('county')->insert([
'name' => 'Alba'
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class AnimalTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('animals')->insert([
'client_id' => 1,
'name' => 'Animal 1',
'date_of_birth' => new DateTime('2017-04-04'),
'gender' => 'female',
'specie_id' => 1,
'race_id' => 1,
'color' => 'brown',
'particular_signs' => 'none',
'identification_code' => '872hhjeh'
]);
DB::table('animals')->insert([
'client_id' => 2,
'name' => 'Animal 2',
'date_of_birth' => new DateTime('2017-04-04'),
'gender' => 'female',
'specie_id' => 1,
'race_id' => 1,
'color' => 'brown',
'particular_signs' => 'none',
'identification_code' => '872hhjeh'
]);
DB::table('animals')->insert([
'client_id' => 2,
'name' => 'Animal 3',
'date_of_birth' => new DateTime('2017-04-04'),
'gender' => 'female',
'specie_id' => 1,
'race_id' => 1,
'color' => 'brown',
'particular_signs' => 'none',
'identification_code' => '872hhjeh'
]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Service extends Model
{
public function admin(){
return $this->belongsToMany(Admin::class, 'users_services', 'service_id', 'admin_id')->withPivot(['price']);
}
}
<file_sep><?php namespace App\Http\Middleware;
class CheckAuth
{
public function handle($request, \Closure $next, $guard = null){
if(!\Auth::guard()->user()){
return redirect(route('show_login'));
}
return $next($request);
}
}<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Appointment extends Model
{
protected $table = 'appointments';
protected $fillable = [
'admin_id','client_id','service_id','animal_id','date','hour','confirmation','medic_id'];
//
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function service()
{
return $this->belongsTo(Service::class,'service_id');
}
public function admin()
{
return $this->belongsTo(Admin::class,'admin_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function client()
{
return $this->belongsTo(Client::class, 'client_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function animal()
{
return $this->belongsTo(Animal::class, 'animal_id');
}
}
<file_sep><?php namespace App\Http\Commands;
/**
* Class FilterByService
* @package App\Http\Commands
*/
class FilterByService extends FilterByCity
{
/**
* @return \Illuminate\Database\Query|mixed
*/
public function handle()
{
$service = array_get($this->filters, "service", null);
$query = $this->query;
if (!is_null($service)) {
$query = $query->whereHas("services", function ($servicesQuery) use ($service) {
return $servicesQuery->whereIn("services.id", [intval($service)]);
});
}
return $query;
}
}<file_sep><?php
namespace App\Http\Controllers;
use App\Admin;
use App\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ServiceController extends Controller
{
public function showAllServicesPage(Request $request, Service $model){
$query = $model->newQuery();
$search = $request->get("search");
if (!is_null($search) && 0 < strlen($search)) {
$query = $query->where("name", "like", "%" . $search . "%");
}
$query->orderBy("name", "ASC");
return view('search_services', [
'services' => $query->get()
]);
}
public function showAddAppointmentPage(){
$vets = Admin::all();
$services = [];
foreach ($vets as $vet) {
$services[$vet->id] = $vet->services;
}
$animals = \Auth::user()->client->animals;
return view('appointment',[
'vets' => $vets,
'animals' => $animals,
'services' => json_encode($services)
]);
}
public function showService(){
$services = Service::all();
return view('services',[
'services' => $services
]);
}
public function addService(){
$service_chosen = Input::get('service');
$service_id = null;
if(!is_null($service_chosen) && "" !== $service_chosen){
$service = Service::whereRaw('LOWER(name)="' . $service_chosen .'"')->get()->first();
if(!is_null($service)){
$service_id = $service->id;
}
else {
$service = new Service();
$service->name = $service_chosen;
$service->save();
$service_id = $service->id;
}
}
else {
$service_id = Input::get('service_combo');
}
if(!is_null($service_id)){
$service_exists = \Auth::user()->admin->services()->where('services.id',$service_id)->get()->first();
if(!$service_exists){
\Auth::user()->admin->services()->attach($service_id, [
'price' => Input::get("price")
]);
}
}
return redirect(route("show_dashbord"));
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class CityTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('city')->insert([
'county_id' => 1,
'name' => 'Turda'
]);
DB::table('city')->insert([
'county_id' => 1,
'name' => '<NAME>'
]);
DB::table('city')->insert([
'county_id' => 2,
'name' => 'Campina'
]);
DB::table('city')->insert([
'county_id' => 5,
'name' => 'Alba'
]);
}
}
<file_sep><?php namespace App\Http\Commands;
use Illuminate\Database\Query;
/**
* Class FilterByCounty
* @package App\Http\Commands
*/
class FilterByCounty
{
/**
* @var Query
*/
protected $query;
/**
* @var array
*/
protected $filters;
public function __construct($query, array $filters)
{
$this->query = $query;
$this->filters = $filters;
}
/**
* @return mixed
*/
public function handle()
{
$county = array_get($this->filters, "county", null);
$query = $this->query;
if (!is_null($county) && 0 < strlen($county)) {
$query = $query->whereHas("user", function ($q) use ($county) {
return $q->where("county", $county);
});
}
return $query;
}
}<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'profile_type' => 0,
'name' => 'MadaBuc',
'email' => '<EMAIL>',
'county' => 'Bucuresti',
'city' => 'Bucuresti',
'username' => 'madder',
'password' => bcrypt('<PASSWORD>'),
]);
DB::table('users')->insert([
'profile_type' => 0,
'name' => 'MadaCluj1',
'email' => '<EMAIL>',
'county' => 'Cluj',
'city' => 'Cluj',
'username' => 'madderr',
'password' => bcrypt('<PASSWORD>'),
]);
DB::table('users')->insert([
'profile_type' => 0,
'name' => 'MadaCluj2',
'email' => '<EMAIL>',
'county' => 'Cluj',
'city' => 'Cluj',
'username' => 'madderrre',
'password' => bcrypt('<PASSWORD>'),
]);
DB::table('users')->insert([
'profile_type' => 0,
'name' => 'MadaBuc2Craiova',
'email' => '<EMAIL>',
'county' => 'Bucuresti',
'city' => 'Craiova',
'username' => 'ee',
'password' => bcrypt('<PASSWORD>'),
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class RaceTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('races')->insert([
'specie_id' => 1,
'name' => 'Papion'
]);
DB::table('races')->insert([
'specie_id' => 1,
'name' => 'Papion 2'
]);
DB::table('races')->insert([
'specie_id' => 2,
'name' => 'Rottwailer Race 1'
]);
DB::table('races')->insert([
'specie_id' => 2,
'name' => 'Rottwailer Race 2'
]);
}
}
| 415ca5eb68ea17e076434b180365d8c2650b7dad | [
"PHP"
] | 22 | PHP | maddie143/Vets | ed93b50408ba3156ec27319483276d8f66cab356 | 81d0d6316d0dfc3e7f713cd769bd2f90fd15b634 |
refs/heads/main | <file_sep><?php include "common/header.php" ?>
<div class="management-system">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Management system</h3>
<p class="my-4 text-white">Precise Management System is everything you as a homeowner need - all gathered in one complete rental platform!</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Try Management System for free!</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/mockup.png" class="w-100" />
</div>
</div>
</section>
<div class="col-md-7 mx-auto py-5 text-center content-container-upper-one">
<h3 class="wow fadeInUp" data-wow-duration="2s">Management System</h3>
<p class="wow fadeInUp" data-wow-duration="2s">Rental is suitable both for you who are going to rent out one dormitory, apartment or room in a shared apartment, and for you who are going to rent out many rental homes. Rental allows you to pick and mix the services and tools you want to ensure a simple, profitable and safe rental of housing. Try Management for free for 2 months now!</p>
</div>
<div class="content-container-upper-two">
<div class="container-lg">
<div class="row mx-0 my-md-3 my-5 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>Help in choosing the right tenant</h4>
<p>With integration with Finn.no, you can advertise the rental unit directly on Finn.no. Precise Management System also allows you to credit check relevant tenants if you wish.</p>
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/finn.png" />
</div>
</div>
</div>
<div class="row mx-0 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/bank-id.png" />
</div>
</div>
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>Digital rental contract with BankID signing</h4>
<p>Precise management system gives you access to perhaps the market's simplest and safest digital rental contract. When you are going to rent out your home, a proper lease is important, even if you are only going to rent out a dormitory. Precise Rental ensures digital creation and digital signing of the rental contract - safe for both landlord and tenant.</p>
<a class="btn btn-bg">Try Management System for free!</a>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<div class="container-lg">
<div class="row mx-0">
<div class="col-md-6 banner-content-half wow fadeInUp" data-wow-duration="2s">
<div class="img-holder">
<img src="images/aprila.png" class="w-100 h-100 object-fit-contain" />
</div>
<h2>Deposit account</h2>
<p>You get a cheap, simple and digital deposit account with <NAME> via our partner Aprila Bank</p>
</div>
<div class="col-md-6 banner-content-half wow fadeInDown" data-wow-duration="2s">
<div class="img-holder">
<img src="images/card15.png" class="w-100 h-100 object-fit-contain" />
</div>
<h2>Occupancy protocol and relocation protocol</h2>
<p>The market's crudest digital takeover protocol for documenting the condition of the home when moving in and moving out. Integration with many relevant third parties helps you make the right choices when moving in and out.</p>
</div>
</div>
</div>
</div>
</div>
<div class="content-container-upper-two">
<div class="container-lg">
<div class="row mx-0 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>Automatic invoicing and reminders</h4>
<p>The rent is invoiced to all your tenants monthly. Automatic reminders by SMS and e-mail if the tenant is late in payment. You can also be guaranteed to pay the rent every month, through our partnership with Aprila Bank.</p>
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/mockup.png" />
</div>
</div>
</div>
<div class="row mx-0 my-md-3 my-5 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/mockup.png" />
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>Dashboard and key figures give you a full overview</h4>
<p>Dashboard with many useful key figures about your rental objects, leases and tenants</p>
<a class="btn btn-bg">Try Management System for free!</a>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="banner-icon-inner light-grey-bg">
<h2 class="text-center heading wow fadeInDown" data-wow-duration="2s">Prices and subscription plans</h2>
<div class="container-lg px-md-3 px-0">
<p class="text-center p-text wow fadeInDown" data-wow-duration="2s">You can choose between two versions of Precise Rentals. Precise Management System gives you everything you need for easy rental, and Rent Guarantee gives you guaranteed rent on due date every single month</p>
<div class="row mx-0">
<div class="col-md-6 my-md-5 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Management System</h5>
<h4 class="my-3 sub-heading">49,- <span>per tenancy / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic invoicing of rent from your tenants</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic reminders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Electronic move-in and move-out protocol</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Dashboard with many useful key figures</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Advertising on Finn.no</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check of stakeholders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Termination and termination of agreement</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Much more</span></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
<div class="col-md-6 my-md-5 my-2 px-md-3 px-0 wow fadeInDown" data-wow-duration="2s">
<div class="position-relative overflow-hidden banner-icon-inner-section">
<span class="green-ribbon">Guarantee</span>
<h5>Rent guarantee</h5>
<h4 class="my-3 sub-heading">5%<span> of the rent / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><b>Guaranteed paid every month on due date</b></li>
<li><span class="fa fa-check-circle mr-2"></span><b>Almost all the work is done for you - no administration with collection of rent</b></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li>
<span class="fa fa-check-circle mr-2"></span><span>Access to Felag Rental Management system including the entire tenancy<em class="d-block">(value: 588, - / year)</em></span>
</li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check by tenant
<em class="d-block">(value: 49, - / credit check)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Deposit account included
<em class="d-block">(value: 249, - / deposit account)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Rental insurance included
<em class="d-block">(value: 1188, - / year)</span></em></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/admin-panel-header.php" ?>
<div class="admin-main-content">
<div class="col-xl-4 col-lg-6 col-sm-8 col-11 px-0 my-5 mx-auto forget-password light-box-shadow">
<div class="forget-pass-block-header">
<div class="forget-pass-block-header-inner">
<p class="mb-2 text-white">Forgot your password</p>
<p class="mb-0 text-white">Reset passwords on your account at<br><b>Garantihuset AS</b></p>
</div>
<div class="PolygonRuler"><svg x="0" y="0" viewBox="0 0 2560 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" class="PolygonRuler__SVG"><polygon points="2560 0 2560 100 0 100" class="PolygonRuler__Polygon PolygonRuler__Polygon--fill-white"></polygon></svg></div>
</div>
<form id="forgetPassForm" action="#">
<b class="d-block mb-3">To set a new password for your account, you must fill out the form below</b>
<div class="form-group">
<label for="existUserEmail">Email<span class="required"> *</span></label>
<input id="existUserEmail" name="email" type="text" class="form-control"
placeholder="<EMAIL>">
</div>
<div class="form-group">
<label>Mobile Number<span class="required"> *</span></label>
<div class="row">
<div class="col-md-4 col-5">
<select class="form-control">
<option value="+1">+1</option>
<option value="+91">+91</option>
<option value="+92">+92</option>
<option value="+93">+93</option>
<option value="+47">+47</option>
</select>
</div>
<div class="pl-0 col-md-8 col-7">
<input type="tel" placeholder="Mobile Number" class="form-control">
</div>
</div>
</div>
<div align="center" class="mt-5">
<a href="#" class="w-100 btn btn-bg">Get a new password</a>
</div>
</form>
</div>
</div>
<?php include "common/admin-panel-footer.php" ?>
<file_sep><?php include "common/admin-panel-header.php" ?>
<div class="admin-main-content">
<div class="col-xl-4 col-lg-6 col-sm-8 col-11 px-0 my-5 mx-auto sign-in light-box-shadow">
<div class="sign-in-block-header">
<div class="sign-in-block-header-inner">
<p class="mb-2 text-white">Welcome!</p>
<p class="mb-0 text-white">Please log in to your user account at<br><b>Garantihuset AS</b></p>
</div>
<div class="PolygonRuler"><svg x="0" y="0" viewBox="0 0 2560 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" class="PolygonRuler__SVG"><polygon points="2560 0 2560 100 0 100" class="PolygonRuler__Polygon PolygonRuler__Polygon--fill-white"></polygon></svg></div>
</div>
<form id="signInForm" action="#">
<div class="form-group">
<label for="userEmail">Email<span class="required"> *</span></label>
<input id="userEmail" name="email" type="text" class="form-control"
placeholder="<EMAIL>">
</div>
<div class="form-group">
<label for="userPassword">Password<span class="required"> *</span></label>
<input id="userPassword" name="password" type="text" class="form-control"
placeholder="<PASSWORD>">
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input"
id="remMe">
<label class="custom-control-label" for="remMe">Remember me</label>
</div>
<div align="center" class="my-4">
<a href="#" class="btn btn-bg">Sign in</a>
</div>
<div class="d-flex flex-wrap justify-content-between">
<a href="./forget-password.php" class="btn p-0">Forgot your password?</a>
<a href="./sign-up.php" class="btn p-0">Create new account</a>
</div>
</form>
</div>
</div>
<?php include "common/admin-panel-footer.php" ?>
<file_sep><?php include "common/admin-panel-header.php" ?>
<div class="admin-main-content">
<div class="my-5 sign-up">
<div class="mx-auto col-lg-8">
<div class="panel light-box-shadow">
<div class="panel-body wizard-content">
<form id="signUpForm" action="#" class="tab-wizard wizard-circle wizard clearfix">
<h6>Account</h6>
<section>
<div class="row">
<div class="col-sm-12">
<b>Choose whether you want to use the service as a private landlord, landlord
organized in a company, or as a tenant.</b>
<div class="text-center mt-3 mb-4">
<div class="btn-group btn-group-toggle landlord-choose-options"
data-toggle="buttons">
<label class="btn landlord-group-btns active d-flex flex-column">
<input type="radio" name="options" id="privlord" autocomplete="off"
value="Private landlord" checked/>
<span class="fa fa-home"></span>
<span class="text">Private landlord</span>
</label>
<label class="btn landlord-group-btns d-flex flex-column">
<input type="radio" name="options" id="lanOrgan" autocomplete="off"
value="Landlord organized in company"/>
<span class="fa fa-building"></span>
<span class="text">Landlord organized in company</span>
</label>
<label class="btn landlord-group-btns d-flex flex-column">
<input type="radio" name="options" id="lanTenant" autocomplete="off"
value="Tenant"/>
<span class="fa fa-user"></span>
<span class="text">Tenant</span>
</label>
</div>
</div>
<div class="my-1">
<div class="custom-control custom-checkbox mr-sm-2">
<input type="checkbox" class="custom-control-input"
id="privStatement">
<label class="custom-control-label" for="privStatement">I agree to
the
Terms of Use and the Privacy Statement for the use of Presis Utleie's
digital services</label>
</div>
<div class="custom-control custom-checkbox mr-sm-2">
<input type="checkbox" class="custom-control-input"
id="recInfo">
<label class="custom-control-label" for="recInfo">Yes
please, I
would like to receive information and newsletters from Presis Utleie by
e-mail based on my areas of interest. I can unsubscribe from this again
at
any time.</label>
</div>
</div>
</div>
</div>
</section>
<h6>Profile</h6>
<section>
<b>Please enter information about yourself so that we can create a new user account for you</b>
<div class="row mt-3">
<div class="form-group col-sm-6">
<label for="name-2">First Name</label>
<input id="name-2" name="name" type="text" class="form-control"
placeholder="First Name">
</div>
<div class="form-group col-sm-6">
<label for="lastname-2">Last Name</label>
<input id="lastname-2" name="surname" type="text" class="form-control"
placeholder="Last Name">
</div>
<div class="form-group col-sm-6">
<label for="email-2">Email<span class="required"> *</span></label>
<input id="email-2" name="email" type="text" class="form-control"
placeholder="<EMAIL>">
</div>
</div>
</section>
<h6>Warning</h6>
<section>
<b>Please enter your mobile number. You will receive an SMS with a verification code.</b>
<div class="form-group col-sm-8 px-0 mt-3">
<label>Mobile Number<span class="required"> *</span></label>
<div class="row">
<div class="col-md-3 col-5">
<select class="form-control">
<option value="+1">+1</option>
<option value="+91">+91</option>
<option value="+92">+92</option>
<option value="+93">+93</option>
<option value="+47">+47</option>
</select>
</div>
<div class="pl-0 col-7">
<input type="tel" placeholder="Mobile Number" class="form-control">
</div>
</div>
</div>
</section>
<h6>Finish</h6>
<section>
<b>Verification of mobile.</b>
<div class="form-group col-sm-6 px-0 mt-3">
<label for="name-2">Code from SMS</label>
<input id="name-2" type="number" class="form-control"
placeholder="Verification Code">
</div>
</section>
</form>
</div>
</div>
</div>
</div>
</div>
<?php include "common/admin-panel-footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="occupancy-protocol">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Occupancy protocol and relocation protocol</h3>
<p class="my-4 text-white">Digital takeover protocol to avoid disagreements between landlord and tenant, completely free at Presis Utleie!</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Create user for free now</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/mockup.png" class="w-100" />
</div>
</div>
</section>
<div class="col-lg-9 mx-auto content-container-upper-one">
<div class="row mx-0 py-sm-5 py-4">
<div class="col-sm-9 mt-sm-0 mt-4 order-sm-1 order-2">
<h3 class="mb-md-4 mb-3 wow fadeInUp" data-wow-duration="2s">What is Precise Occupancy Protocol?</h3>
<p class="wow fadeInUp" data-wow-duration="2s">To make moving in as easy as possible, and to best document the condition of the home when moving in / moving out, we offer you free use of our moving-in protocol. The moving-in protocol makes it easy to check that the home is in the right condition both when moving in and moving out, that the deposit and the first rent are in place at the right time.</p>
<p class="wow fadeInUp" data-wow-duration="2s">The moving-in protocol helps both landlord and tenant to make the right choices when moving in and moving out. We recommend all landlords to use our moving-in protocol to avoid disagreements or quarrels with tenants.</p>
<a href="#" class="mt-md-4 mt-2 btn btn-bg wow fadeInUp" data-wow-duration="2s">Create user for free now</a>
</div>
<div class="col-sm-3 order-sm-2 order-1">
<div class="img-holder wow fadeInDown" data-wow-duration="4s">
<img src="https://presisutleie.no/wp-content/uploads/2021/03/Protokoll-Presis-153x300.jpg" class="w-100 h-100 object-fit-contain" />
</div>
</div>
</div>
</div>
<div class="content-container-upper-two">
<div class="container-lg px-md-3 px-0">
<h3 class="text-center wow fadeInDown" data-wow-duration="2s">How can I easily create a move-in protocol now?</h3>
<p class="text-center mb-lg-5 mb-md-4 wow fadeInDown" data-wow-duration="2s">Implementing a move-in with our move-in protocol is easy!</p>
<div class="mx-0 row">
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">1</span>
<h5 class="mb-3 heading">Create a lease or add to an existing lease</h5>
<p class="mb-0">Add and sign a lease in Presis Utleie completely free with BankID signing.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">2</span>
<h5 class="mb-3 heading">The protocol is initiated by the landlord during the move-in</h5>
<p class="mb-0">The landlord opens the link to the move-in protocol that he / she has received by e-mail.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">3</span>
<h5 class="mb-3 heading">Deposit and first rent confirmed</h5>
<p class="mb-0">The landlord and tenant confirm that the deposit and first rent have been paid into the correct account.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">4</span>
<h5 class="mb-3 heading">The rental object is checked</h5>
<p class="mb-0">The home is inspected, and any errors and omissions can be documented with photos and text if desired. An electricity meter is read if the home has its own electricity meter. The tenant can order an electricity agreement directly in the move-in protocol!</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">5</span>
<h5 class="mb-3 heading">Reading and signing of minutes</h5>
<p class="mb-0">The protocol is read by the landlord and tenant, and signed by both parties directly on the unit used.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">6</span>
<h5 class="mb-3 heading">A copy of the signed move-in protocol is sent to both parties</h5>
<p class="mb-0">The landlord and tenant will receive a signed PDF of the moving-in protocol by e-mail. The landlord can now safely hand over the keys to the tenant.</p>
</div>
</div>
</div>
<div align="center" class="wow fadeInUp" data-wow-duration="2s">
<a href="#" class="mt-md-3 btn btn-bg section-btn">Create lease now</a>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><div>
<?php include "common/dashboard-sidebar.php" ?>
<div id="dashboardSidebarRightContent">
<?php include "common/admin-panel-header.php" ?>
<div class="p-4 admin-main-content">
<h4>User Account</h4>
<p><span class="fa fa-home"></span> - <NAME></p>
<div class="row mx-0 py-3 rounded light-box-shadow">
<div class="col-3 nav-pills-container">
<h5>Shortcuts</h5>
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<a class="mb-1 nav-link active" id="v-my-profile-tab" data-toggle="pill" href="#v-my-profile" role="tab" aria-controls="v-my-profile" aria-selected="true">My Profile</a>
<a class="mb-1 nav-link" id="v-settings-tab" data-toggle="pill" href="#v-settings" role="tab" aria-controls="v-settings" aria-selected="false">Settings</a>
<a class="mb-1 nav-link" id="v-subscriptions-tab" data-toggle="pill" href="#v-subscriptions" role="tab" aria-controls="v-subscriptions" aria-selected="false">Subscriptions</a>
<a class="nav-link" id="v-order-tab" data-toggle="pill" href="#v-order" role="tab" aria-controls="v-order" aria-selected="false">Order</a>
</div>
</div>
<div class="col-9">
<div class="tab-content" id="v-pills-tabContent">
<div class="tab-pane fade show active" id="v-my-profile" role="tabpanel" aria-labelledby="v-my-profile-tab">
<form class="needs-validation" novalidate>
<div class="mb-4 d-flex flex-wrap align-items-center justify-content-between">
<h5 class="mb-0">My profile</h5>
<a class="btn btn-bg">Edit</a>
</div>
<p class="text-muted">Here you will find an overview of your personal information and what is visible to others.</p>
<div class="avatar-wrapper">
<img class="profile-pic" id="uploadedImage" src=""/>
<div class="upload-button">
<span class="fa fa-plus profile-img-uploaded-icon"></span>
</div>
<input class="file-upload" name="avatar" type="file" accept="image/*"/>
</div>
<h6>Contact information</h6>
<div class="form-row">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" placeholder="<NAME>" class="form-control" />
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" placeholder="<NAME>" class="form-control" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Email</label>
<input type="email" placeholder="<EMAIL>" class="form-control" />
</div>
<div class="form-group col-md-6">
<label>Mobile Number</label>
<input type="tel" placeholder="Mobile Number" class="form-control" />
</div>
</div>
<h6 class="mt-3">Address</h6>
<div class="form-row">
<div class="form-group col-md-6">
<label>Gate</label>
<input type="text" placeholder="Gate" class="form-control" />
</div>
<div class="form-group col-md-6">
<label>Place</label>
<input type="text" placeholder="Place" class="form-control" />
</div>
</div>
</form>
</div>
<div class="tab-pane fade" id="v-settings" role="tabpanel" aria-labelledby="v-settings-tab">
<div class="mb-4 d-flex flex-wrap align-items-center justify-content-between">
<h5 class="mb-0">Settings</h5>
<a class="btn btn-bg">Save</a>
</div>
<p class="text-muted">Here you will find an overview of your settings</p>
<h6>Agree</h6>
<div class="row">
<div class="col-md-9">
<b class="text-muted">subscribe to newsletter</b>
<p class="text-muted">Precise Rentals will send you relevant news to your email address</p>
</div>
<div class="col-md-3 text-right">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="agreeYes">
<label class="custom-control-label" for="agreeYes"></label>
</div>
</div>
</div>
<h6>Settings</h6>
<div class="row">
<div class="col-md-9">
<b class="text-muted">Copy of email to tenant about payment of rent</b>
<p class="text-muted">When the tenant receives monthly payment information about rent, you as the landlord can receive an email with information about this</p>
</div>
<div class="col-md-3 text-right">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="payYes">
<label class="custom-control-label" for="payYes"></label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-9">
<b class="text-muted">Notification of unpaid rent</b>
<p class="text-muted">You as a landlord can receive notification of unpaid rent 5 days after the payment deadline</p>
</div>
<div class="col-md-3 text-right">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="unPayYes">
<label class="custom-control-label" for="unPayYes"></label>
</div>
</div>
</div>
<h6>Payment card</h6>
<p class="text-muted">No payment card is stored on your profile</p>
</div>
<div class="tab-pane fade" id="v-subscriptions" role="tabpanel" aria-labelledby="v-subscriptions-tab">
<h5>Subscriptions</h5>
<p class="text-muted">Here you will find an overview of your subscriptions</p>
<p class="text-muted text-center">No subscription found</p>
</div>
<div class="tab-pane fade" id="v-order" role="tabpanel" aria-labelledby="v-order-tab">
<h5>Order</h5>
<p class="text-muted">Here you will find an overview of your orders</p>
<p class="text-muted text-center">No order found</p>
</div>
</div>
</div>
</div>
</div>
<?php include "common/admin-panel-footer.php" ?>
</div>
<script>
$(function () {
/*dasboard sidebar*/
$(".sidebar-links").each(function () {
var currentUrlBase = window.location.href.split('/').pop();
var activeUrlBase = $(this).attr("href").split('/').pop();
if (currentUrlBase == activeUrlBase && currentUrlBase!=undefined && activeUrlBase!=undefined) {
$(this).addClass("nav-underline-pg");
$(this).parent().addClass('active');
$(this).children('img').addClass("img-hover");
}
});
$('#dashboardSidebar .side-nav .side-nav-links li').on('click', function () {
var $this = $(this);
$this.toggleClass('opend').siblings().removeClass('opend');
if ($this.hasClass('opend')) {
$this.find('.side-nav-dropdown').slideToggle('fast');
$this.siblings().find('.side-nav-dropdown').slideUp('fast');
$this.tooltip('disable');
} else {
$this.find('.side-nav-dropdown').slideUp('fast');
$this.tooltip('enable');
}
});
$('#dashboardSidebar .side-nav .close-aside').on('click', function () {
$('#' + $(this).data('close')).addClass('show-side-nav');
contents.removeClass('margin');
});
/*dasboard sidebar*/
/*Avatar upload*/
var readURL = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#uploadedImage').attr('src', e.target.result);
$('.header-profile-pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function () {
readURL(this);
});
$(".upload-button").on('click', function () {
$(this).siblings('.file-upload').click();
});
/*Avatar upload*/
});
</script>
</div>
<file_sep><?php include "common/header.php" ?>
<div class="rent-guarantee">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Rent guarantee from Aprila Bank</h3>
<p class="my-4 text-white">Do you drive, or do you want to rent, but think it is too much to think about? Rent guarantee is guaranteed a product for you!</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Create user for free now!</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/bank-id.png" class="w-100" />
</div>
</div>
</section>
<div class="content-container-upper-two">
<div class="col-md-8 mx-auto px-md-3 px-0">
<div class="mx-0 row">
<div class="mb-sm-4 mb-3 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<div class="mb-2 img-holder">
<img src="images/aprila.png" class="w-100 h-100 object-fit-contain">
</div>
<h5 class="mb-3 heading">Guaranteed paid on due date each month</h5>
<p class="mb-0">The rent is invoiced automatically and is guaranteed in your account until the due date every month. This also applies in cases where the tenant is behind with payment. In the event of non-payment by the tenant, you are guaranteed rent on account on the due date every month for up to 6 months.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<div class="mb-2 img-holder">
<img src="images/aprila.png" class="w-100 h-100 object-fit-contain">
</div>
<h5 class="mb-3 heading">Rental insurance</h5>
<p class="mb-0">Including rental insurance that covers damage to the home, costs in the event of theft or embezzlement of the tenant, or costs in the event of eviction of the tenant. The rental insurance is offered by If Forsikring and covers costs in addition to the coverage from the deposit up to NOK 500,000.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<div class="mb-2 img-holder">
<img src="images/aprila.png" class="w-100 h-100 object-fit-contain">
</div>
<h5 class="mb-3 heading">Deposit account</h5>
<p class="mb-0">A deposit account is created automatically upon signing the rental contract - completely without administration on your part. Aprila Bank ensures that the tenant transfers 3 months' rent to the deposit account before moving in.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<div class="mb-2 img-holder">
<img src="images/aprila.png" class="w-100 h-100 object-fit-contain">
</div>
<h5 class="mb-3 heading">Credit check by tenant</h5>
<p class="mb-0">Included in the rent guarantee, the tenant is credit-checked under the auspices of Experian, to ensure that you have a payable tenant without payment remarks.</p>
</div>
</div>
</div>
</div>
</div>
<div class="content-container-upper-three">
<div class="container-lg px-md-3 px-1">
<h3 class="text-center mb-4 wow fadeInDown" data-wow-duration="2s">That's how simple Aprila Rent Guarantee is</h3>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<h5>Create a user in Precise Rental</h5>
<p class="mb-0">To access the Aprila Rent Guarantee, you must be a user of <NAME>.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">1</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">2</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<h5>Verification and onboarding</h5>
<p class="mb-0">You verify with BankID, answer a few simple questions, and sign a rent guarantee agreement with Aprila Bank.</p>
</div>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<h5>Create a lease and add a tenant</h5>
<p class="mb-0">Create a lease, add a tenant, and sign the lease with BankID.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">3</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">4</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<h5>Get the lease approved by Aprila Bank</h5>
<p class="mb-0">Aprila Bank spends up to one day approving the lease, but typically this is much faster.</p>
</div>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<h5>Deposit account is created automatically</h5>
<p class="mb-0">The deposit account is created automatically in the tenant's name. The tenant is automatically sent a request for payment on a deposit corresponding to 3 months' rent.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">5</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">6</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<h5>The tenancy starts and you are guaranteed the rent on account every month</h5>
<p class="mb-0">The rent is invoiced automatically and is guaranteed in your account until the due date every month. This also applies in cases where the tenant is behind with payment. In the event of non-payment by the tenant, you are guaranteed rent on account on the due date every month for up to 6 months.</p>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="banner-icon-inner light-grey-bg">
<h2 class="mb-4 text-center heading wow fadeInDown" data-wow-duration="2s">Questions and answers about Rent Guarantee</h2>
<div class="container-lg px-md-3 px-0">
<div class="accordion" id="rentGuaranteeFaqs">
<div class="card">
<div class="p-0 card-header">
<h5 class="mb-0 p-3 d-flex justify-content-between collapsing-bar" data-toggle="collapse" data-target="#rentGuaranteeFaqsOne">
What does the Rent Guarantee cost, and what do I get for this price?
<span class="fa fa-plus"></span>
</h5>
</div>
<div id="rentGuaranteeFaqsOne" class="collapse" data-parent="#rentGuaranteeFaqs">
<div class="card-body">
<p>You pay 5% of the monthly rent for the rent guarantee. This guarantees you payment on due dates every month (for up to 6 months in the event of a forced deviation or similar), automatic invoicing of the rent, rental insurance, deposit account, credit check of the tenant, and access to the Precise Management System.</p>
</div>
</div>
</div>
<div class="card">
<div class="p-0 card-header">
<h5 class="mb-0 p-3 d-flex justify-content-between collapsing-bar" data-toggle="collapse" data-target="#rentGuaranteeFaqsTwo">
Can I rent to anyone?
<span class="fa fa-plus"></span>
</h5>
</div>
<div id="rentGuaranteeFaqsTwo" class="collapse" data-parent="#rentGuaranteeFaqs">
<div class="card-body">
<p>You choose which tenant you want to rent to. In order to offer the rent guarantee, on the other hand, it is a requirement that the tenant does not have payment remarks, has a Norwegian birth number or D-number, and must be able to sign the lease with BankID.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="contact-us">
<section class="banner">
<div class="banner-content">
<div class="col-md-8 mx-auto p-md-5 p-4 banner-content-block wow fadeInLeft" data-wow-duration="2s">
<h3 class="banner-heading">Help and support</h3>
<p class="mt-4 mb-0 text-white">Feel free to send us an e-mail and we will help you as soon as possible! PS: Precise Rental is still in beta, and we develop the support pages as we receive questions from users.</p>
</div>
</div>
</section>
<div class="banner-icon">
<div class="banner-icon-inner light-grey-bg">
<h2 class="mb-md-4 text-center heading wow fadeInUp" data-wow-duration="2s">Contact Us</h2>
<div class="container-lg px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="row mx-0 justify-content-center">
<div class="my-md-0 my-2 px-0 col-lg-7 col-md-9">
<div class="banner-icon-inner-section">
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" placeholder="<NAME>" class="form-control" />
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" placeholder="<NAME>" class="form-control" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Email<span class="required"> *</span></label>
<input type="email" placeholder="<EMAIL>" class="form-control" />
</div>
<div class="form-group col-md-6">
<label>Mobile Number<span class="required"> *</span></label>
<input type="tel" placeholder="Mobile Number" class="form-control" />
</div>
</div>
<div class="form-group">
<label>Description <span class="required">*</span></label>
<textarea class="form-control" placeholder="Description..."></textarea>
</div>
<div align="center">
<button type="submit" class="mt-4 btn btn-bg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep>"# felag-frontend"
<file_sep><?php include "common/header.php" ?>
<div class="collection-rent">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Precise, safe and easy collection of rent from your tenants</h3>
<p class="my-4 text-white">Collecting rent has never been easier!</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Try Management System Now!</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/bank-id.png" class="w-100" />
</div>
</div>
</section>
<div class="col-md-7 mx-auto py-5 text-center content-container-upper-one">
<h3 class="wow fadeInUp" data-wow-duration="2s">Collection of rent</h3>
<p class="wow fadeInUp" data-wow-duration="2s">Precise Rental ensures that the rent is invoiced to all your tenants monthly. Automatic reminders by SMS and e-mail if the tenant is late with payment. You can also be guaranteed to pay the rent every single month on due date, through our partnership with Aprila Bank . Regardless of whether you choose Rent Guarantee from Aprila Bank or only use the Precise Management System, fully automatic invoicing of all your tenants is included.</p>
<h3 class="wow fadeInUp mt-5" data-wow-duration="2s">As a landlord and user of the Precise Management System, you have two choices when it comes to collecting the rent</h3>
</div>
<div class="content-container-upper-two">
<div class="container-lg">
<div class="row mx-0 my-md-3 my-5 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>Precise Management System:</h4>
<ul class="list-style-none">
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>You collect the rent yourself if the tenant does not pay the rent</span></li>
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>You carry out all processes in connection with any forced deviation and eviction should this occur</span></li>
</ul>
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/finn.png" />
</div>
</div>
</div>
<div class="row mx-0 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/bank-id.png" />
</div>
</div>
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<h4>April Rent Guarantee</h4>
<ul class="list-style-none">
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>The rent is invoiced automatically and is guaranteed in your account until the due date every month. This also applies in cases where the tenant is behind with payment. In the event of non-payment by the tenant, you are guaranteed rent on account on the due date every month for up to 6 months.</span></li>
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>No administration with collection of rent</span></li>
<li class="mb-2 d-flex align-items-baseline"><span class="fa fa-check-circle mr-2"></span><span>Assistance in the entire coercive waiver and eviction process if this should be relevant</span></li>
</ul>
<a class="btn btn-bg">Try Management System for free!</a>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="banner-icon-inner">
<h2 class="text-center heading wow fadeInUp" data-wow-duration="2s">Prices and subscription plans</h2>
<p class="text-center p-text wow fadeInUp" data-wow-duration="2s">Everything from a completely simple and digital rental contract, to guaranteed rent due every single month</p>
<div class="container-lg px-md-3 px-0">
<div class="row mx-0">
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Simple rental contract</h5>
<h4 class="my-3 sub-heading">For free</h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
</ul>
<a class="w-100 mt-4 mb-3 btn btn-bg">Select</a>
<small class="d-block text-center">Only 1 free rental contract per customer</small>
</div>
</div>
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5 class="heading">Recommended</h5>
<h4 class="my-3 sub-heading">49,- <span>per tenancy / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic invoicing of rent from your tenants</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic reminders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Electronic move-in and move-out protocol</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Dashboard with many useful key figures</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Advertising on Finn.no</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check of stakeholders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Termination and termination of agreement</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Much more</span></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInDown" data-wow-duration="2s">
<div class="position-relative overflow-hidden banner-icon-inner-section">
<span class="green-ribbon">Guarantee</span>
<h5>Rent guarantee</h5>
<h4 class="my-3 sub-heading">5%<span> of the rent / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li>
<span class="fa fa-check-circle mr-2"></span><span>Access to Felag Rental Management system including the entire tenancy<em class="d-block">(value: 588, - / year)</em></span>
</li>
<li><span class="fa fa-check-circle mr-2"></span><span>Guaranteed paid every month on due date</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>No administration with collection of rent</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check by tenant
<em class="d-block">(value: 49, - / credit check)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Deposit account included
<em class="d-block">(value: 249, - / deposit account)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Rental insurance included
<em class="d-block">(value: 1188, - / year)</span></em></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="home">
<section class="banner">
<div class="banner-content">
<h1 class="banner-heading wow fadeInUp" data-wow-duration="2s">Home rental made safe and easy for you and your tenants</h1>
<h4 class="banner-sub-heading wow fadeInUp" data-wow-duration="2s">Organize your rental business today!</h4>
<a href="#" class="btn btn-bg banner-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</section>
<div class="img-holder wow fadeInDown" data-wow-duration="2s">
<img src="images/mockup.png" />
</div>
<div class="mb-lg-0 mb-4 content-container-upper-one">
<div class="container text-center">
<h2 class="wow fadeInDown" data-wow-duration="2s">How does it work?</h2>
<p class="wow fadeInDown" data-wow-duration="2s">It is easy to get started with Felag management system</p>
<div class="row mx-0 content-container-inner justify-content-center">
<div class="col-lg-4 col-md-6 my-lg-5 my-2 wow fadeInUp" data-wow-duration="2s">
<a href="#" class="d-inline-block text-reset text-decoration-none inner-block">
<div class="content-container-inner-section">
<img src="https://w7.pngwing.com/pngs/312/1018/png-transparent-orange-blue-and-black-logo-logo-circle-technology-circle-blue-text-information-technology-thumbnail.png" />
<h6>Digital lease</h6>
<p>Rental contract simple, secure and digital, signed with BankID!</p>
</div>
</a>
</div>
<div class="col-lg-4 col-md-6 my-lg-5 my-2 wow fadeInDown" data-wow-duration="2s">
<a href="#" class="d-inline-block text-reset text-decoration-none inner-block">
<div class="content-container-inner-section">
<img src="https://w7.pngwing.com/pngs/312/1018/png-transparent-orange-blue-and-black-logo-logo-circle-technology-circle-blue-text-information-technology-thumbnail.png" />
<h6>Complete management system</h6>
<p>Felag Management System is everything you as a homeowner need - all gathered in one complete rental platform!</p>
</div>
</a>
</div>
<div class="col-lg-4 col-md-6 my-lg-5 my-2 wow fadeInUp" data-wow-duration="2s">
<a href="#" class="d-inline-block text-reset text-decoration-none inner-block">
<div class="content-container-inner-section">
<img src="https://w7.pngwing.com/pngs/312/1018/png-transparent-orange-blue-and-black-logo-logo-circle-technology-circle-blue-text-information-technology-thumbnail.png" />
<h6>Deposit guarantee</h6>
<p>Do you drive, or do you want to rent, but think it is too much to think about? Rent guarantee is guaranteed a product for you!</p>
</div>
</a>
</div>
</div>
</div>
</div>
<div class="content-container-upper-two">
<div class="container-lg">
<div class="row mx-0 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/mockup.png" />
</div>
</div>
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<p>Web-based management system</p>
<h4>Felag management system</h4>
<p>Felag Rental is suitable both for you who are going to rent out one dormitory, apartment or room in a shared apartment, and for you who are going to rent out many rental homes. Felag Rental allows you to pick and mix the services and tools you want to ensure a simple, profitable and safe rental of housing. Try Felag Management for free for 2 months now!</p>
<a class="btn btn-bg">Get started now!</a>
</div>
</div>
</div>
<div class="row mx-0 my-md-3 my-5 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-section">
<p>Lease with BankID signing</p>
<h4>Easy with bankID signing</h4>
<p>Felag Rental gives you access to perhaps the market's simplest and safest digital rental contract. When you are going to rent out your home, a proper rental contract is important, even if you are only going to rent out a dormitory. Felag Rental ensures digital creation and digital signing of the rental contract - safe for both landlord and tenant.</p>
<a class="btn btn-bg">Get started now!</a>
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/bank-id.png" />
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="banner-icon-inner">
<h2 class="text-center wow fadeInUp" data-wow-duration="2s">Prices and subscription plans</h2>
<p class="text-center wow fadeInUp" data-wow-duration="2s">Everything from a completely simple and digital rental contract, to guaranteed rent due every single month</p>
<div class="container-lg px-md-3 px-0">
<div class="row mx-0">
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Simple rental contract</h5>
<h4 class="my-3 sub-heading">For free</h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
</ul>
<a class="w-100 mt-4 mb-3 btn btn-bg">Select</a>
<small class="d-block text-center">Only 1 free rental contract per customer</small>
</div>
</div>
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInDown" data-wow-duration="2s">
<div class="position-relative overflow-hidden banner-icon-inner-section">
<span class="green-ribbon">Guarantee</span>
<h5>Rent guarantee</h5>
<h4 class="my-3 sub-heading">5%<span> of the rent / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li>
<span class="fa fa-check-circle mr-2"></span><span>Access to Felag Rental Management system including the entire tenancy<em class="d-block">(value: 588, - / year)</em></span>
</li>
<li><span class="fa fa-check-circle mr-2"></span><span>Guaranteed paid every month on due date</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>No administration with collection of rent</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check by tenant
<em class="d-block">(value: 49, - / credit check)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Deposit account included
<em class="d-block">(value: 249, - / deposit account)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Rental insurance included
<em class="d-block">(value: 1188, - / year)</span></em></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Recommended</h5>
<h4 class="my-3 sub-heading">49,- <span>per tenancy / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic invoicing of rent from your tenants</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic reminders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Electronic move-in and move-out protocol</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Dashboard with many useful key figures</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Advertising on Finn.no</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check of stakeholders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Termination and termination of agreement</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Much more</span></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="content-container-upper-two">
<div class="container-lg">
<div class="row mx-0 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/mockup.png" />
</div>
</div>
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-section">
<p>Collection of rent</p>
<h4>Safe and easy collection of rent</h4>
<p>Felag Rental ensures that the rent is invoiced to all your tenants monthly. Automatic reminders by SMS and e-mail if the tenant is late in payment. You can also be guaranteed to pay the rent every single month on due date, through our partnership with Aprila Bank. Regardless of whether you choose Rent Guarantee from Aprila Bank or only use the Felag Management System, fully automatic invoicing of all your tenants is included.</p>
<a class="btn btn-bg">Get started now!</a>
</div>
</div>
</div>
<div class="row mx-0 mt-3 align-items-center content-container-inner">
<div class="col-md-6 wow fadeInDown" data-wow-duration="2s">
<div class="content-container-inner-section">
<p>Rent guarantee from Aprila Bank</p>
<h4>Guaranteed paid on due date each month</h4>
<p>Do you drive, or do you want to rent, but think it is too much to think about? Rent guarantee is guaranteed a product for you!</p>
<a class="btn btn-bg">Get started now!</a>
</div>
</div>
<div class="col-md-6 wow fadeInUp" data-wow-duration="2s">
<div class="content-container-inner-img">
<img src="images/bank-id.png" />
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">YouIt's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="deposit-account">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Occupancy protocol and relocation protocol</h3>
<p class="my-4 text-white">Digital takeover protocol to avoid disagreements between landlord and tenant, completely free at Presis Utleie!</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Create user for free now</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/aprila.png" class="w-100" />
</div>
</div>
</section>
<div class="col-md-7 mx-auto py-5 text-center content-container-upper-one">
<h3 class="wow fadeInUp" data-wow-duration="2s">Precise security and security deposit</h3>
<p class="wow fadeInUp" data-wow-duration="2s">As a landlord, you should always have some form of security for your tenants. You can set up a deposit account via our partner Aprila Bank from NOK 0!</p>
</div>
<div class="banner-icon">
<div class="banner-icon-inner">
<p class="text-center wow fadeInUp l-spacing-6px" data-wow-duration="2s">3 CHOICES</p>
<h2 class="text-center wow fadeInUp" data-wow-duration="2s">How to set up a deposit account with Presis Utleie?</h2>
<div class="container-lg px-md-3 px-0">
<div class="row mx-0">
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Deposit account free of charge via Aprila Bank if you are a Rent Guarantee customer</h5>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span><b>If you choose a rent guarantee from Aprila Bank, we will make sure to get a 3 month deposit from your tenant</b> - you pay nothing for the deposit account if you are a Rent Guarantee customer</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span><b>Access to Precise Rental Management system including the entire tenancy</b><em class="d-block">(value: 588, - / year)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><b>Guaranteed paid every month on due date</b></li>
<li><span class="fa fa-check-circle mr-2"></span><b>No administration with collection of rent</b></li>
<li><span class="fa fa-check-circle mr-2"></span><span><b>Digital rental contract</b> with e-signing</span></li>
</ul>
<a class="w-100 mt-4 mb-3 btn btn-bg">Read more about Aprila Rent Guarantee</a>
<small class="d-block text-center">5% of the rent / month</small>
</div>
</div>
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInDown" data-wow-duration="2s">
<div class="position-relative overflow-hidden banner-icon-inner-section">
<h5>Deposit account via Aprila Bank: Coming!</h5>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>The deposit account from Aprila Bank is in development these days and is just around the corner!</span></li>
</ul>
</div>
</div>
<div class="col-md-4 my-md-5 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Deposit account or other security in another bank or institution</h5>
<ul class="list-style-none">
<li>If you do not want a Rent Guarantee from Aprila Bank, then the following is of course also possible to enter in the rental contract:</li>
<li><span class="fa fa-check-circle mr-2"></span><span><b>Deposit account in another bank:</b> Enter the account number for the deposit account in the rental contract, and it will automatically appear in both the rental agreement on your pages</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span><b>Deposit guarantee in another bank or NAV guarantee:</b> Enter information about the guarantee and who the guarantee issuer is in the rental contract, and it will appear both in the rental agreement and on your pages</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span><b>No security:</b> Of course not recommended, but it is possible to choose no security if both the landlord and tenant agree on this.</span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="content-container-upper-two">
<div class="container-lg px-md-3 px-0">
<h3 class="mb-4 text-center wow fadeInDown" data-wow-duration="2s">Useful information about deposit account</h3>
<div class="mx-0 row">
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Coverage for unpaid rent and costs for damages and the like</h5>
<p class="mb-0">Deposit account is the landlord's security for unpaid rent and any costs the landlord incurs in connection with damage to the home, or costs related to eviction.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Maximum 6 month deposit</h5>
<p class="mb-0">It is not allowed to demand more than six months' deposit according to Rent Act §3-5.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Created in the tenant's name</h5>
<p class="mb-0">The deposit amount must be deposited in a separate deposit account, created in the tenant's name. The tenant is the owner of the account, and earns earned interest paid to him.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Not binding until the agreed security has been established</h5>
<p class="mb-0">The lease agreement is not binding on the landlord as long as the agreed security is not established. If the agreed security is not in order before moving in, this is to be regarded as a material breach of the lease, and the lease can be terminated by the landlord unless otherwise agreed.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Landlord bears the cost of creating a deposit account</h5>
<p class="mb-0">Any expenses related to the establishment of a deposit account will be covered by the landlord, cf. the Rent Act § 3-5.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<h5 class="mb-3 heading">Depositumsgaranti</h5>
<p class="mb-0">As an alternative to a deposit, a guarantee can be created. A guarantee works in the same way as a deposit, but here the landlord's counterparty in the event of a conflict will be an insurance company. The advantage for tenants when using a guarantee is that you pay a smaller lump sum. Remember that the guarantee has a limited duration, and if the tenant lives in the home for many years, you may have to renew the guarantee.</p>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="precise-rent-contract">
<section class="banner">
<div class="row mx-0 banner-content">
<div class="col-md-6 wow slideInLeft" data-wow-duration="2s">
<div class="p-md-5 p-4 banner-content-block">
<h3 class="banner-heading">Free, digital lease with bankID signing</h3>
<p class="my-4 text-white">Rental contract simple, secure and digital, signed with BankID.</p>
<a href="#" class="w-100 btn btn-bg banner-btn">Create lease now</a>
</div>
</div>
<div class="col-md-6 mt-md-0 mt-4 wow bounceInUp" data-wow-duration="2s">
<img src="./images/bank-id.png" class="w-100" />
</div>
</div>
</section>
<div class="col-md-7 mx-auto py-5 text-center content-container-upper-one">
<h3 class="wow fadeInUp" data-wow-duration="2s">Easy with bankID signing</h3>
<p class="wow fadeInUp" data-wow-duration="2s">Precise Rental gives you access to perhaps the market's simplest and safest digital rental contract. When you are going to rent out your home, a proper lease is important, even if you are only going to rent out a dormitory. Precise Rental ensures digital creation and digital signing of the lease - safe for both landlord and tenant.</p>
</div>
<div class="content-container-upper-two">
<div class="container-lg px-md-3 px-0">
<h3 class="text-center mb-4 wow fadeInDown" data-wow-duration="2s">Why choose Precise Lease?</h3>
<div class="mx-0 row">
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">1</span>
<h5 class="mb-3 heading">Digital</h5>
<p class="mb-0">You create the entire rental contract easily on your own PC, mobile or tablet - zero pen and paper, zero nonsense.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">2</span>
<h5 class="mb-3 heading">Lots of great tips and advice</h5>
<p class="mb-0">You will be guided through the entire process from A to Z - we help you make sure that you choose the most appropriate choices, and that you avoid breaking the rent law.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">3</span>
<h5 class="mb-3 heading">Signing with BankID</h5>
<p class="mb-0">Signing of the rental contract with BankID. This makes the signing process simple, safe and smooth for both landlord and tenant.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">4</span>
<h5 class="mb-3 heading">Legally approved lease</h5>
<p class="mb-0">Our rental contact safeguards the Rent Act, as well as the best interests of both the landlord and tenant. Secure lease for both parties. The lease is based on the Consumer Council's lease.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">5</span>
<h5 class="mb-3 heading">Everything stored digitally</h5>
<p class="mb-0">After signing the rental contract, you will have access to a PDF of the file, which you will have stored digitally with all signatures in place.</p>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="number">6</span>
<h5 class="mb-3 heading">For free!</h5>
<p class="mb-0">No hidden fees, no nonsense. Rent contract with BankID signing is completely free at Presis Utleie (maximum 1 lease free per customer).</p>
</div>
</div>
</div>
<div align="center" class="wow fadeInUp" data-wow-duration="2s">
<a href="#" class="mt-md-3 btn btn-bg section-btn">Create lease now</a>
</div>
</div>
</div>
<div class="content-container-upper-three">
<div class="container-lg px-md-3 px-1">
<h3 class="text-center mb-4 wow fadeInDown" data-wow-duration="2s">That's how easy it is to create a Precise Rental Contract</h3>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<p class="mb-0">Enter the address of the rental object you want to rent. Information such as farm number and use number is retrieved automatically from the Mapping Authority, so you do not need to think about this.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">1</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">2</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<p class="mb-0">Select the start date (and any end time) of the rental agreement, the rental amount, and to which account you want to have the rent paid.</p>
</div>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<p class="mb-0">Enter the e-mail address of the tenant and press send!</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">3</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">4</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<p class="mb-0">The tenant receives a link by e-mail and opens it. When the tenant has read over the rental agreement, he / she signs super easily with BankID.</p>
</div>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<p class="mb-0">You will receive a link by e-mail with information that the tenant has signed the tenancy agreement. You sign the agreement with BankID.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">5</span>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="col-lg-5 number-outer wow fadeInRight" data-wow-duration="2s">
<span class="ml-lg-auto number">6</span>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInRight" data-wow-duration="2s">
<div class="h-100 block-content block-content-left">
<p class="mb-0">Both you and the tenant get access to the signed document digitally in PDF.</p>
</div>
</div>
</div>
<div class="mx-0 row justify-content-md-center position-relative">
<div class="mb-sm-4 mb-3 col-lg-5 wow fadeInLeft" data-wow-duration="2s">
<div class="h-100 block-content block-content-right">
<p class="mb-0">You will receive a link by e-mail with information that the tenant has signed the tenancy agreement. You sign the agreement with BankID.</p>
</div>
</div>
<div class="col-lg-1 text-center">
<Span class="seperator">|</Span>
</div>
<div class="col-lg-5 number-outer wow fadeInLeft" data-wow-duration="2s">
<span class="number">7</span>
</div>
</div>
</div>
</div>
<div class="content-container-upper-four">
<div class="container-lg px-md-3 px-1">
<h3 class="text-center wow fadeInDown" data-wow-duration="2s">Contents of the lease</h3>
<p class="text-center wow fadeInDown" data-wow-duration="2s">The lease contract for Presis Utleie contains all the elements that a traditional lease contract contains.</p>
<div class="mx-0 row">
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Information about the property and the rental object</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Information about landlord and tenant</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Information about furnishing, house rules, electricity, internet and the like</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">The type and length of the tenancy</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Rent amount (including any supplements such as electricity and water), rent account and due date</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Bonding time and notice period</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Deposit type, deposit size and deposit account number</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Custom content</h6>
</div>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6 wow fadeInUp" data-wow-duration="2s">
<div class="h-100 light-box-shadow block-content">
<span class="mr-3 fa fa-check-circle"></span>
<h6 class="mb-0">Reference to the legislation, as well as the parties' obligations in the tenancy</h6>
</div>
</div>
</div>
<div align="center" class="wow fadeInUp" data-wow-duration="2s">
<a href="#" class="mt-md-3 btn btn-bg section-btn">Create lease now</a>
</div>
</div>
</div>
<!-- <div class="content-container-upper-five">
<div class="container-lg px-md-3 px-0">
<h3 class="mb-4 text-center">also read</h3>
<div class="mx-0 row justify-content-center">
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6">
<a href="#" class="text-reset text-decoration-none d-inline-block h-100 light-box-shadow block-content">
<div class="img-container">
<img src="images/banner-img.jpg" class="w-100 h-100 object-fit-cover" />
</div>
<div class="p-3">
<h5 class="mb-3">Rent contract - Security for landlord and tenant</h5>
<p class="mb-0">Read about why you should have a good, written rental contract.</p>
</div>
</a>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6">
<a href="#" class="text-reset text-decoration-none d-inline-block h-100 light-box-shadow block-content">
<div class="img-container">
<img src="images/banner-img.jpg" class="w-100 h-100 object-fit-cover" />
</div>
<div class="p-3">
<h5 class="mb-3">Rent contract - Security for landlord and tenant</h5>
<p class="mb-0">Read about why you should have a good, written rental contract.</p>
</div>
</a>
</div>
<div class="mb-sm-4 mb-3 col-lg-4 col-sm-6">
<a href="#" class="text-reset text-decoration-none d-inline-block h-100 light-box-shadow block-content">
<div class="img-container">
<img src="images/banner-img.jpg" class="w-100 h-100 object-fit-cover" />
</div>
<div class="p-3">
<h5 class="mb-3">Rent contract - Security for landlord and tenant</h5>
<p class="mb-0">Read about why you should have a good, written rental contract.</p>
</div>
</a>
</div>
</div>
</div>
</div>-->
</div>
<?php include "common/footer.php" ?>
<file_sep><?php include "common/header.php" ?>
<div class="prices">
<section class="banner">
<div class="banner-content">
<div class="col-md-8 mx-auto p-md-5 p-4 banner-content-block wow fadeInLeft" data-wow-duration="2s">
<h3 class="banner-heading">Prices and subscription</h3>
<p class="mt-4 mb-0 text-white">You can choose from three different versions of Precise Rentals. Simple lease is for you who only need a lease here and now. Precise Management System is for you who want control over your tenancies, and Rent Guarantee is for you who want to make the least of the job yourself.</p>
</div>
</div>
</section>
<div class="banner-icon">
<div class="banner-icon-inner light-grey-bg">
<h2 class="text-center heading wow fadeInUp" data-wow-duration="2s">Prices and subscription plans</h2>
<p class="text-center p-text wow fadeInUp" data-wow-duration="2s">Everything from a completely simple and digital rental contract, to guaranteed rent due every single month</p>
<div class="container-lg px-md-3 px-0">
<div class="row mx-0">
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5>Simple rental contract</h5>
<h4 class="my-3 sub-heading">For free</h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
</ul>
<a class="w-100 mt-4 mb-3 btn btn-bg">Select</a>
<small class="d-block text-center">Only 1 free rental contract per customer</small>
</div>
</div>
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInDown" data-wow-duration="2s">
<div class="position-relative overflow-hidden banner-icon-inner-section">
<span class="green-ribbon">Guarantee</span>
<h5>Rent guarantee</h5>
<h4 class="my-3 sub-heading">5%<span> of the rent / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Access to Felag Management System for free for 2 months</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Digital rental contract with e-signing</span></li>
<li>
<span class="fa fa-check-circle mr-2"></span><span>Access to Felag Rental Management system including the entire tenancy<em class="d-block">(value: 588, - / year)</em></span>
</li>
<li><span class="fa fa-check-circle mr-2"></span><span>Guaranteed paid every month on due date</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>No administration with collection of rent</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check by tenant
<em class="d-block">(value: 49, - / credit check)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Deposit account included
<em class="d-block">(value: 249, - / deposit account)</em></span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Rental insurance included
<em class="d-block">(value: 1188, - / year)</span></em></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
<div class="col-md-4 my-md-0 my-2 px-md-3 px-0 wow fadeInUp" data-wow-duration="2s">
<div class="banner-icon-inner-section">
<h5 class="heading">Recommended</h5>
<h4 class="my-3 sub-heading">49,- <span>per tenancy / month</span></h4>
<ul class="list-style-none">
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic invoicing of rent from your tenants</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Automatic reminders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Electronic move-in and move-out protocol</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Dashboard with many useful key figures</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Advertising on Finn.no</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Credit check of stakeholders</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Termination and termination of agreement</span></li>
<li><span class="fa fa-check-circle mr-2"></span><span>Much more</span></li>
</ul>
<a class="w-100 mt-4 btn btn-bg">Select</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="banner-icon">
<div class="text-center banner-icon-inner">
<h2 class="wow fadeInUp" data-wow-duration="2s">Get started with Felag Rentals for free now!</h2>
<p class="wow fadeInUp" data-wow-duration="2s">You can create your first rental contract in less than 2 minutes.</p>
<a class="btn banner-icon-btn wow fadeInUp" data-wow-duration="2s">It's completely free!</a>
</div>
</div>
</div>
<?php include "common/footer.php" ?>
<file_sep>$(function() {
// Add minus icon for collapse element which is open by default
$(".collapse.show").each(function () {
$(this)
.prev(".card-header")
.find(".fa")
.addClass("fa-minus")
.removeClass("fa-plus");
});
// Toggle plus minus icon on show hide of collapse element
$(".collapse").on("show.bs.collapse", function () {
$(this)
.prev(".card-header")
.find(".fa")
.removeClass("fa-plus")
.addClass("fa-minus");
}).on("hide.bs.collapse", function () {
$(this)
.prev(".card-header")
.find(".fa")
.removeClass("fa-minus")
.addClass("fa-plus");
});
/*wow animation*/
wow = new WOW(
{
boxClass: 'wow', // default
animateClass: 'animated', // default
offset: 0, // default
mobile: true, // default
live: true // default
}
)
wow.init();
/*wow animation*/
/*footer*/
var currentYear = (new Date).getFullYear();
$('#current-year').text(currentYear);
/*footer*/
/*header view, if user not at page top*/
if ($(window).scrollTop() != 0) {
$('.header-navbar').addClass('bg-white light-box-shadow');
if ($(window).width() >= 992) {
$('.sign-in-btn').css({'border': '2px solid #48a955', 'color': '#48a955'});
}
$('.header-navbar .navbar-links .nav-link').css({'color': '#000', 'text-shadow': 'unset'});
$('.header-navbar .navbar-brand .feelag-logo').css('filter', 'invert(1)');
}
/*header view, if user not at page top*/
$(window).on('scroll', function () {
/*header view on scroll*/
$('.header-navbar').addClass('bg-white light-box-shadow');
if ($(window).width() >= 992) {
$('.sign-in-btn').css({'border': '2px solid #48a955', 'color': '#48a955'});
if ($(window).scrollTop() == 0) {
$('.sign-in-btn').css({'border': '2px solid #FFF', 'color': '#FFF'});
}
}
$('.header-navbar .navbar-links .nav-link').css({'color': '#000', 'text-shadow': 'unset'});
$('.header-navbar .navbar-brand .feelag-logo').css('filter', 'invert(1)');
if ($(window).scrollTop() == 0) {
$('.header-navbar').removeClass('bg-white light-box-shadow');
$('.header-navbar .navbar-links .nav-link').css({'color': '', 'text-shadow': ''});
$('.header-navbar .navbar-brand .feelag-logo').css('filter', '');
}
/*header view on scroll*/
});
if ($(window).width() >= 992) {
/*header navbar link hover effect*/
$(".header-navbar .navbar-nav .nav-item.dropdown").hover(function () {
$(this).addClass("show");
$(this).find(".dropdown-menu").addClass("show");
}, function () {
$(this).removeClass("show");
$(this).find(".dropdown-menu").removeClass("show");
});
/*header navbar link hover effect*/
}
$(window).resize(function () {
if ($(window).width() >= 992) {
/*header navbar link hover effect*/
$(".header-navbar .navbar-nav .nav-item.dropdown").hover(function () {
$(this).addClass("show");
$(this).find(".dropdown-menu").addClass("show");
}, function () {
$(this).removeClass("show");
$(this).find(".dropdown-menu").removeClass("show");
});
/*header navbar link hover effect*/
}
});
});
| 807196880dab870d3448dfe3cef5c960a732879a | [
"Markdown",
"JavaScript",
"PHP"
] | 15 | PHP | AsfandRanglerz/leieadmin-frontend | 39a007dcb911ca4c0c4601c60f04881647418215 | 51c4c66c448d4890027519845d64bce9b9ce89ad |
refs/heads/master | <file_sep>export interface Note {
id ?: number;
title?: string;
body: string;
entity_id: number;
entity_type: string;
}<file_sep>import EntityLocation from "./EntityLocation";
export default interface Character {
id?: number;
name: string;
race: string;
age: number;
appearance: string;
party_member: boolean;
friendly: boolean;
location?: EntityLocation;
}<file_sep>
export default class QuestValidator {
validateCreate(quest: any) {
if (!quest) {
alert("Please add some quest information");
return false;
}
if (!quest.name) {
alert("Please add a name");
return false;
}
if (!quest.description) {
alert("Please add a description");
return false;
}
if (!quest.type) {
alert("Please add a type");
return false;
}
return true;
}
}<file_sep>export default interface EntityLocation {
id?: number;
name: string;
friendly: string;
}<file_sep># DND Journal
## Running the project
`npm install`
`npm start`
Hosted on [http://localhost:3000](http://localhost:3000)
## Create mock server
`npm install -g json-server`
`json-server --watch db.json --port 3004`
API on [http://localhost:3004](http://localhost:3004)<file_sep>import {AppRequest} from "./AppRequest";
import {Quest} from "../types/Quest";
export default class QuestRequest extends AppRequest {
getQuests() {
return super.get('/quest/');
}
getQuestNotes(quest: Quest) {
return super.get(`/quest/${quest.id}/notes`)
}
createQuest(quest: any) {
return super.post('/quest/', quest);
}
updateQuest(quest: any) {
return super.put(`/quest/${quest.id}`, quest);
}
}<file_sep>import {QuestStatus} from "./QuestStatus";
import {QuestType} from "./QuestType";
export interface Quest {
id?: number;
name: string;
description: string;
quest_status: QuestStatus;
quest_type: QuestType;
} | 5a3b5fa47dc8e3af8933be6c5c48fb58e23b8e50 | [
"Markdown",
"TypeScript"
] | 7 | TypeScript | JamesMcClelland/DND-Journal | 09e49e9dd4a22ab07bb8e8d8cc0fb845a9a98f4b | 205f1a88a4c08572744274477f98b5c39835cae0 |
refs/heads/master | <repo_name>umng/Learn-to-Program<file_sep>/Java/CTS_SFDC/workspace/IO - Read Stream and Identify Patterns/src/Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
int i = 0, n;
String s = "";
Scanner sc = new Scanner(System.in);
ArrayList<String> search = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("team.txt"));
System.out.println("Enter number of words");
n = Integer.parseInt(sc.nextLine());
System.out.println("Enter the strings to be searched");
while(i < n) {
search.add(sc.nextLine());
i++;
}
sc.close();
while((i = br.read()) != -1) {
s += (char)i;
}
br.close();
System.out.println("Given string is " + s);
for(String sr : search) {
System.out.println("Word:" + sr + " Count:" + getNoOfPatterns(s, sr));
}
}
private static int getNoOfPatterns(String s, String search) {
int i = 0, x = 0;
while(x != -1) {
x = s.indexOf(search, x);
if(x != -1) {
i++;
x += search.length();
}
}
return i;
}
}
<file_sep>/Java/CTS_SFDC/workspace/String Builder 1/src/UserMainCode.java
public class UserMainCode {
public static void display(String firstName, String lastName) {
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(firstName.charAt(0)).toUpperCase());
sb.append(firstName.substring(1).toLowerCase());
sb.append(" ");
sb.append(lastName.toUpperCase());
System.out.println(sb.toString());
}
}
<file_sep>/c_cpp/afterSummer/JTG Prepare/checkMirrorTree.cpp
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
typedef struct node{
int data;
node *left;
node *right;
}tNode;
tNode* createNode(int data)
{
tNode* n = new tNode();
n->data=data;
n->left=NULL;
n->right=NULL;
return n;
}
bool checkMirror(tNode *root1, tNode *root2)
{
if(!root1 && !root2)
return true;
else if( (!root1 && root2) || (root1 && !root2) )
return false;
if(root1->data == root2->data)
return (checkMirror(root1->left, root2->right) && checkMirror(root1->right, root2->left));
else
return false;
}
int main(int argc, char const *argv[])
{
tNode *root1=NULL, *root2=NULL;
root1 = createNode(1);
root1 -> left = createNode(2);
root1 -> right = createNode(3);
root1 -> left -> left = createNode(4);
root1 -> left -> right = createNode(5);
root1 -> right -> left = createNode(6);
root1 -> right -> right = createNode(7);
root2 = createNode(1);
root2 -> right = createNode(2);
root2 -> left = createNode(3);
root2 -> right -> right = createNode(4);
root2 -> right -> left = createNode(5);
root2 -> left -> right = createNode(6);
root2 -> left -> left = createNode(7);
// root2 -> left -> left -> right = createNode(7);
string ans = checkMirror(root1, root2) ? "True" : "False";
cout<<ans<<endl;
return 0;
}<file_sep>/c_cpp/c/day 2/dupliactes in sorted array.cpp
#include<iostream>
using namespace std;
int fir,las,flag=0;
void first(int arr[],int key,int high)
{
int low=0;
int mid;
while(low<=high){
mid=(low+high)/2;
if(arr[mid]==key)
{
flag=1;
fir=mid;
high=mid-1;
}
else if(arr[mid]>key)
high=mid-1;
else low=mid+1;
}
}
void last(int arr[],int key,int high)
{
int low=0;
int mid;
while(low<=high){
mid=(low+high)/2;
if(arr[mid]==key)
{
las=mid;
low=mid+1;
}
else if(arr[mid]>key)
high=mid-1;
else low=mid+1;
}
}
int main()
{
int ar[100],key,len,index;
cout<<"Enter array length = ";
cin>>len;
cout<<" Enter Array \n";
for(int i=0;i<len;i++)
{
cin>>ar[i];
}
cout<<"\nEnter the key to find";
cin>>key;
first(ar,key,len-1);
last(ar,key,len-1);
if(flag==1)
cout<<" occurences = "<<las-fir+1;
else cout<<" Element Not Present in array ";
}
<file_sep>/Java/CTS_SFDC/workspace/Player (Split)/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the player details");
s = sc.nextLine();
sc.close();
String[] parts = s.split(",");
Player p = new Player();
p.name = parts[0];
p.country = parts[1];
p.skill = parts[2];
System.out.printf("Player Details :\nPlayer Name : %s\nCountry Name : %s\nSkill : %s", p.name, p.country, p.skill);
}
}
<file_sep>/Web/Static - HTML,CSS,JS/pattern-program/index.js
function runProgram() {
document.getElementById("output").innerHTML = "running Program...";
var items = JSON.parse("[" + document.getElementById("input").value + "]");
var sumMap = [];
var countMap = [];
for (var i in items) {
for (var j in items[i]) {
sumMap.hasOwnProperty(items[i][j])
? (sumMap[items[i][j]] += parseInt(i) + parseInt(j))
: (sumMap[items[i][j]] = parseInt(i) + parseInt(j));
countMap.hasOwnProperty(items[i][j])
? countMap[items[i][j]]++
: (countMap[items[i][j]] = 1);
}
}
// console.log(sumMap);
// console.log(countMap);
var followsPattern = true;
var coordinateValue;
for (var i in sumMap) {
if (coordinateValue) {
if (coordinateValue == sumMap[i] / countMap[i]) {
followsPattern = true;
break;
} else {
followsPattern = false;
}
}
coordinateValue = sumMap[i] / countMap[i];
}
console.log(coordinateValue);
console.log(followsPattern);
document.getElementById("output").innerHTML = followsPattern;
}
<file_sep>/c_cpp/c/day 2/perfectSum.cpp
#include<iostream>
using namespace std;
int c=0;
void perfSum(int arr[],int i,int k,int sum,int key)
{
if(i==k)
{
if(sum==key) c++;
}
else
{
perfSum(arr,i+1,k,sum+arr[i],key);
perfSum(arr,i+1,k,sum,key);
}
}
int main()
{
int arr[]={2,4,1,3,5,6,-1};
perfSum(arr,0,7,0,4);
cout<<c;
}
<file_sep>/c_cpp/c/day 1/Untitled1.cpp
#include<iostream>
using namespace std;
#include<stdio.h>
main()
{
int a[9]={-2,1,-3,4,-1,2,1,-5,4};
int high=0,sum;
for(int i=0;i<9;i++)
{
sum=0;
for(int j=i;j<9;j++)
{
sum=sum+a[j];
if(sum>high)
high=sum;
}
}
cout<<high;
}
<file_sep>/c_cpp/beforeSummer/prep_class/DP/0-1SnapsackProblem.c
#include <stdio.h>
int A[100][100] = {0};
int c = 0, s = 0;
int max(int x, int y)
{
return (x > y) ? x : y;
}
int knapSack(int cap, int P[], int W[], int n)
{
c++;
if(cap <= 0) return 0;
if(n < 0) return 0;
else
{
if(A[cap][n] != 0)
{
return A[cap][n];
}
if(W[n] <= cap)
A[cap][n] = max( P[n] + knapSack(cap - W[n], P, W, n - 1), knapSack(cap, P, W, n - 1) );
else
A[cap][n] = knapSack(cap, P, W, n - 1);
return A[cap][n];
}
}
int main(int argc, char const *argv[])
{
int n = 5;
int capacity = 17;
int P[] = {10, 25, 4, 3, 2};
int W[] = {5, 1, 8, 7, 11};
printf("Maximum Profit:\t%d\n", knapSack(capacity, P, W, n));
printf("Time Complexity:\t%d\n", c);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Innings Class/src/Innings.java
public class Innings {
String number, battingTeam;
Long runs;
public void displayInningsDetails() {
System.out.printf("Innings Details :\nInnings number : %s\nBattingTeam : %s\nRuns scored :%d", number, battingTeam, runs);
}
}
<file_sep>/Python/pythonWorkshop/tushar files/project/app/schema.py
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
item = db.Column(db.String(120), nullable=False)
isComplete = db.Column(db.Boolean, default=False)
def __init__(self, item):
self.item = item
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(120), nullable = False)
def __init__(self, name):
self.name = name
<file_sep>/c_cpp/c/day 4/anagrams.cpp
#include<iostream>
#include<string>
using namespace std;
void perm(string a,string b,int N)
{
if(N==0)
{
cout<<b<<endl;
}
else{
string c;
for(int k=0;k<a.length();k++)
{
c=a;
c.erase(c.begin()+k,c.begin() +k+1);
perm(c,b + a[k],N-1);
}
}
}
int main()
{
string s="ABC";
perm(s,"",3);
}
<file_sep>/c_cpp/afterSummer/Questions/DP/longestCommonSubSequence.cpp
#include <iostream>
using namespace std;
int getMax(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int longestCommonSubSequence(string s1, string s2, int n1, int n2)
{
int dp1[n1] = {0}, dp2[n1] = {0};
if(n1== 0 || n2==0)
return 0;
for (int i = 0; i < n2; i++)
{
for (int j = 0; j < n1; j++)
{
if(s1[i] == s2[j])
dp2[j] = 1 + dp1[j-1];
else
dp2[j] = getMax(dp2[j-1], dp1[j]);
for (int k = 0; k < n1; k++)
{
dp1[k] = dp2[k];
}
}
}
return dp1[n1-1];
}
int main(int argc, char const *argv[])
{
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
cout<<longestCommonSubSequence(s1, s2, s1.length(), s2.length())<<endl;
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/longestCommonSubSequence.cpp
#include <iostream>
using namespace std;
string longestCommonSubSequence(string str1, string str2, int m, int n)
{
int dp[m+1][n+1] = {0};
for (int i = 0; i < m+1; i++)
{
for (int j = 0; j < n+1; j++)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else if(str1[i-1] == str2[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
// cout<<dp[i][j]<<"\t";
}
// cout<<endl;
}
int i=m, j=n;
int len = dp[i][j];
char subSequence[len + 1];
subSequence[len--]='\0';
while(i>=0 && j>=0)
{
if(str1[i-1] == str2[j-1])
{
subSequence[len--] = str1[i-1];
i--;
j--;
}
else if (dp[i-1][j] > dp[i][j-1])
i--;
else
j--;
}
return subSequence;
}
int main(int argc, char const *argv[])
{
string s1 = "GXTXAYB";
string s2 = "AGGTAB";
cout<<longestCommonSubSequence(s1, s2, s1.length(), s2.length())<<endl;
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Display Team Details/src/PlayerDAO.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class PlayerDAO {
public List<Player> getPlayerDetails(int tid,int sid) throws ClassNotFoundException, SQLException {
Connection con = DBConnection.getConnection();
Statement statement = con.createStatement();
String sql = "select p.id, p.name, p.country, s.name as skill, t.name as team from player p, skill s, team t where p.skill_id=s.id and p.team_id=t.id and skill_id=" + sid +" and team_id=" + tid + " order by name;";
ResultSet result = statement.executeQuery(sql);
List<Player> players = new ArrayList<>();
SkillDAO sdo = new SkillDAO();
TeamDAO tdo = new TeamDAO();
while(result.next()) {
players.add(new Player(result.getInt(1), result.getString(2), result.getString(3), sdo.getSkillByName(result.getString(4)), tdo.getTeamByName(result.getString(5))));
}
return players;
}
}
<file_sep>/Java/CTS_SFDC/workspace/Inheritance - Vehicle/src/Vehicle.java
public class Vehicle {
protected String make, vehicleNumber, fuelType;
protected int fuelCapacity, cc;
public Vehicle(String make, String vehicleNumber, String fuelType, int fuelCapacity, int cc) {
super();
this.make = make;
this.vehicleNumber = vehicleNumber;
this.fuelType = fuelType;
this.fuelCapacity = fuelCapacity;
this.cc = cc;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getVehicleNumber() {
return vehicleNumber;
}
public void setVehicleNumber(String vehicleNumber) {
this.vehicleNumber = vehicleNumber;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public int getFuelCapacity() {
return fuelCapacity;
}
public void setFuelCapacity(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
}
public int getCc() {
return cc;
}
public void setCc(int cc) {
this.cc = cc;
}
public void displayMake() {
System.out.printf("***%s***\n", make);
}
public void displayBasicInfo() {
System.out.printf("---Basic Information---\nVehicle Number:%s\nFuel Capacity:%d\nFuel Type:%s\nCC:%d\n", vehicleNumber, fuelCapacity, fuelType, cc);
}
public void displayDetailInfo() {
}
}
<file_sep>/c_cpp/c/day 2/maxArray.cpp
#include<iostream>
using namespace std;
int max(int arr[],int N,int m)
{
if(N<0)
return m;
if(arr[N]>m) m=arr[N];
max(arr,N-1,m);
}
int main()
{
int arr[]={1,2,3,4,5};
cout<<"MAX = " <<max(arr,4,0);
}
<file_sep>/Java/CTS_SFDC/workspace/HTTPSession2p1/src/PlayerBO.java
import java.sql.*;
public class PlayerBO {
public Player validateLogin(String username,String password) throws ClassNotFoundException,SQLException {
//fill the code
Player p=new PlayerDAO().validateLogin(username, password);
return p;
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/Test/test1.c
#include <stdio.h>
int c1, c2, cSum = 0, c;
int getClosest(int n, int a[], int x)
{
int y = 0, i = 0, j = n - 1, sum = -9999;
while(i < j)
{
cSum = sum;
sum = a[i] + a[j];
if(sum == x)
{
c1 = i;
c2 = j;
cSum = x;
break;
}
else if( (x - sum) < (x - cSum) )
{
c1 = i;
c2 = j;
cSum = sum;
// printf("%d\n", cSum);
j--;
}
if(sum <= x)
{
i++;
}
else
{
j--;
}
y++;
c++;
}
}
int main(int argc, char const *argv[])
{
int a[] = {10, 22, 28, 29, 30, 40};
// int a[] = {-10, -5, -2, 0, 6, 9, 11};
getClosest(7, a, 52);
printf("C1:\t%d\nC2:\t%d\nSum:\t%d\nComplexity:\t%d\n", c1, c2, cSum, c);
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/DP/coinChangeProblem.cpp
#include <iostream>
using namespace std;
int dp[10] = {-1};
int getCoins(int c[], int n, int v)
{
if(v == 0){
return 0;
}
int maxCoins = 0;
for (int i = 1; i < n; i++)
{
if(dp[i - 1] == -1)
{
dp[i - 1] = getCoins(coins, n, v - coins[i-1]);
}
}
}
int main(int argc, char const *argv[])
{
int coins[] = {9,6,5,1};
cout<<getCoins(coins, 4, 11)<<endl;
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/array/matrix_mult.c
#include <stdio.h>
int main(int argc, char const *argv[])
{
int a[][2] = { {1, 2}, {3, 4} };
int b[][2] = { {1, 2}, {3, 4} };
int c[2][2] = { {0, 0}, {0, 0} };
int i = 0, j = 0, k = 0;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
for(k = 0; k < 2; k++)
{
c[i][j] += b[k][j] * a[j][k];
}
}
}
//print results
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/null/Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
//fill your code
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/q6.c
#include <stdio.h>
int max(int a, int b)
{
return (a > b) ? a : b;
}
int main(int argc, char const *argv[])
{
int a[] = {2, -1, 5, -3, 9, -9};
int c = 0, maxSum = a[0], temp = a[0], i;
for(i = 1; i < 6; i++)
{
temp = max(temp + a[i], a[i]);
if(temp > maxSum) maxSum = temp;
c++;
}
printf("Maximumu Sum:\t%d\nComplexity:\t%d\n", maxSum, c);
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/HTTPSession2p1/src/Index.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
/**
* Servlet implementation class Index
*/
@WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Index() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//fill the code
PrintWriter out=response.getWriter();
out.println("<html><body><h2>Login</h2>");
out.println("<form action='LoginServlet' method='get'>");
if(request.getParameter("err")!=null)
{
out.println("<div id='errorMsg'>");
out.println(request.getParameter("err"));
out.println("</div>");
}
if(request.getParameter("logout")!=null)
{
out.println("<div id=logoutMsg>");
out.println(request.getParameter("logout"));
out.println("</div>");
}
out.println("UserName <input type='text' id=username name=username width=200px><br>"
+ "Password <input type='<PASSWORD>' id=password name=password width=200px><br>"
+ "<input type='submit' id=Login name=login value='Login' width=200px>"
+ "</form></body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<file_sep>/Java/CTS_SFDC/workspace/Delivey Details/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
Long r;
String bowler, batsman;
Scanner sc = new Scanner(System.in);
System.out.println("Menu\n1.Player details of the delivery\n2.Run details of the delivery");
i = sc.nextInt();
sc.nextLine();
Delivery d = new Delivery();
if(i == 1) {
System.out.println("Enter the bowler name");
bowler = sc.nextLine();
System.out.println("Enter the batsman name");
batsman = sc.nextLine();
d.displayDeliveryDetails(bowler, batsman);
} else if(i ==2) {
System.out.println("Enter the number of runs");
r = sc.nextLong();
d.displayDeliveryDetails(r);
}
sc.close();
}
}
<file_sep>/Java/CTS_SFDC/workspace/HTTPSession2p1/src/LoginServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//fill the code
try {
String username=request.getParameter("username");
String password=request.getParameter("password");
Player p=new PlayerBO().validateLogin(username, password);
if(p!=null)
{
HttpSession session = request.getSession();
session.setAttribute("username",username);
session.setAttribute("password",<PASSWORD>);
request.getRequestDispatcher("/HomeServlet?name="+p.getName()).forward(request, response);
}
else
response.sendRedirect("Index?err=Invalid username or password");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.sendRedirect("Index");
}
}
<file_sep>/Java/CSE406/Stream API/Reduction Operations/StreamMapping.java
import java.util.*;
import java.util.stream.*;
class Employee{
String name;
int pay;
public Employee(String name, int pay){
this.name = name;
this.pay = pay
}
}
class EmployeePay{
int pay;
public EmployeePay(int pay){
this.pay = pay;
}
}
class StreamMapping{
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Satish", 50000));
employees.add(new Employee("Umang", 10000));
employees.add(new Employee("Sagar", 35000));
employees.add(new Employee("Rishabh", 50000));
employees.add(new Employee("Nikunj", 30000));
Stream<EmployeePay> employeePays = list.stream().map( (a) -> )
}
}
<file_sep>/Java/CTS_SFDC/workspace/Transformer Optimus Prime’s Quest/src/UserMainCode.java
public class UserMainCode {
public static String getPosition(int l, String s) {
int x = 0, y = 0;
for(int i=0; i<l; i++) {
if(s.charAt(i) == 'L')
x--;
else if(s.charAt(i) == 'R')
x++;
else if(s.charAt(i) == 'D')
y--;
else if(s.charAt(i) == 'U')
y++;
}
return x + " " + y;
}
}
<file_sep>/Java/CTS_SFDC/workspace/Validation 1/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s;
Scanner sc = new Scanner(System.in);
s = sc.nextLine();
sc.close();
if(UserMainCode.validatePlayer(s.substring(0, s.indexOf(" ")), s.substring(s.indexOf(" ") + 1))) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
<file_sep>/c_cpp/afterSummer/JTG Prepare/findSumPair.cpp
#include <iostream>
using namespace std;
void printSumPair(int a[], int n, int x)
{
int i= 0, j= n-1, sum = 0;
while(i<j)
{
sum = a[i] + a[j];
if(sum == x)
{
cout<<a[i]<<"\t"<<a[j]<<endl;
break;
}
else if(sum > x)
j--;
else
i++;
}
}
int main(int argc, char const *argv[])
{
int a[] = {1,5,10,0,16};
printSumPair(a,sizeof(a)/sizeof(a[0]),6);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Collection-List2(Sorting)/src/Main.java
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static <T> void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
TreeSet<Integer> scores = new TreeSet<>();
n = sc.nextInt();
sc.nextLine();
for(int i=0; i<n; i++) {
scores.add(sc.nextInt());
}
for(int s : scores) {
System.out.println(s);
}
}
}
<file_sep>/c_cpp/c/day 4/rotate matrix.cpp
#include<iostream>
using namespace std;
int main()
{
int a[3][3];
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
cin>>a[i][j];
int temp;
for(int i=0;i<3;i++)
{
for(int j=0;j!=i;j++)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/q8.c
#include <stdio.h>
//find non-repeatable element
int getXOR(int a[], int i, int n)
{
if(i == n) return a[i];
return a[i] ^ getXOR(a, i + 1, n);
}
int main(int argc, char const *argv[])
{
int a[] = {3, 1, 2, 3, 10, 2, 1};
printf("non-repeatable Element:\t%d\n", getXOR(a, 0, 7));
return 0;
}<file_sep>/c_cpp/c/day 4/QUE.cpp
#include<iostream>
using namespace std;
int que[100];
int front=-1,rear=-1;
void ins(int x){
if(rear==100)
cout<<"Overflow";
else{
if(front==-1 && rear==-1)
{
rear++;
que[rear]=x;
front=rear;
}
else{
rear++;
que[rear]=x;
}
}
}
int del()
{
if(front==-1 || front ==rear+1)
cout<<"Underflow";
else{
int x=que[front];
front++;
return x;
}
}
int main()
{
ins(10);
ins(20);
ins(20);
ins(30);
ins(40);
for(int i=0;i<5;i++)
cout<<del();
}
<file_sep>/c_cpp/beforeSummer/prep_class/searching/linearSearch.c
#include <stdio.h>
int c = 0;
int linearSearch(int a[], int key, int n)
{
int i = 0;
for(i = 0; i < n; i++)
{
if(a[i] == key) return i;
c++;
}
return -1;
}
int main(int argc, char const *argv[])
{
int a[] = {2, 3, 1, 7, 0, 5};
int key = 0, n = 6;
printf("Complexity:\t%d\nElement %d is at position:\t%d\n", c, key, linearSearch(a, key, n) );
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Servlet-JDBC -Store the Team Details/src/TeamDAO.java
import java.util.ResourceBundle;
import java.sql.*;
public class TeamDAO {
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String user=rb.getString("db.username");
String pass=rb.getString("db.password");
public void createCity(City city) throws ClassNotFoundException,SQLException
{
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "pass");
String query="insert into city(id,name) values(?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1, city.getId());
ps.setString(2, city.getName());
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {e.printStackTrace();}
}
public Boolean createTeam(Team team)throws ClassNotFoundException,SQLException
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "pass");
String query="insert into team(name,coach,home_city_id,captain) values(?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1, team.getName());
ps.setString(2, team.getCoach());
ps.setInt(3,team.getHomeCity().getId());
ps.setInt(4, team.getCaptain());
int count=ps.executeUpdate();
if(count!=0)
return true;
else
return false;
}
public int getPlayerIdByPlayerName(String name)throws ClassNotFoundException,SQLException
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "pass");
String query="select id from player where name=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1, name);
ResultSet rs=ps.executeQuery();
if(rs.next())
return rs.getInt(1);
else
return 0;
}
public int getCityIdByCityName(String name)throws ClassNotFoundException,SQLException
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "<PASSWORD>");
String query="select id from city where name=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1, name);
ResultSet rs=ps.executeQuery();
if(rs.next())
return rs.getInt(1);
else
return 0;
}
}
<file_sep>/c_cpp/afterSummer/Questions/permutationString.cpp
#include <iostream>
using namespace std;
void permutationString(string &s, int i, int n)
{
if(i == n)
cout<<s<<endl;
else
for (int j = i; j<n; j++)
{
swap(s[i], s[j]);
permutationString(s, i+1, n);
swap(s[i], s[j]);
}
}
int main(int argc, char const *argv[])
{
string s = "abc";
permutationString(s, 0, s.length());
return 0;
}
<file_sep>/c_cpp/afterSummer/Questions/sortBinaryArray.c
//sort a binary array
#include <stdio.h>
int complexity = 0;
int sortBinaryAray(int a[], int len)
{
len--;
int i = 0, j = len;
while( (j - i) > 0)
{
while(a[i] == 0)
{
i++;
complexity++;
}
while(a[j] == 1)
{
j--;
complexity++;
}
if(j > i)
{
a[i] = 0;
a[j] = 1;
i++;
j--;
complexity++;
}
}
}
int main(int argc, char const *argv[])
{
int len = 12, i = 0;
int a[len] = {1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1};
sortBinaryAray(a, len);
//print
for(i = 0; i < len; i++)
{
printf("%d\t", a[i]);
}
printf("\nComplexity:\t%d\n", complexity);
return 0;
}<file_sep>/Python/pythonWorkshop/project/app/apis.py
from flask import jsonify, request
from app import app_api, db
from schema import Todo, User
@app_api.route('/getid', methods=['POST'])
def get_id() :
name = request.json['name']
user = User.query.filter_by(name=name).first()
if not user:
user = User(name)
db.session.add(user)
db.session.commit()
return jsonify({"id": user.id})
@app_api.route('/todos/<int:todoid>', methods=['DELETE'])
@app_api.route('/todos', methods=['POST', 'GET', 'PUT'],defaults = {'todoid':0})
def todos(todoid):
if request.method == 'POST':
return add_todo()
if request.method == 'GET':
return getTodos()
if request.method == 'DELETE':
return deleteTodo(todoid)
def add_todo() :
user_id = request.json['user_id']
item = request.json['item']
user = User.query.get(user_id)
if user is None:
return jsonify(dict(error="user not found"))
todo = Todo(item, user_id)
db.session.add(todo)
db.session.commit()
return jsonify({"status": True}),200
def getTodos():
user_id = int(request.args['userid'])
user = User.query.get(user_id)
if user is None:
return jsonify(dict(error="user not found")),404
# if user is None:
# return jsonify(dict(error="user not found")),404
todos = Todo.query.filter_by(user_id=user_id).all()
# todos_result = []
# for todo in todos:
# todos_result.append(todo.to_dict())
todos_result = [todo.to_dict() for todo in todos]
return jsonify(dict(todos=todos_result))
def deleteTodo(todoid):
todo = Todo.query.get(todoid)
if todo is None:
return jsonify(dict(error="todo not found"))
db.session.delete(todo)
db.session.commit()
return jsonify({"status":"True"})<file_sep>/c_cpp/afterSummer/Questions/DP/pathCountExactlyKConins.cpp
#include <iostream>
using namesace std;
int pathCountDP(int mat[][])
int main(int argc, char const *argv[])
{
int mat[][3] = { {1, 2, 3}, {4, 6, 5}, {3, 2, 1} };
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/array/sumArrayRecursion.c
#include <stdio.h>
int getSum(int a[], int n)
{
if(n == 1) return a[0];
return a[n] + getSum(a, n - 1);
}
int main(int argc, char const *argv[])
{
int a[11] = {-2, 1, -3, 4, -1, 2, 1, -5, 4, -10, 12};
printf("Sum:\t%d\n", getSum(a, 11));
return 0;
}
<file_sep>/c_cpp/afterSummer/JTG Prepare/spiralTraversalTree.cp
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
typedef struct node{
int data;
node *left;
node *right;
}tNode;
tNode* createNode(int data)
{
tNode* n = new tNode();
n->data=data;
n->left=NULL;
n->right=NULL;
return n;
}
void preOrder(tNode *root)
{
if(!root)
return;
cout<<root->data<<" -> ";
preOrder(root->left);
preOrder(root->right);
}
void spiralTraverse(tNode *root)
{
bool flag = false;
queue<tNode*> q;
stack<tNode*> s;
q.push(root);
q.push(NULL);
while(!q.empty() || !s.empty())
{
tNode* temp = q.front();
q.pop();
if(temp!=NULL)
{
cout<<temp->data<<"\t";
if(flag==false)
{
flag = true;
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
else
{
flag = false;
if(temp->right)
q.push(temp->right);
if(temp->left)
q.push(temp->left);
}
}
else
{
cout<<endl;
if(!q.empty())
q.push(NULL);
}
}
}
int main(int argc, char const *argv[])
{
tNode *root =NULL;
root = createNode(1);
root -> left = createNode(2);
root -> right = createNode(3);
root -> left -> left = createNode(4);
root -> left -> right = createNode(5);
root -> right -> left = createNode(6);
root -> right -> right = createNode(7);
// cout<<root->left->data<<endl;
// preOrder(root);
spiralTraverse(root);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Abstract Class I – Shape/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int l, b, r;
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Circle\nSquare\nRectangle\nEnter the shape name");
s = sc.nextLine();
Shape sp;
if(s.equals("Rectangle")) {
System.out.println("Enter the length");
l = sc.nextInt();
sc.nextLine();
System.out.println("Enter the breadth");
b = sc.nextInt();
sc.close();
sp = new Rectangle(s, l, b);
System.out.printf("Area of Rectangle is %.2f", sp.calculateArea());
} else if(s.equals("Square")) {
System.out.println("Enter the side");
l = sc.nextInt();
sc.close();
sp = new Square(s, l);
System.out.printf("Area of Square is %.2f", sp.calculateArea());
} else if(s.equals("Circle")) {
System.out.println("Enter the radius");
r = sc.nextInt();
sc.close();
sp = new Circle(s, r);
System.out.printf("Area of Circle is %.2f", sp.calculateArea());
}
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/HW Questions/Day 3/q1.c
#include <stdio.h>
int getMax(int x, int y)
{
return (x > y) ? x : y;
}
int main(int argc, char const *argv[])
{
int a[] = {2, 2, 4, 6, 2, 3}, n = 6, maxHeight = 6;
int i = 0, j = 0, cnt = 0, maxArea = 0, c = 0;
for(i = 0; i <= maxHeight; i++)
{
cnt = 0;
for(j = 0; j <= n; j++)
{
if(a[j] >= i)
{
cnt++;
maxArea = getMax(maxArea, i * cnt);
}
else
{
maxArea = getMax(maxArea, i * cnt);
cnt = 0;
}
c++;
}
}
printf("Maximum Area:\t%d\nComplexity:%d\n", maxArea, c);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Strike rate/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Double sr;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the strike rate:");
sr = sc.nextDouble();
sc.close();
System.out.printf("The Strike rate of Dhoni is %.2f", Float.parseFloat(sr.toString()));
}
}
<file_sep>/c_cpp/afterSummer/Questions/Tree/rootToLeafPaths.cpp
#include <iostream>
#include <vector>
using namespace std;
typedef struct node
{
int info;
node *left;
node *right;
}tnode;
// typedef struct node tnode;
tnode *createNode(int info, tnode* left = NULL, tnode* right = NULL)
{
tnode* node = new tnode();
node -> info = info;
node -> left = NULL;
node -> right = NULL;
return node;
}
void preOrder(tnode* root)
{
if(!root)
return;
cout<< root -> info<<"\t";
preOrder(root -> left);
preOrder(root -> right);
}
void inOrder(tnode* root)
{
if(!root)
return;
inOrder(root -> left);
cout<< root -> info<<"\t";
inOrder(root -> right);
}
void postOrder(tnode* root)
{
if(!root)
return;
postOrder(root -> left);
postOrder(root -> right);
cout<< root -> info<<"\t";
}
void rootToLeafPaths(tnode *root, std::vector<int> v)
{
v.push_back(root -> info);
if(root -> left == NULL && root -> right == NULL)
{
int n = v.size();
for(int i = 0; i < n; i++)
{
cout<<"\t->\t"<<v.at(i);
}
cout<<endl;
v.pop_back();
return;
}
if(root -> left != NULL)
rootToLeafPaths(root -> left, v);
if(root -> right != NULL)
rootToLeafPaths(root -> right, v);
}
int main(int argc, char const *argv[])
{
tnode *root;
root = createNode(10);
root -> left = createNode(8);
root -> right = createNode(2);
root -> left -> left = createNode(3);
root -> left -> right = createNode(5);
root -> right -> left = createNode(2);
// cout<<endl<<"PreOrder:\t";
// preOrder(root);
// cout<<endl<<"InOrder:\t";
// inOrder(root);
// cout<<endl<<"PostOrder:\t";
// postOrder(root);
// cout<<endl;
std::vector<int> v;
rootToLeafPaths(root, v);
return 0;
}
<file_sep>/c_cpp/c/day 5/maxsum(rec).cpp
#include<iostream>
using namespace std;
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int maxsum(int a[],int n)
{
if(n==0)
{
return a[n];
}
if (n==1)
{
return a[n];
}
max(maxsum(a,n-1),maxsum(a,n-2)+a[n]);
}
main()
{
int a[]={1,2,3,4,5};
int n=5,c;
c=maxsum(a,n);
cout<<c;
}
<file_sep>/c_cpp/c/doubleList.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node* head;
struct node* newNode(int data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> prev = NULL;
newN -> data = data;
newN -> next = NULL;
return newN;
}
void insertNode(int data)
{
if(head == NULL)
{
head = newNode(data);
}
else
{
struct node* trav = head;
struct node* temp = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
temp = newNode(data);
trav -> next = temp;
temp -> prev = trav;
trav = temp;
}
printf("Node Added Succesfully\n");
}
void printNode()
{
struct node* trav = head;
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
printf("%d\n", trav -> data);
while(trav -> next != NULL)
{
trav = trav -> next;
printf("%d\n", trav -> data);
}
}
}
void deleteNode(int data)
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
int i = 0;
if(trav -> next == NULL)
{
if(trav -> data == data)
{
trav = trav -> next;
trav -> prev = NULL;
free(trav);
i = 2;
}
}
else
{
while(trav -> next != NULL)
{
if(trav -> data == data)
{
if(trav -> prev == NULL)
{
head = head -> next;
}
else
{
temp -> next = trav -> next;
(trav -> next) -> prev = temp;
free(trav);
i = 1;
break;
}
}
temp = trav;
trav = trav -> next;
}
}
if(i == 0)
{
printf("Node with value : %d\t NOT FOUND\n", data );
}
else if(i == 1)
{
printf("Node with value : %d\t DELETED Succesfully\n", data );
}
else if(i == 2)
{
printf("Node with value : %d\t DELETED Succesfully. LIST is NULL now.\n", data );
}
}
}
int main(int argc, char const *argv[])
{
head = NULL;
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
insertNode(50);
int x = 1, temp = 0;
printf("***\tLinked List\t***\n");
while(1 == 1)
{
printf("--------------------------------\nEnter your choice.\n1)Print List\n2)Insert Node\n3)Delete Node\n0)Exit\nYour choice: ");
scanf("%d", &x);
if(x == 0)
{
printf("Thank You!\n");
return 0;
}
else if (x == 1)
{
printNode();
}
else if (x == 2)
{
printf("Enter value for new node: ");
scanf("%d", &temp);
insertNode(temp);
}
else if (x == 3)
{
printf("Enter value of node: ");
scanf("%d", &temp);
deleteNode(temp);
}
else
{
printf("INVALID choice... Try Again...\n");
}
}
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Repeated Annotation/src/Roles.java
import java.lang.annotation.*;
@Retention( RetentionPolicy.RUNTIME )
@interface Roles {
Role[] value() default{};
}<file_sep>/c_cpp/c/day 3/Non duplicate in array.cpp
#include<iostream>
using namespace std;
int main()
{
int ar[]={1,3,4,5,2,3,4,1,5};
int x=ar[0];
for(int i=1;i<9;i++ )
x=x^ar[i];
cout<<x;
}
<file_sep>/Java/CTS_SFDC/workspace/List 1/src/Main.java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int m, total = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
m = sc.nextInt();
sc.nextLine();
for(int i = 0; i< m; i++) {
scores.add(sc.nextInt());
}
sc.close();
for(int s : scores) {
total += s;
}
System.out.println(total);
System.out.printf("%.1f", (float)total/m);
}
}
<file_sep>/c_cpp/afterSummer/Questions/Graph/detectCycleInGraph.cpp
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#define MAX 100
using namespace std;
bool static visited[MAX]={false};
bool static currPath[MAX]={false};
int _detectCycleInGraph(std::vector<std::vector<int> > g, int v)
{
visited[v] = true;
// cout<<v<<" -- ";
currPath[v] = true;
for (std::vector<int>::iterator iter = g[v].begin(); iter != g[v].end(); iter++)
{
if(visited[g[v][*iter]] == false)
{
if(_detectCycleInGraph(g, g[v][*iter]) == 1)
{
cout<<v<<"\t";
return 1;
}
}
else if(currPath[*iter])
{
cout<<v<<"\t";
return 1;
}
}
currPath[v] = false;
return 0;
}
void detectCycleInGraph(std::vector<std::vector<int> > g, int first)
{
memset(visited, false, sizeof(bool)*MAX);
_detectCycleInGraph(g, first);
}
int main(int argc, char const *argv[])
{
int n=10;
int color[MAX]={-1};
std::vector<std::vector<int> > graph;
graph.resize(10);
// graph[1].push_back(2);
// graph[1].push_back(3);
// graph[3].push_back(6);
// graph[2].push_back(4);
// graph[2].push_back(5);
// graph[5].push_back(7);
// graph[5].push_back(8);
// graph[5].push_back(9);
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(2);
graph[2].push_back(0);
graph[2].push_back(3);
graph[3].push_back(3);
cout<<endl;
detectCycleInGraph(graph, 1);
return 0;
}<file_sep>/c_cpp/c/doubleEndedQueue.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* head;
struct node* top;
struct node* newNode(int data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void enqueFront(int data)
{
if(head == NULL)
{
head = newNode(data);
top = head;
}
else
{
struct node* trav = top;
trav -> next = newNode(data);
top = trav -> next;
}
printf("Node Added Succesfully\n");
}
void enqueLast(int data)
{
if(top == NULL)
{
top = newNode(data);
head = top;
}
else
{
struct node* trav = head;
trav = newNode(data);
trav -> next = head;
head = trav;
}
printf("Node Added Succesfully\n");
}
void dequeLast()
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
temp = trav;
trav = trav -> next;
head = trav;
free(temp);
printf("POPPED Succesfully\n");
}
}
void dequeFirst()
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = temp;
while(trav -> next != NULL)
{
temp = trav;
trav = trav -> next;
}
// temp = trav;
// trav = trav -> next;
top = temp;
top -> next = NULL;
free(trav);
printf("POPPED Succesfully\n");
}
}
void printNode()
{
struct node* trav = head;
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
printf("%d\n", trav -> data);
while(trav -> next != NULL)
{
trav = trav -> next;
printf("%d\n", trav -> data);
}
}
}
void isEmpty()
{
if(head == NULL)
{
printf("Queue is EMPTY.\n");
}
else
{
printf("Queue is NOT Empty.\n");
}
}
void getFront()
{
if(head == NULL)
{
printf("Queue is EMPTY.\n");
}
else
{
printf("Front is : %d.\n", top -> data);
}
}
void getLast()
{
if(head == NULL)
{
printf("Queue is EMPTY.\n");
}
else
{
printf("Last is : %d.\n", head -> data);
}
}
int main()
{
head = NULL;
printNode();
enqueFront(10);
enqueFront(20);
enqueFront(30);
enqueFront(40);
dequeLast();
dequeLast();
enqueFront(50);
dequeLast();
enqueFront(60);
enqueLast(80);
// dequeFirst();
// dequeFirst();
// dequeLast();
// dequeLast();
isEmpty();
getFront();
getLast();
printNode();
}<file_sep>/c_cpp/c/day 2/permuations Of string.cpp
#include<iostream>
using namespace std;
void combinations(string a,string b,int i,int k)
{
if(i==k){
cout<<b<<endl;
}
else
{
combinations(a,b + a[i],i+1,k);
combinations(a,b,i+1,k);
}
}
int main()
{
string s="ABC";
combinations(s,"",0,3);
}
<file_sep>/c_cpp/afterSummer/Questions/trappingRainWater.cpp
#include <iostream>
using namespace std;
int findWater(int arr[], int n)
{
int left[n];
int right[n];
int water = 0;
left[0] =arr[0];
for (int i = 1; i < n; i++)
left[i] = max(left[i-1], arr[i]);
right[n-1] = arr[n-1];
for (int i = n-2; i >= 0; i--)
right[i] = max(right[i+1], arr[i]);
for (int i = 0; i < n; i++)
{
water += min(left[i], right[i]) - arr[i];
cout<<water<<endl;
}
return water;
}
int getMaxTrapRainWater(int a[], int n)
{
int MAX = 0, curr = 0, prev_curr = 0;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
curr = prev_curr + ( a[i] - a[j] );
prev_curr = curr;
}
if(a[j] >= a[i])
{
MAX = max(MAX, curr);
cout<<a[i]<<"\t"<<a[j]<<"\t->"<<curr<<endl;
curr = 0;
prev_curr = 0;
i = j;
j++;
}
}
}
return MAX;
}
int main(int argc, char const *argv[])
{
int a[] = {0,1,0,2,1,0,1,3,2,1,2,1};
cout<<getMaxTrapRainWater(a, 12)<<endl;
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Player-Team/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s1, s2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the player name");
s1 = sc.nextLine();
System.out.println("Enter the team name");
s2 = sc.nextLine();
sc.close();
UserMainClass.display(s1, s2);
}
}
<file_sep>/c_cpp/c/day 3/queue-as-stack.cpp
#include <iostream>
#include<stdio.h>
using namespace std;
struct stack
{
int a[100];
int top;
} s;
void init_stack()
{
s.top = -1;
}
void pause()
{
char ch;
cin >> ch;
}
void push(int item)
{
if (s.top == 99)
{
printf("Overflow");
pause();
}
else
{
s.top++;
s.a[s.top] = item;
}
}
int peek()
{
if (s.top == -1)
{
printf("Underflow");
pause();
}
else
{
return s.a[s.top];
}
}
void pop()
{
if (s.top == -1)
{
printf("Underflow");
pause();
}
else
{
s.top--;
}
}
int queue_pop()
{
if (s.top == -1)
{
printf("Underflow");
} else
{
int temp = peek();
pop();
if (s.top == -1)
{
return temp;
}
else
{
int bottom = queue_pop();
push(temp);
return bottom;
}
}
}
int main()
{
init_stack();
push(1);
push(2);
push(3);
cout << queue_pop() << endl;
cout << queue_pop() << endl;
}
<file_sep>/Java/CTS_SFDC/workspace/.metadata/version.ini
#Thu Mar 02 16:36:28 IST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.2.v20161124-1400
<file_sep>/c_cpp/beforeSummer/prep_class/stack/sortStack.c
#include <stdio.h>
struct stack
{
int a[20];
int top;
};
struct stack s;
bool isEmpty()
{
if(s.top == -1) return true;
else return false;
}
bool isFull()
{
if(s.top == 19) return true;
else return false;
}
bool push(int x)
{
if(!isFull()) s.a[++s.top] = x;
else return false;
}
bool pop()
{
if(!isEmpty()) s.top--;
else return false;
}
int peek()
{
if(!isEmpty()) return s.a[s.top];
else return false;
}
int main(int argc, char const *argv[])
{
s.top = -1;
push(5);
push(4);
push(2);
push(3);
push(6);
printf("%d\n", dequeue());
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/Test/test3.c
#include <stdio.h>
int flag = 0, c = 0;
int getSum(char x, char y)
{
int a = 0, b = 0;
if(x == '0') a = 0;
else a = 1;
if(y == '0') b = 0;
else b = 1;
int z = 0;
if(a == 0)
{
if(b == 0)
{
if(flag == 1)
{
flag = 0;
return 1;
}
else
{
flag = 0;
return 0;
}
}
else
{
if(flag == 1)
{
flag = 1;
return 0;
}
else
{
flag = 0;
return 1;
}
}
}
else
{
if(b == 0)
{
if(flag == 1)
{
flag = 1;
return 0;
}
else
{
flag = 0;
return 1;
}
}
else
{
if(flag == 1)
{
flag = 1;
return 1;
}
else
{
flag = 1;
return 0;
}
}
}
}
void getBinarySum(char a[], char b[], int n, int m)
{
int i = n, j = m, p = 0; char k;
while(i > 0 && j > 0)
{
// printf("%d\n", flag);
p = getSum(a[i - 1], b[j - 1]);
if(p == 0) k = '0';
else k = '1';
// printf("%c\t%c:\t%c\n", a[i - 1], b[j - 1] , k);
a[i - 1] = k;
i--;
j--;
c++;
}
while(i > 0)
{
p = getSum(a[i - 1], '0');
if(p == 0) k = '0';
else k = '1';
// printf("%c\t%c:\t%c\n", a[i - 1], '0' , k);
a[i - 1] = k;
i--;
c++;
}
while(i > 0)
{
p = getSum(b[j - 1], '0');
if(p == 0) k = '0';
else k = '1';
c++;
// printf("%c\t%c:\t%c\n", b[j - 1], '0' , k);
a[i - 1] = k;
i--;
}
}
int main(int argc, char const *argv[])
{
char a[] = "1";
char b[] = "111";
int n = 3, m = 1;
if(n > m)
{
getBinarySum(a, b, n, m);
if(flag == 1)
printf("Sum is:\t1%s\n", a);
else
printf("Sum is:\t%s\n", a);
}
else
{
getBinarySum(b, a, m, n);
if(flag == 1)
printf("Sum is:\t1%s\n", b);
else
printf("Sum is:\t%s\n", b);
}
printf("Complexity:\t%d\n", c);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/HW Questions/Day 3/queueUsingStack.c
#include <stdio.h>
struct stack
{
int a[20];
int top;
};
struct stack s;
bool isEmpty()
{
if(s.top == -1) return true;
else return false;
}
bool isFull()
{
if(s.top == 19) return true;
else return false;
}
bool push(int x)
{
if(!isFull()) s.a[++s.top] = x;
else return false;
}
bool pop()
{
if(!isEmpty()) s.top--;
else return false;
}
int peek()
{
if(!isEmpty()) return s.a[s.top];
else return false;
}
bool insertAtBottom(int x)
{
if(isEmpty()) push(x);
else
{
int y = peek();
pop();
insertAtBottom(x);
push(y);
}
}
bool enque(int x)
{
return insertAtBottom(x);
}
int dequeue()
{
int x = peek();
pop();
return x;
}
int main(int argc, char const *argv[])
{
s.top = -1;
enque(5);
enque(4);
enque(3);
printf("%d\n", dequeue());
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Player Details(Array of objects)/src/PlayerBO.java
public class PlayerBO {
void displayAllPlayerDetails(Player[] playerList)
{
System.out.println("Player Details");
for(Player p : playerList) {
System.out.println(p);
}
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/stack/reverseStack.c
#include <stdio.h>
struct stack
{
int a[20];
int top;
};
struct stack s1, s2;
bool isEmptyS1()
{
if(s1.top == -1) return true;
else return false;
}
bool isFullS1()
{
if(s1.top == 19) return true;
else return false;
}
bool pushS1(int x)
{
if(!isFullS1()) s1.a[++s1.top] = x;
else return false;
}
bool popS1()
{
if(!isEmptyS1()) s1.top--;
else return false;
}
int peekS1()
{
if(!isEmptyS1()) return s1.a[s1.top];
else return false;
}
bool isEmptyS2()
{
if(s2.top == -1) return true;
else return false;
}
bool isFullS2()
{
if(s2.top == 19) return true;
else return false;
}
bool pushS2(int x)
{
if(!isFullS2()) s2.a[++s2.top] = x;
else return false;
}
bool popS2()
{
if(!isEmptyS2()) s2.top--;
else return false;
}
int peekS2()
{
if(!isEmptyS2()) return s2.a[s2.top];
else return false;
}
bool reverse()
{
if(!isEmptyS1())
{
int y = peekS1();
popS1();
reverse();
pushS2(y);
}
else
{
while(!isEmptyS2())
{
int y = peekS2();
popS2();
pushS2(y);
}
}
}
int main(int argc, char const *argv[])
{
s1.top = -1;
s2.top = -1;
pushS1(5);
pushS1(4);
pushS1(3);
printf("%d\n", peekS1());
reverse();
printf("%d\n", peekS2());
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Inheritance/src/Shape.java
class Shape {
String shapeName;
Shape(String shapeName) {
this.shapeName = shapeName;
}
public String getShapeName() {
return shapeName;
}
public void setShapeName(String shapeName) {
this.shapeName = shapeName;
}
Double calculateArea() {
return (double) 0;
}
}<file_sep>/Java/CTS_SFDC/workspace/HashMap – Wicket Details/src/Main.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String s;
String bowlerName;
Scanner sc = new Scanner(System.in);
LinkedHashMap<String, Wicket> wickets = new LinkedHashMap<>();
do {
System.out.println("Enter the player name");
bowlerName = sc.nextLine();
System.out.println("Enter wickets - seperated by \"|\" symbol");
for(String playerName : getWickets(sc.nextLine())) {
wickets.put(playerName ,new Wicket(playerName, new Bowler(bowlerName)));
}
System.out.println("Do you want to add another player (yes/no)");
s = sc.nextLine();
} while(s.toLowerCase().equals("yes"));
do {
boolean flag = true;
System.out.println("Enter the player name to search");
bowlerName = sc.nextLine();
for(Map.Entry<String, Wicket> m : wickets.entrySet()) {
Wicket w = m.getValue();
if(w.getBowler().getName().equals(bowlerName)) {
if(flag) {
System.out.printf("Player Name : %s\nWickets :\n", bowlerName);
flag = false;
}
System.out.printf("%s\n", w.getPlayerName());
}
}
if(flag)
System.out.printf("No player found with the name %s\n", bowlerName);
System.out.println("Do you want to search another player (yes/no)");
s = sc.nextLine();
} while(s.toLowerCase().equals("yes"));
sc.close();
}
private static ArrayList<String> getWickets(String s) {
ArrayList<String> wickets = new ArrayList<>();
StringTokenizer st = new StringTokenizer(s, "|");
while(st.hasMoreTokens()) {
wickets.add(st.nextToken());
}
return wickets;
}
}
<file_sep>/Java/CTS_SFDC/workspace/Display Team Details/src/SkillBO.java
import java.sql.SQLException;
public class SkillBO {
public Skill getSkillByName(String skill) throws ClassNotFoundException, SQLException {
return new SkillDAO().getSkillByName(skill);
}
}
<file_sep>/c_cpp/c/day 2/sumArray(rec).cpp
#include<iostream>
using namespace std;
int sum(int arr[],int i,int N)
{
if(i==N)
return arr[i];
int m= ( i+N)/2;
return sum(arr,i,m) + sum(arr,m + 1,N);
}
int main()
{
int arr[]={1,2,3,4,5};
cout<<"Sum = " <<sum(arr,0,4);
}
<file_sep>/c_cpp/beforeSummer/prep_class/DP/coinChangeProblem.c
#include <stdio.h>
int min = 9999;
int func(int a[], int i, int x)
{
if(i >= 0)
{
int j = 0;
float k = x / a[i];
for(j = 0; j <= k; j++)
{
int temp = func(a, i + 1, x - (j * a[i]) );
if(temp <= min)
min = temp;
}
return min;
}
else
return 0;
}
int main(int argc, char const *argv[])
{
int a[] = {1, 2, 5, 10};
printf("Minimum Coins:\t%d\n", func(a, 0, 75));
return 0;
}<file_sep>/Java/CSE406/Generics & Collections/List/TestDeque.java
import java.util.*;
class TestDeque{
public static void main(String[] args) {
Deque<Integer> dq = new LinkedList<>();
// REMOVAL FROM EMPTY LIST RETURNS "NULL" //
dq.pollLast();
System.out.println(dq.peekFirst());
dq.offer(20);
dq.offer(0);
dq.offer(30);
// dq.offerFirst(10);
// dq.offerLast(30);
// dq.offerLast(40);
// dq.pollFirst();
// dq.pollLast();
dq.poll();
System.out.println(dq.peekFirst());
System.out.println(dq.peekLast());
// dq.pollLast();
// System.out.println(dq.pollLast());
// System.out.println(dq.peekLast());
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/sorting/quickSort.c
#include <stdio.h>
int partition(int a[], int lower, int upper)
{
int i, p, q, t;
p = lower + 1;
q = upper;
i = a[lower];
while(q >= p)
{
while(a[p] <= i)
p++;
while(a[q] >= i)
q--;
if(q > p)
{
t = a[p];
a[p] = a[q];
a[q] = t;
}
}
t = a[lower];
a[lower] = a[q];
a[q] = t;
return q;
}
void quickSort(int a[], int lower, int upper)
{
int i = 0;
if(upper > lower)
{
i = partition(a, lower, upper);
quickSort(a, lower, i - 1);
quickSort(a, i + 1, upper);
}
}
int main(int argc, char const *argv[])
{
int a[] = {10, 5, 8, 11, 1, 3, 2};
int i = 0, n = 6;
printf("Array:\t");
for(i = 0; i < n; i++)
printf("%d\t", a[i]);
quickSort(a, 0, n);
printf("\n\nSorted Array:\t");
for (int i = 0; i < n; i++)
printf("%d\t", a[i]);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/tree/identifyIdenticalTrees.c
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree *root, *root2, *trav;
int flag = 0;
struct tree *newNode(int data)
{
struct tree *node = (struct tree *) malloc(sizeof(struct tree));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return node;
}
void insertNode(struct tree* head, int data)
{
if(head == NULL)
{
if(head == root)
root = newNode(data);
else
root2 = newNode(data);
return;
}
if(head -> data > data)
{
if(head -> left == NULL)
head -> left = newNode(data);
else
insertNode(head -> left, data);
}
else
{
if(head -> right == NULL)
head -> right = newNode(data);
else
insertNode(head -> right, data);
}
}
void identifyIdentical(struct tree *head, struct tree *head2)
{
if(head == NULL && head2 != NULL )
{
flag = 1;
return;
}
else if(head != NULL && head2 == NULL )
{
flag = 1;
return;
}
if(head != NULL)
{
if(head -> data != head2 -> data)
{
flag = 1;
return;
}
identifyIdentical(head -> left, head2 -> left);
identifyIdentical(head -> right, head2 -> right);
}
}
int main(int argc, char const *argv[])
{
insertNode(root, 12);
insertNode(root, 10);
insertNode(root, 30);
insertNode(root, 25);
insertNode(root, 40);
insertNode(root, 45);
insertNode(root, 41);
insertNode(root, 49);
insertNode(root, 8);
insertNode(root2, 12);
insertNode(root2, 10);
insertNode(root2, 30);
insertNode(root2, 25);
insertNode(root2, 40);
insertNode(root2, 45);
insertNode(root2, 41);
insertNode(root2, 49);
insertNode(root2, 8);
// printTree(root);
// printf("\n\n\n\n");
// printTree(root2);
identifyIdentical(root, root2);
if(flag == 0)
printf("Identical.\n");
else
printf("Not Identical.\n");
return 0;
}
<file_sep>/c_cpp/beforeSummer/prep_class/isomorphics.c
// A C++ program to check if two given trees are isomorphic
#include <iostream>
using namespace std;
/* A binary tree node has data, pointer to left and right children */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Given a binary tree, print its nodes in reverse level order */
bool isIsomorphic(node* n1, node *n2)
{
// Both roots are NULL, trees isomorphic by definition
if (n1 == NULL && n2 == NULL)
return true;
// Exactly one of the n1 and n2 is NULL, trees not isomorphic
if (n1 == NULL || n2 == NULL)
return false;
if (n1->data != n2->data)
return false;
// There are two possible cases for n1 and n2 to be isomorphic
// Case 1: The subtrees rooted at these nodes have NOT been "Flipped".
// Both of these subtrees have to be isomorphic, hence the &&
// Case 2: The subtrees rooted at these nodes have been "Flipped"
return
(isIsomorphic(n1->left,n2->left) && isIsomorphic(n1->right,n2->right))||
(isIsomorphic(n1->left,n2->right) && isIsomorphic(n1->right,n2->left));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return (temp);
}
/* Driver program to test above functions*/
int main()
{
// Let us create trees shown in above diagram
struct node *n1 = newNode(1);
n1->left = newNode(2);
n1->right = newNode(3);
n1->left->left = newNode(4);
n1->left->right = newNode(5);
n1->right->left = newNode(6);
n1->left->right->left = newNode(7);
n1->left->right->right = newNode(8);
struct node *n2 = newNode(1);
n2->left = newNode(3);
n2->right = newNode(2);
n2->right->left = newNode(4);
n2->right->right = newNode(5);
n2->left->right = newNode(6);
n2->right->right->left = newNode(8);
n2->right->right->right = newNode(7);
if (isIsomorphic(n1, n2) == true)
cout << "Yes";
else
cout << "No";
return 0;
}
<file_sep>/c_cpp/beforeSummer/prep_class/Test/test4.c
#include <stdio.h>
#include <stdlib.h>
struct list
{
int data;
struct list *next;
struct list *child;
};
struct list *head;
struct list *newNode(int data)
{
struct list *l = (struct list *) malloc(sizeof(struct list));
l -> data = data;
l -> next = NULL;
l -> child = NULL;
}
struct list insertNextNode(int data, int after)
{
}
struct list insertChildNode(int data, int after)
{
}
int main(int argc, char const *argv[])
{
/* code */
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/q1.c
#include <stdio.h>
int main(int argc, char const *argv[])
{
//input
int n = 5;
int a[n] = {3, 1, 2, 5, 3};
int b[n] = {0};
int i = 0, j = 0, k = 0, c = 0;
for(i = 0; i < n; i++)
{
if( (b[a[i] - 1] += 1) > 1 ) j = a[i];
if( b[i] < 1 ) k = i+1;
c++;
}
//output
printf("A = %d\nB = %d\nComplexity: %d\n", j, k, c);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/linkedList/mergeTwoLists.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *headA, *headB, *trav, *temp;
struct Node *newNode(int data)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNodeA(int data)
{
trav = headA;
if(headA == NULL)
headA = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void insertNodeB(int data)
{
trav = headB;
if(headB == NULL)
headB = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void printListA()
{
trav = headA;
if(headA == NULL)
printf("List is Empty.\n");
else
{
printf("\nListA:\t");
while(trav != NULL)
{
printf("%d\t", trav -> data);
trav = trav -> next;
}
printf("\n\n");
}
}
void printListB()
{
trav = headB;
if(headB == NULL)
printf("List is Empty.\n");
else
{
printf("\nListB:\t");
while(trav != NULL)
{
printf("%d\t", trav -> data);
trav = trav -> next;
}
printf("\n\n");
}
}
struct Node* mergeLists();
int main(int argc, char const *argv[])
{
insertNodeA(3);
insertNodeA(5);
insertNodeA(8);
insertNodeA(6);
insertNodeA(3);
printListA();
insertNodeB(2);
insertNodeB(1);
insertNodeB(7);
insertNodeB(6);
printListB();
return 0;
}<file_sep>/c_cpp/c/day 5/minimumdiference.cpp
#include<iostream>
using namespace std;
main()
{
int min=9999;
int max=-9999;
int a[]={1,2,3,4,5};
for(int i=0;i<5;i++)
{
if(a[i]>max)
{max=a[i];}
if(a[i]<min)
{min=a[i];}
}
cout<<max-min;
}
<file_sep>/Java/CSE406/JDBC/GUIwithDB.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
class GUIwithDB extends JFrame{
private JTextField tfId, tfName, tfCourse, tfMarks;
private JButton btnSave;
public GUIwithDB(){
Container cp = getContentPane();
cp.setLayout(new GridLayout(5,2));
add(new JLabel("Id: "));
tfId = new JTextField(8);
add(tfId);
add(new JLabel("Name: "));
tfName = new JTextField(20);
add(tfName);
add(new JLabel("Course: "));
tfCourse = new JTextField(20);
add(tfCourse);
add(new JLabel("Marks: "));
tfMarks = new JTextField(3);
add(tfMarks);
btnSave = new JButton("Save");
add(btnSave);
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int id = Integer.parseInt(tfId.getText().trim());
String name = tfName.getText().trim();
String course = tfCourse.getText().trim();
int marks = Integer.parseInt(tfMarks.getText().trim());
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mySqlDb","root","mkteq1mu");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into student values(" + id + ",'" + name + "');");
stmt.addBatch("insert into academics values(" + id + ",'" + course + "'," + marks + ");");
stmt.executeBatch();
con.commit();
con.close();
}catch(Exception e){
System.out.println(e);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Student Details");
setSize(300,300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GUIwithDB();
}
});
}
}
<file_sep>/Java/CTS_SFDC/workspace/Comparable - Player Information Based on Player Cap Number/src/Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i = 0, n;
String playername;
String skill;
long capNumber;
Scanner sc = new Scanner(System.in);
ArrayList<Player> players = new ArrayList<>();
System.out.println("Enter number of players:");
n = sc.nextInt();
sc.nextLine();
while(i < n) {
System.out.println("Enter player " + (++i) + " detail");
System.out.println("Enter Name");
playername = sc.nextLine();
System.out.println("Enter Skill");
skill = sc.nextLine();
System.out.println("Enter Cap Number");
capNumber = Long.parseLong(sc.nextLine());
players.add(new Player(playername, skill, capNumber));
}
sc.close();
Collections.sort(players);
System.out.println("Player list after sorting by cap number in descending order");
i = 0;
for(Player p : players) {
System.out.println(p.getPlayername() + "-" + p.getCapNumber());
}
}
}
<file_sep>/c_cpp/afterSummer/Questions/DP/editDistance.cpp
#include <iostream>
using namespace std;
int getMin(int a, int b, int c)
{
if(a<b && a<c)
return a;
else if(b<a && b<c)
return b;
else
return c;
}
int editDistance(string str1, string str2, int m, int n)
{
if(m == 0)
return n;
if(n == 0)
return m;
if(str1[m-1] == str2[n-1])
return editDistance(str1, str2, m-1 , n-1);
// cout<< 1 + getMin(editDistance(str1, str2, m , n-1), editDistance(str1, str2, m-1 , n), editDistance(str1, str2, m-1 , n-1))<<"\t";
return 1 + getMin(editDistance(str1, str2, m , n-1), editDistance(str1, str2, m-1 , n), editDistance(str1, str2, m-1 , n-1));
}
int main(int argc, char const *argv[])
{
string str1 = "SUNDAY";
string str2 = "SATURDAY";
cout<<editDistance(str1, str2, str1.length(), str2.length())<<endl;
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Match Details II/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i = 0, n;
String date;
String teamOne;
String teamTwo;
String venue;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of matches");
n = sc.nextInt();
sc.nextLine();
Match[] matchList = new Match[n];
while(i<n) {
System.out.printf("Enter match %d details\n", ++i);
System.out.println("Enter the match date");
date = sc.nextLine();
System.out.println("Enter the team one");
teamOne = sc.nextLine();
System.out.println("Enter the team two");
teamTwo = sc.nextLine();
System.out.println("Enter the Venue");
venue = sc.nextLine();
matchList[i-1] = new Match(date, teamOne, teamTwo, venue);
}
MatchBO mbo = new MatchBO();
mbo.displayAllMatchDetails(matchList);
System.out.println("Enter the date to be searched");
date = sc.nextLine();
sc.close();
mbo.displaySpecificMatchDetails(matchList, date);
}
}
<file_sep>/c_cpp/c/elimVowels.c
#include<stdio.h>
int main()
{
char s[] = "umang and nikunj";
int i = 0;
for(i = 0; s[i] != '\0'; i++)
{
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
s[i] = ' ';
}
}
printf("%s\n", s);
}<file_sep>/c_cpp/beforeSummer/prep_class/array/maxContSumArray.c
#include <stdio.h>
// //approach 1
// int getMaxSumArray(int a[], int l)
// {
// int i = 0, j = 0, k = 0, sum = 0, lsum = a[0], c = 0;
// //block size of contigous elements
// for(i = 0; i < l; i++)
// {
// //sub arrays
// for(j = 0; j < l - i; j++)
// {
// sum = 0;
// //adding sum
// for (k = j; k <= j + i; k++)
// {
// sum += a[k];
// printf("%d\t", sum);
// c++;
// }
// if(sum > lsum)
// lsum = sum;
// }
// }
// printf("\nComplexity:\t%d\n", c);
// return lsum;
// }
//approach 2
int getMaxSumArray(int a[], int l)
{
int i = 0, j = 0, sum = 0, lsum = a[0], c = 0;
//block size of contigous elements
for(i = 0; i < l; i++)
{
sum = 0;
//sub arrays
for(j = i; j < l; j++)
{
//adding sum
// for (k = i; k <= j; k++)
// {
// sum += a[k];
// printf("%d\t", sum);
// c++;
// }
sum += a[j];
c++;
if(sum > lsum)
lsum = sum;
}
}
printf("\nComplexity:\t%d\n", c);
return lsum;
}
int main(int argc, char const *argv[])
{
int a[11] = {-2, 1, -3, 4, -1, 2, 1, -5, 4, -10, 12};
printf("Sum:\t%d\n", getMaxSumArray(a, 11));
return 0;
}
<file_sep>/c_cpp/beforeSummer/prep_class/stringPermutation.c
#include <stdio.h>
#include <string.h>
void getstringPermutation(char s[], char g[], int sn, int gn)
{
if(strlen(g) == gn)
{
printf("%s\n", g);
}
else
{
sn++;
int i = 0;
for(i = sn; sn <= gn; sn++)
{
char temp[1] = {s[sn]};
getstringPermutation(s, strcat(g, temp), sn, gn);
}
// getstringPermutation(s, g, sn, gn);
}
}
int main(int argc, char const *argv[])
{
char s[] = "lpu";
char g[3] = "";
getstringPermutation(s, g, -1, 3);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Thread - Team and Player With Queue/src/Main.java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static Queue<Integer> q = new LinkedList<>();
public static void main(String[] args) throws InterruptedException {
Integer numberOfPlayers;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of Players");
numberOfPlayers = Integer.parseInt(sc.nextLine());
sc.close();
Main m = new Main();
TeamThread tt = new TeamThread(m, numberOfPlayers);
PlayerThread pt = new PlayerThread(m, numberOfPlayers);
tt.start();
pt.start();
tt.join();
pt.join();
}
}
<file_sep>/c_cpp/c/day 4/LinkedList.cpp
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
}*head=NULL;
void ins(int x)
{
node* ptr=new node();
ptr->data=x;
ptr->next=NULL;
if(head==NULL)
{
ptr->next=head;
head=ptr;
}
else{
ptr->next=head;
head=ptr;
}
}
}
int main()
{ stuct
ins(1);
ins(3);
ins(6);
print();
}
<file_sep>/c_cpp/c/maximumContigiousArray.c
#include<stdio.h>
int getMax(int x, int y)
{
return ( (x>=y)? x : y );
}
void maximumContigiousArray(int* A, int* DP)
{
int i = 0;
DP[0] = A[0];
for( i = 1; i<7; i++)
{
DP[i] = getMax( DP[i-1] + A[i], A[i]);
}
}
void show(int *A)
{
printf("\nElements:\t");
int i;
for(i = 0; i<7; i++)
{
printf("%d\t", A[i]);
}
}
int getMaxArray(int *A)
{
int i, temp, x;
for(i = 0; i<7; i++)
{
temp = getMax(A[i], A[i+1]);
if(temp >= x) x = temp;
}
return x;
}
int main()
{
int A[7] = {1, 7, 2, -2, -9, 4, 5};
int DP[7];
maximumContigiousArray(A,DP);
show(A);
show(DP);
printf("\nMaximum :\t%d\t", getMaxArray(DP));
}<file_sep>/c_cpp/beforeSummer/prep_class/Test/tree.c
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree * l;
struct tree * r;
};
struct tree * root;
struct tree * newNode(int data)
{
struct tree * ptr=(struct tree *)malloc(sizeof(struct tree));
ptr->data=data;
ptr->l=NULL;
ptr->r=NULL;
return ptr;
}
void insert( struct tree * head,int data)
{
if(root==NULL)
{
root=newNode(data);
return ;
}
if(head->data > data)
{
if(head->l==NULL)
{
head->l=newNode(data);
}
else
insert(head->l,data);
}
else
{
if(head->r==NULL)
{
head->r=newNode(data);
return;
}
else
insert(head->r,data);
}
}
void preorder(struct tree * head)
{
if(head!=NULL)
{
printf("%d\t",head->data);
preorder(head->l);
preorder(head->r);
}
else
{
return ;
}
}
struct tree * ptr;
void printTree(struct tree * head)
{
if(head==NULL)
{
return;
}
ptr=head;
int count=0;
while(ptr!=NULL)
{
printf("%d\t ",ptr->data);
ptr=ptr->l;
count++;
}
ptr=head;
while(count!=0)
{
ptr=ptr->r;
count--;
}
printTree(ptr);
}
void printTree2(struct tree * head)
{
if(head==NULL)
{
return;
}
ptr=head;
int count=0;
while(ptr!=NULL)
{
printf("%d\t ",ptr->data);
ptr=ptr->r;
count++;
}
ptr=head;
while(count!=0)
{
ptr=ptr->l;
count--;
}
printTree(ptr);
}
int main()
{
insert(root,12);
insert(root,5);
insert(root,13);
insert(root,25);
insert(root,40);
insert(root,45);
insert(root,49);
// insert(root,8);
preorder(root);
printf("\nLeft View\n");
printTree(root);
printf("\nright View\n");
// printTree2(root);
}
<file_sep>/c_cpp/afterSummer/Questions/Tree/printNodesAtKDistanceFromNode.cpp
#include <iostream>
#include <vector>
using namespace std;
typedef struct node
{
int info;
node *left;
node *right;
}tnode;
tnode *createNode(int info, tnode* left = NULL, tnode* right = NULL)
{
tnode* node = new tnode();
node -> info = info;
node -> left = NULL;
node -> right = NULL;
return node;
}
int KDown(tnode* root, int k)
{
if(!root)
return 0;
if(k == 0)
{
cout<<root -> info<<", ";
return 0;
}
k--;
KDown(root -> left, k);
KDown(root -> right, k);
return 0;
}
int printNodesAtKDistanceFromNode(tnode *root, int target, int k)
{
if(!root)
return -1;
if(root -> info == target)
{
KDown(root, k);
return 0;
}
int m = printNodesAtKDistanceFromNode(root -> left, target, k);
if(m > -1)
{
if(m+1 == k)
cout<<root -> info<<", ";
else
{
KDown(root -> right, k-m-1);
return m+1;
}
}
else
{
int n = printNodesAtKDistanceFromNode(root -> right, target, k);
if(n+1 == k)
cout<<root -> info<<", ";
else
KDown(root -> left, k-m-1);
return n+1;
}
}
int main(int argc, char const *argv[])
{
tnode *root;
root = createNode(20);
root -> left = createNode(8);
root -> right = createNode(22);
root -> left -> left = createNode(4);
root -> left -> right = createNode(12);
root -> left -> right -> left = createNode(10);
root -> left -> right -> right = createNode(14);
printNodesAtKDistanceFromNode(root,8,2);
return 0;
}
<file_sep>/c_cpp/afterSummer/Questions/t9PhoneWords.cpp
#include <iostream>
using namespace std;
string s[] = {" ", " ", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};
void t9PhoneWords(string str, int i, int n, string t)
{
if(i == n)
{
cout<<t<<endl;
return;
}
for(int j = 0; j < s[str[i] - '0'].length(); j++)
t9PhoneWords(str, i+1, n, t + s[str[i] - '0'][j]);
}
void printT9PhoneWords(string str)
{
t9PhoneWords(str, 0, str.length(), "");
}
int main(int argc, char const *argv[])
{
string str = "22";
printT9PhoneWords(str);
return 0;
}
<file_sep>/c_cpp/beforeSummer/prep_class/DP/0-1SnapsackProblemWIthoutDP.c
#include <stdio.h>
int c = 0, s = 0;
int max(int x, int y)
{
return (x > y) ? x : y;
}
int knapSack(int cap, int P[], int W[], int profit, int n)
{
c++;
if(n >= 0)
{
if(W[n] <= cap)
return max(knapSack(cap - W[n], P, W, profit + P[n], n - 1), knapSack(cap, P, W, profit, n - 1) );
else
return knapSack(cap, P, W, profit, n - 1);
}
else
return profit;
}
int main(int argc, char const *argv[])
{
int n = 5;
int capacity = 17;
int P[] = {10, 25, 4, 3, 2};
int W[] = {5, 1, 8, 7, 11};
printf("Maximum Profit:\t%d\n", knapSack(capacity, P, W, 0, n));
printf("Time Complexity:\t%d\n", c);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/World Cup Finals-Date/src/Main.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the date:");
try {
Date DOB = sdf.parse(sc.nextLine());
sc.close();
System.out.println("MS Dhoni brought World Cup glory back for India on " + String.valueOf(new SimpleDateFormat("MMMM dd,yyyy").format(DOB.getTime())));
} catch (Exception e) {
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/List Captain names/src/TeamBO.java
import java.sql.SQLException;
public class TeamBO {
public Team getTeamById(int id) throws ClassNotFoundException, SQLException {
return new TeamDAO().getTeamById(id);
}
public int updateCoachName(Integer id, String coach) throws ClassNotFoundException, SQLException {
return new TeamDAO().updateCoachName(id, coach);
}
}
<file_sep>/c_cpp/afterSummer/Questions/test.cpp
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
int a = stoi("23");
cout<<a;
return 0;
}<file_sep>/c_cpp/beforeSummer/Paper 1/q1.c
#include <stdio.h>
int c =0;
int getMin(int x, int y)
{
return (x < y) ? x : y;
}
void cutSticks(int n, int l[])
{
int i = 0, min = 9999, cnt = 0, flag = 0;
// get minimum
for(i = 0; i < n; i++)
{
min = getMin(l[i], min);
}
while(flag == 0)
{
flag = 1;
cnt = 0;
for(i = 0; i < n; i++)
{
c++;
if(l[i] > 0)
{
cnt++;
l[i] -= min;
if(l[i] > 0) flag = 0;
}
}
printf("%d\n", cnt);
}
}
int main(int argc, char const *argv[])
{
int l[] = {4, 5, 10, 8, 11};
int n = 5;
cutSticks(n, l);
printf("\n\nComplexity:\t%d\n", c);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/array/findsum.java
public class findsum{
public void findsumarray(int arr[],int k,int len)
{
sort(arr,len);
}
public void sort(int arr,int len)
{int i;
int j;
int temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
if(arr[i]>ar[j])
{
temp=arr[i];
a[i]=arr[j];
arr[j]=temp;
}
}
for(i=0;i<n;i++)
{
System.out.println(arr[i]+ " ");
}
}
public static void main(String args[])
{
int a[]={10,1,3,0,2,5};
int len=a.length;
System.out.println(len);
findsum f=new findsum();
f.findsumarray(a,10,len);
}
}
<file_sep>/c_cpp/beforeSummer/Paper 1/q3.c
#include <stdio.h>
#include <string.h>
char x[10][5] = {"", "", "ABC ", "DEF ", "GHI ", "JKL ", "MNO ", "PQRS", "TUV ", "WXYZ"};
int getInt(char c)
{
return ((int) c) - 48;
}
void func(char a[])
{
int l = strlen(a);
int i = 0, j = 0;;
int flag = 0;
for(j = 0; j < 4; j++)
{
for(j = 0; j < 4; j++)
{
i = 0;
while(i < l)
{
int v = getInt(a[i]);
if(v == 7 || v == 9)
{
if(j < 4) printf("%c", x[v][j]);
}
else
{
if(j < 3) printf("%c", x[v][j]);
}
i++;
}
printf("\n");
}
}
}
int main(int argc, char const *argv[])
{
char a[] = "893548";
func(a);
return 0;
}<file_sep>/c_cpp/c/mergeSort.c
//merge sort
#include<stdio.h>
int merge(int a[],int i,int m,int j)
{
int p,q,k,index;
int n1=m-i+1;
int n2=j-m;
int l[n1],r[n2];
for(k=0;k<n1;k++)
l[k]=a[k+i];
for(k=0;k<n2;k++)
r[k]=a[k+m+1];
p=0;q=0;index=i;
while(p<n1 && q<n2)
{
if(l[p]<r[q]){
a[index]=l[p];
p++;index++;
}
else
{
a[index]=r[q];
q++;
index++;
}
}
while(p<n1)
{
a[index]=l[p];
index++;
p++;
}
while(q<n2)
{
a[index]=r[q];
q++;
index++;
}
}
int mergesort(int a[],int i,int j)
{
if(i<j)
{
int m=(i+j)/2;
mergesort(a,i,m);
mergesort(a,m+1,j);
merge(a,i,m,j);
}
}
void printArray(int a[],int n)
{
int i=0;
printf("\nArray is : \n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
}
int main()
{
int a[]={6,5,4,3,2,1};
int n=sizeof(a)/sizeof(a[0]);
printArray(a,n);
mergesort(a,0,n-1);
printArray(a,n);
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/Thread – Match Outcome to Title Case/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
int i = 0, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of lines in the outcome");
n = Integer.parseInt(sc.nextLine());
TitleCaseThread[] tct = new TitleCaseThread[n];
Thread[] t = new Thread[n];
while(i < n) {
tct[i] = new TitleCaseThread(sc.nextLine());
t[i] = new Thread(tct[i]);
t[i].start();
i++;
}
sc.close();
try{
for(Thread th : t) {
th.join();
}
}catch(Exception e){
}
i = 0;
for(TitleCaseThread tc : tct) {
System.out.println("Sentence " + (++i) + " : " + tc.getModifiedSummary());
}
}
}
<file_sep>/Python/MyFirstPython.py
#print "hello world"
#l = int(raw_input("Enter a lower limit: "))
#u = int(raw_input("Enter a upper limit: "))
#a = int(raw_input("Enter a number: "))
# a = raw_input("Enter a number: ")
# a+=1
# print "You entered ", %a
# if a>10:
# print "%d is greater than 10" %a
# elif a == 10:
# print "%d equals 10" %a
# else:
# print "%d is less than 10" %a
# if a >= l and a <= u:
# print "valid"
# else:
# print "invalid"
# if a >= l & a <= u:
# print "valid"
# else:
# print "invalid"
# if a%5==0 or a%3==0:
# print "valid"
# else:
# print "invalid"
# if a%5 is 0 or a%3 is 0:
# print "valid"
# else:
# print "invalid"
# a = "hello ' "
# a = "hello"
# print "%r world!" %a
# print "%s world!" %a
# a = [1,2,3,4,5,6,7]
# print a[2]
# for x in range(1,5):
# print a[x],
# print("""Raz said, "I didn't know about triple quotes!" and laughed.
# ... Hello""")
# print "Hello\nWorld"
# print("Use backslash, so the single quote isn\'t noticed.")
# print("My name is \"Umang\"")
# print "Hello \\ World"
# print "Hello \a World"
# print "Hello \f World"
# print "Hello \t World"
# print "Hello \u0021 World"
# import math # Imports the math module
# everything = dir(math) # Sets everything to a list of things from math
# print everything
# from math import *
# print sqrt(9)
# from math import sqrt
# print sqrt(9)
# import math
# print math.sqrt(9)
# """
# def biggest_number(*args):
# print max(args)
# return max(args)
# def smallest_number(*args):
# print min(args)
# return min(args)
# def distance_from_zero(arg):
# print abs(arg)
# return abs(arg)
# biggest_number(-10, -5, 5, 10)
# smallest_number(-10, -5, 5, 10)
# distance_from_zero(-10)
# """
# print type(42)
# print type(4.2)
# print type('spam')
# a,b,c = [1, 2, 3]
# print a,b,c
# a = (1, 2)
# a = ['a', 'b']
# print a
# # swap using tuples
# a,b = [3, 4]
# a,b = b,a
# print a,b
# a = dict(name = "Umang")
# print a
# a = dict()
# a["name"]="Umang"
# print a
# a = dict(name = "Umang", age =21)
# print a
# a = dict(name = "Umang", age =21)
# # fetch all keys
# print a.keys()
# # fetch all items or values
# print a.items()
# # get length
# print len(a)
# for x in a:
# print "Name : %s" %a[x]
# print "Age : %s" %a[x]
# for x,y in a.items():
# print x, y
# a = int(raw_input("Enter a number"))
# b = int(raw_input("Enter a number"))
# a = 5
# b = 10
# if a > b:
# print "%d is greater" %a
# else:
# print "%d is greater" %b
# def getMax(a , b):
# if a > b:
# print "%d is greater" %a
# else:
# print "%d is greater" %b
# a = 5
# b = 10
# getMax(a,b)
# def getMax(a , b):
# if a > b:
# return a
# else:
# return b
# a = 5
# b = 10
# print "%d is greater" %getMax(a,b)
# # classes
# class User:
# name = ''
# age = 0
# g = ''
# def __init__(self, name = '', age = 0, g = ''):
# self.name = name
# self.age = age
# self.g = g
# def Display(self):
# print 'Name : %s' %self.name
# print 'Age : %s' %self.age
# print 'g : %s' %self.g
# def to_dict(self):
# return dict(name = self.name, age = self.age, g = self.g)
# def __repr__(self):
# return 'Name : %s\nAge : %s\ng : %s' %(self.name, self.age, self.g)
# # sampleUser = User('Umang', 21)
# sampleUser = User(name = 'Umang', age = 21, g = 'abc')
# # sampleUser.Display()
# print sampleUser
# print sampleUser.to_dict()
# from sys import argv
# arg1, arg2, arg3 = argv
# print arg1, arg2, arg3
# print argv
# n = [1, 3, 5]
# n.pop(1)
# # Returns 3 (the item at index 1)
# print n
# # prints [1, 5]
# n.remove(1)
# # Removes 1 from the list,
# # NOT the item at index 1
# print n
# # prints [3, 5]
# del(n[0])
# # Doesn't return anything
# print n
# # prints [1, 5]
# ################# --Start-- BattleShip Game ######################
# from random import randint
# board = []
# for x in range(5):
# board.append(["O"] * 5)
# def print_board(board):
# for row in board:
# print " ".join(row)
# print "Let's play Battleship!"
# print_board(board)
# def random_row(board):
# return randint(0, len(board) - 1)
# def random_col(board):
# return randint(0, len(board[0]) - 1)
# for turn in range(4):
# print "Turn", turn + 1
# ship_row = random_row(board)
# ship_col = random_col(board)
# print ship_row
# print ship_col
# # Everything from here on should go in your for loop!
# # Be sure to indent four spaces!
# guess_row = int(raw_input("Guess Row:"))
# guess_col = int(raw_input("Guess Col:"))
# if guess_row == ship_row and guess_col == ship_col:
# print "Congratulations! You sunk my battleship!"
# break
# else:
# if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
# print "Oops, that's not even in the ocean."
# elif(board[guess_row][guess_col] == "X"):
# print "You guessed that one already."
# else:
# print "You missed my battleship!"
# board[guess_row][guess_col] = "X"
# # Print (turn + 1) here!
# print_board(board)
# if turn ==3:
# print "Game Over"
# ################# --End -- BattleShip Game ######################
# list = ["a", "b", "c", "d"]
# for i,j in enumerate(list):
# print i+1,j
# list_a = [3, 9, 17, 15, 19]
# list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
# list_c = [1,2,50,4,5,6,]
# def getMax(x,y,z):
# if x>=y and x>=z:
# return x
# elif y>=x and y>=z:
# return y
# else:
# return z
# for a, b, c in zip(list_a, list_b, list_c):
# # Add your code here!
# print getMax(a,b,c)
# fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
# print 'You have...'
# for f in fruits:
# if f == 'tomato':
# print 'A tomato is not a fruit!' # (It actually is.)
# break
# print 'A', f
# else: #else will be hitted
# print 'A fine selection of fruits!'
# def median(numbers):
# for i in range(len(numbers)):
# j = i + 1
# while j < len(numbers):
# if numbers[i] > numbers[j]:
# x = numbers[i]
# numbers[i] = numbers[j]
# numbers[j] = x
# j += 1
# print numbers
# med = 0
# if len(numbers)%2 is 1:
# return numbers[(len(numbers)/2) ]
# else:
# print numbers[len(numbers)/2]
# med = ( float(numbers[len(numbers)/2 - 1]) + \
# (numbers[(len(numbers)/2)]) ) / 2
# return med
# # print median([4,5,5,4])
# print median([1, 34, 1, 6, 8, 0])
# # grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
# grades = [7,8]
# def grades_sum(scores):
# total = 0
# for i in scores:
# total += i
# return total
# def grades_average(grades):
# return float(grades_sum(grades)) / len(grades)
# print grades_sum(grades)
# print grades_average(grades)
# grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
# def print_grades(grades):
# for grade in grades:
# print grade
# def grades_sum(grades):
# total = 0
# for grade in grades:
# total += grade
# return total
# def grades_average(grades):
# sum_of_grades = grades_sum(grades)
# average = sum_of_grades / float(len(grades))
# return average
# def grades_variance(scores):
# average = grades_average(scores)
# variance = 0
# for score in scores:
# variance += (average - score) ** 2
# return variance / len(scores)
# def grades_std_deviation(variance):
# return variance ** 0.5
# print_grades(grades)
# print grades_sum(grades)
# print grades_average(grades)
# print grades_variance(grades)
# variance = grades_variance(grades)
# print grades_std_deviation(variance)
# my_dict = {
# "name" : "Umang",
# "age" : 20
# }
# print my_dict.keys()
# print my_dict.values()
# for item in my_dict:
# print item, my_dict[item]<file_sep>/Java/CTS_SFDC/workspace/Player Details/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
String name, country, skill;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the player name");
name = sc.nextLine();
System.out.println("Enter the country name");
country = sc.nextLine();
System.out.println("Enter the skill");
skill = sc.nextLine();
sc.close();
Player p = new Player(name, country, skill);
PlayerBO pb = new PlayerBO();
pb.displayPlayerDetails(p);
}
}
<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/subsetSumProblem.cpp
#include <iostream>
using namespace std;
int subsetSum(int a[], int s, int n)
{
int maxWays = 0;
int dp[s+1][n] = {0};
for (int i = 0; i <= s; i++)
{
cout<<i<<"->\t";
for (int j = 0; j < n; j++)
{
if(i == 0)
dp[i][j] = 1;
else if(j == 0)
dp[i][j] = 0;
else if(i >= a[j])
dp[i][j] = dp[i - a[j]][j-1] + dp[i][j-1];
else
dp[i][j] = dp[i][j-1];
cout<<dp[i][j]<<"\t";
}
maxWays = max(maxWays, dp[s][n-1]);
cout<<endl;
}
return maxWays;
}
int main(int argc, char const *argv[])
{
int a[] = {0,3,34,4,12,5,2};
int s = 9 ;
cout<<"No. of ways:\t"<<subsetSum(a, s, sizeof(a)/sizeof(a[0]))<<endl;
return 0;
}<file_sep>/c_cpp/c/day 3/no of occuren(recursion).cpp
#include<iostream>
using namespace std;
int count=0;
int flag=0;
int binSearch(int arr[],int key,int low,int high)
{
int mid;
if(low>high)
return 0;
mid=(low+high)/2;
if(arr[mid]==key)
{
flag=1;
count++;
binSearch(arr,key,low,mid-1);
binSearch(arr,key,mid+1,high);
}
else if(arr[mid]>key)
binSearch(arr,key,low,mid-1);
else binSearch(arr,key,mid+1,high);
}
int main()
{
int ar[100],key,len,index;
cout<<"Enter array length = ";
cin>>len;
cout<<" Enter Array \n";
for(int i=0;i<len;i++)
{
cin>>ar[i];
}
cout<<"\nEnter the key to find";
cin>>key;
binSearch(ar,key,0,len-1);
if(flag==0)
cout<<"Not found key, ";
else cout<<" Count = "<<count;
}
<file_sep>/c_cpp/c/day 4/petrol pump problem.cpp
#include<iostream>
using namespace std;
int main(){
int arr1[]={4,5,7,5};
int arr2[]={6,4,3,6};
int N=4;
int arr3[N];
for(int i=0;i<N;i++){
arr3[i]=arr1[i]-arr2[i];
}
int x=0;
int y=0;
int sum=0;
int count=0;
while(count<=N)
{
sum=sum+arr3[y];
y=(y+1)%N;
count++;
if(sum<0)
{
sum=sum-arr3[x];
x=(x+1)%N;
count--;
}
}
cout<<x;
}
<file_sep>/Python/a.py
import requests
from bs4 import BeautifulSoup
def stop():
exit(0)
def print_head(header):
print('\n________________________________\n--------------------------------\n' + header + '\n--------------------------------')
def get_session_id(session, url):
try:
response = session.get(url)
return (response.headers.get('Set-Cookie')[18:])[:-18]
except:
print('ERROR- get_session_id()')
stop()
def load_time_table_page(session, _session_id, url):
try:
response = session.get(url, cookies={'ASP.NET_SessionId': _session_id})
return response
except:
print('ERROR- load_get_time_table_page()')
stop()
def _find_session_alive_url(page_html):
a = 0
b = 0
for i in range(len(page_html)):
if page_html[i:i+15] == 'KeepAliveUrl":"':
a = i+15
elif page_html[i:i+57] == '","id":"ReportViewerabcd_SessionKeepAlive"}, null, null);':
b = i
break
if a==0:
print('ERROR- _find_session_alive_url() - getting a')
stop()
if b==0:
print('ERROR- _find_session_alive_url() - getting b"')
stop()
_ctrl_id = str(page_html[a+83:b-15])
return ('https://ums.lpu.in' + str(page_html[a:a+67]) + '&' + str(page_html[a+73:b-15]) + '&' + str(page_html[b-9:b]) , _ctrl_id)
def make_session_alive(session, _session_id, page_html):
try:
_session_alive_url, _ctrl_id = _find_session_alive_url(page_html)
response = session.get(_session_alive_url, cookies={'ASP.NET_SessionId': _session_id})
if(response.status_code == 200):
return (_ctrl_id, True)
else:
print('ERROR- SESSION_ALIVE- False')
stop()
except:
print('ERROR- make_session_alive()')
stop()
def load_time_table(session, _session_id, url, registration_number):
try:
soup1 = BeautifulSoup((session.get(url)).text, "lxml")
__VSTATE = soup1.select('input[name=__VSTATE]')[0]['value']
print(__VSTATE)
request_body1 = {
"ReportViewerabcd$ctl09$VisibilityState$ctl00": "None",
"__VIEWSTATE": "",
"__VSTATE": __VSTATE,
"btnGetTimeTable": "View Time Table",
"txtRegistrationNumber": registration_number
}
headers1 = {
'content-type': "application/x-www-form-urlencoded",
'cookie': "ASP.NET_SessionId=" + _session_id,
'cache-control': "no-cache"
}
response1 = session.request("POST", url, headers=headers1, data=request_body1, cookies={'ASP.NET_SessionId': _session_id})
# print response1.text
_ctrl_id, SESSION_ALIVE= make_session_alive(session, _session_id, response1.text)
print('CONTROL ID-\t' + _ctrl_id)
print('SESSION_ALIVE-\t' + str(SESSION_ALIVE))
soup2 = BeautifulSoup(response1.text, "lxml")
__VSTATE = soup2.select('input[name=__VSTATE]')[0]['value']
print(__VSTATE)
request_body2 = {
"ReportViewerabcd$ctl09$VisibilityState$ctl00": "None",
"__EVENTARGUMENT": "",
"__EVENTTARGET": "ReportViewerabcd$ctl09$Reserved_AsyncLoadTarget",
"__VIEWSTATE": "",
"__VSTATE": __VSTATE,
"btnGetTimeTable": "View Time Table",
"txtRegistrationNumber": registration_number
}
headers2 = {
'origin': "https://ums.lpu.in",
'x-requested-with': "XMLHttpRequest",
'x-microsoftajax': "Delta=true",
'content-type': "application/x-www-form-urlencoded",
'accept': "*/*",
'referer': "https://ums.lpu.in/Lpuums/Reports/frmStudentTimeTable.aspx",
'cache-control': "no-cache"
}
response2 = session.request("POST", url, headers=headers2, data=request_body2, cookies={'ASP.NET_SessionId': _session_id})
print response2.text
# soup = BeautifulSoup(response.text, "html.parser")
# print(soup.prettify())
return response1
except:
print('ERROR- load_time_table()')
stop()
def get_time_table(session, _session_id, _ctrl_id):
try:
url = 'https://ums.lpu.in/LpuUms/Reserved.ReportViewerWebControl.axd?Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=' + _ctrl_id + '&OpType=Export&FileName=rptTimeTableStudent&ContentDisposition=OnlyHtmlInline&Format=CSV'
response = session.request("GET", url, cookies={'ASP.NET_SessionId': _session_id})
return response
except Exception as e:
raise e
def main():
url_time_table_page = 'https://ums.lpu.in/Lpuums/Reports/frmStudentTimeTable.aspx'
# INITIALIZE SESSION
session = requests.Session()
# GET CURRENT SESSION ID
print_head('get_session_id()')
SESSION_ID = get_session_id(session, 'https://ums.lpu.in/lpuums/')
print 'SESSION_ID-\t' + str(SESSION_ID)
# LOAD GET TIME TABLE PAGE
print_head('load_time_table_page()')
load_time_table_response = load_time_table_page(session, SESSION_ID, url_time_table_page)
print 'load_time_table_response-\t' + str(load_time_table_response)
# GET MAKE SESSION ALIVE
print_head('make_session_alive()')
CONTROL_ID, SESSION_ALIVE = make_session_alive(session, SESSION_ID, load_time_table_response.text)
print 'CONTROL_ID-\t' + str(CONTROL_ID)
print 'SESSION_ALIVE-\t' + str(SESSION_ALIVE)
#LOAD_TIME_TABLE
print_head('load_time_table()')
registration_number = '11304295'
load_time_table(session, SESSION_ID, url_time_table_page, registration_number)
# GET TIME TABLE
# print_head('get_time_table()')
# print(str(get_time_table(session, SESSION_ID, CONTROL_ID)))
if __name__ == "__main__": main()
<file_sep>/Java/CTS_SFDC/workspace/Set - Player List Index Builder/src/IndexBuilder.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
public class IndexBuilder {
public TreeSet<Index> buildIndex(HashSet<Player> players) {
TreeSet<Index> indexes = new TreeSet<>();
Iterator<Player> iterator = players.iterator();
while(iterator.hasNext()) {
Player p = iterator.next();
Index i = findIndex(indexes, p.getName().charAt(0));
if(i == null) {
indexes.add(new Index(p.getName().charAt(0), 1));
} else {
indexes.remove(i);
indexes.add(new Index(p.getName().charAt(0), i.getCount() + 1));
}
}
return indexes;
}
private Index findIndex(TreeSet<Index> indexes,char ch) {
Iterator<Index> iterator = indexes.iterator();
while(iterator.hasNext()) {
Index i = iterator.next();
if(i.getCh() == ch)
return i;
}
return null;
}
public void displayIndex(TreeSet<Index> indexes) {
System.out.print(String.format("%-14s%-15s","Player", "Index"));
Iterator<Index> iterator = indexes.iterator();
while(iterator.hasNext()) {
Index i = iterator.next();
System.out.print(String.format("\n%-15s%-15d",i.getCh(), i.getCount()));
}
}
}
<file_sep>/c_cpp/afterSummer/Questions/getMaxJ-I.cpp
#include <iostream>
using namespace std;
int maxDiff(int arr[], int n)
int getMax(int a[], int n)
{
int i=0, j=n-1;
while(i<j)
{
if(a[i]<a[j])
return j-i;
if(a[i]>a[j] && a[i]>a[j-1])
i++;
else
j--;
}
return -1;
}
int main(int argc, char const *argv[])
{
int a[] = {34,8,10,3,2,80,30,35,1};
int b[] = {9,2,3,4,5,6,7,8,18,0};
int c[] = {1,2,3,4,5,6};
// int d[] = {6,5,4,3,2,1};
int d[] = {7,6,100,4,3,2,1};
cout<<getMax(a, 9)<<endl<<getMax(b,10)<<endl<<getMax(c,6)<<endl<<getMax(d,7)<<endl;
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/PlayerStatistics 1/src/IKabbadiPlayerStatistics.java
public interface IKabbadiPlayerStatistics {
void displayKabbadiPlayerDetails();
}
<file_sep>/Python/pythonWorkshop/project/app/schema.py
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
item = db.Column(db.String(120), nullable=False)
isComplete = db.Column(db.Boolean, default=False)
def __init__(self, item, user_id):
self.item = item
self.user_id = user_id
def to_dict(self):
return dict(id=self.id,item=self.item)
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(120), nullable = False)
def __init__(self, name):
self.name = name
<file_sep>/Java/CTS_SFDC/workspace/Game Details By Venue/src/gameDetail/TeamBO.java
package gameDetail;
public class TeamBO {
public Team getTeamById(int id) throws ClassNotFoundException {
return new Team();
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/q3.c
#include <stdio.h>
int sumArray(int a[], int x, int y)
{
// if( (y - x) == 1) return a[x] + a[y];
// if( (y - x) == 0) return a[x];
// if( ( (y - x) % 2) == 0) return sumArray(a, x, (y/2) ) + sumArray(a, (y/2) + 1, y);
// if( ( (y - x) % 2) == 1) return sumArray(a, x, (y/2) - 1 ) + sumArray(a, (y/2) , y);
if( (y - x) == 0) return a[x];
else
{
int m = (x + y) / 2;
return sumArray(a, x, m) + sumArray(a, m + 1, y);
}
}
int main(int argc, char const *argv[])
{
int a[] = {3, 1, 2, 5, 4, 5, 4, 9};
printf("Sum:\t%d\n", sumArray(a, 0, 7));
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/Thread - Mark Mean, Min and Max Scores/src/CalculateScores.java
public class CalculateScores implements Runnable {
String matchType;
String scoreString;
Integer[] scores;
Double meanScore;
Integer minScore;
Integer maxScore;
public CalculateScores(String matchType, String scoreString) {
super();
this.matchType = matchType;
this.scoreString = scoreString;
}
public String getMatchType() {
return matchType;
}
public void setMatchType(String matchType) {
this.matchType = matchType;
}
public String getScoreString() {
return scoreString;
}
public void setScoreString(String scoreString) {
this.scoreString = scoreString;
}
public Integer[] getScores() {
return scores;
}
public void setScores(Integer[] scores) {
this.scores = scores;
}
public Double getMeanScore() {
return meanScore;
}
public void setMeanScore(Double meanScore) {
this.meanScore = meanScore;
}
public Integer getMinScore() {
return minScore;
}
public void setMinScore(Integer minScore) {
this.minScore = minScore;
}
public Integer getMaxScore() {
return maxScore;
}
public void setMaxScore(Integer maxScore) {
this.maxScore = maxScore;
}
@Override
public void run() {
String[] parts = scoreString.split(",");
int i = 0, total = 0;
maxScore = 0;
minScore = 1000;
scores = new Integer[parts.length];
while(i < parts.length) {
scores[i] = Integer.parseInt(parts[i]);
total += scores[i];
if(scores[i] > maxScore) {
maxScore = scores[i];
}
if(scores[i] < minScore) {
minScore = scores[i];
}
meanScore = ((double) total) / parts.length;
i++;
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Thread - Mark Mean, Min and Max Scores/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
int i = 0, n = 3;
String matchType;
String scoreString;
Scanner sc = new Scanner(System.in);
CalculateScores[] csList = new CalculateScores[3];
Thread[] t = new Thread[3];
while(i < n) {
System.out.println("Enter the match :");
matchType = sc.nextLine();
System.out.println("Enter the scores :");
scoreString = sc.nextLine();
csList[i] = new CalculateScores(matchType, scoreString);
t[i] = new Thread(csList[i]);
t[i].start();
i++;
}
sc.close();
try{
for(Thread th : t) {
th.join();
}
}catch(Exception e){
}
System.out.println("Score Summary");
for(CalculateScores ss : csList) {
System.out.println("Match : " + ss.getMatchType());
System.out.println( String.format("Mean : %.2f", ss.getMeanScore().floatValue()));
System.out.println("Min Score : " + ss.getMinScore());
System.out.println("Max Score : " + ss.getMaxScore());
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/JDBC – Search Team/src/TeamDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class TeamDAO {
public Team getTeamByID(Long id) throws ClassNotFoundException, SQLException {
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String user=rb.getString("db.username");
String pass=rb.getString("db.password");
Connection con = DriverManager.getConnection(url,user,pass);
Statement statement = con.createStatement();
String sql = "select id,name from team where id=" + id;
ResultSet result = statement.executeQuery(sql);
result.next();
return new Team(result.getLong("id"), result.getString("name"));
}
}
<file_sep>/Web/Static - HTML,CSS,JS/Match Details/index.html
<!DOCTYPE html>
<html>
<head>
<title>Indian Premier League</title>
<style type="text/css">
body {
background-color: #FF6AB4;
color: white;
}
main {
background-color: white;
padding: 10px;
color: black;
}
hr {
color: #FFFF00;
}
.heading {
color:#C71585;
font-style: italic;
}
</style>
</head>
<body>
<header>
<center>
<h1>Indian Premier League</h1>
</center>
</header>
<main>
<center>
<h4 class="heading">Team Details</h4>
<h4 class="heading">Mumbai Indians vs Rising Pune Supergiants</h4>
</center>
<div id="team">
<div style="float:left; ">
<h4 class="heading">Team 1 : Mumbai Indians</h4>
<ul>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li>Shreyas Gopal</li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li>Bumrah</li>
</ul>
</div>
<div style="display: inline-block; margin-left: 300px;">
<h4 class="heading">Team 2 : Rising Pune Supergiants</h4>
<ul>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li><NAME></li>
<li>Dhoni</li>
<li><NAME></li>
<li>Ashwin</li>
<li><NAME></li>
<li>Ishant</li>
<li>RP Singh</li>
</ul>
</div>
</div>
<hr>
<div>
<center>
<h4 class="heading">Winning Details</h4>
</center>
</div>
<div id="win">
<b>Rising Pune Supergiants</b> won the match by <b>7 wickets</b>
</div>
<hr>
<div>
<center>
<h4 class="heading">Score Details</h4>
</center>
</div>
<div id="score">
<div style="float:left; ">
<h4 class="heading">Mumbai Indians</h4>
<p><b>Runs</b> - 121</p>
<p><b>Overs</b> - 20</p>
<p><b>Wickets</b> - 8</p>
</div>
<div style="display: inline-block; margin-left: 300px;">
<h4 class="heading">Rising Pune Supergiants</h4>
<p><b>Runs</b> - 126</p>
<p><b>Overs</b> - 14.4</p>
<p><b>Wickets</b> - 1</p>
</div>
</div>
</main>
</body>
</html><file_sep>/Java/CTS_SFDC/workspace/Venue/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String name, city;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the venue name");
name = sc.nextLine();
System.out.println("Enter the city name");
city = sc.nextLine();
sc.close();
Venue v = new Venue();
v.name = name;
v.city = city;
System.out.print("Venue Details :"
+ "\nVenue Name : " + v.name
+ "\nCity Name : " + v.city
);
}
}
<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/0_1_KnapSack.cpp
#include <iostream>
using namespace std;
string knapsack(int val[], int wt[], int W, int n)
{
int dp[W+1][n+1] = {0};
for (int i = 0; i <= W; i++)
{
// cout<<i<<"\t";
for (int j = 0; j <= n; j++)
{
if(i==0 || j==0)
dp[i][j] = 0;
else if(i >= wt[j])
dp[i][j] = max(dp[i - wt[j]][j-1] + val[j], dp[i][j-1]);
else
dp[i][j] = dp[i][j-1];
// cout<<dp[i][j]<<"\t";
}
// cout<<endl;
}
int i = W;
int j = n;
string s = "";
while(i!=0)
{
if(dp[i][j] == dp[i][j-1])
j--;
else
{
cout<<j<<"\t";
i = i-wt[j];
}
}
return s;
}
int main(int argc, char const *argv[])
{
int val[] = {0,80,100,120,130};
int wt[] = {0,10,20,30,50};
int W = 60;
cout<<knapsack(val,wt,W, sizeof(wt)/sizeof(wt[0]))<<endl;
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/Linked List/constructMaxSumPathList.cpp
#include <iostream>
using namespace std;
typedef struct node{
int data;
node* next;
}lNode;
lNode* createNode(int data){
lNode* n = new lNode();
n -> data = data;
n -> next = NULL;
return n;
}
lNode* getMaxSumPathList(lNode* head1, lNode* head2)
{
lNode *head, *tHead1=head1, *tHead2=head2, *trav1=head1, *trav2=head2, *tempHead;
int sum1 = 0, sum2 = 0;
bool flagSetted = false;
while(trav1 != NULL || trav2 != NULL)
{
// if(trav1 -> data == trav2 -> data)
// {
// if(sum1 > sum2)
// {
// tempHead -> next = tHead1 -> next;
// tempHead = tHead1 = trav1;
// }
// else
// {
// tempHead -> next = tHead2 -> next;
// tempHead = tHead2 = trav2;
// }
// trav1 = trav1 -> next;
// trav2 = trav2 -> next;
// sum1 = trav1 -> data;
// sum2 = trav2 -> data;
// if(flagSetted == false)
// {
// head = tempHead;
// flagSetted = true;
// }
// }
// else
// {
// if(sum1 > sum2)
// {
// trav2 = trav2 -> next;
// sum2 += trav2 -> data;
// }
// else
// {
// trav1 = trav1 -> next;
// sum1 += trav1 -> data;
// }
// }
}
return head;
}
int main(int argc, char const *argv[]) {
lNode *head1 = createNode(1);
head1->next = createNode(3);
head1->next->next = createNode(30);
head1->next->next->next = createNode(90);
head1->next->next->next->next = createNode(120);
head1->next->next->next->next->next = createNode(240);
head1->next->next->next->next->next->next = createNode(511);
lNode *head2 = createNode(0);
head2->next = createNode(3);
head2->next->next = createNode(12);
head2->next->next->next = createNode(32);
head2->next->next->next->next = createNode(90);
head2->next->next->next->next->next = createNode(125);
head2->next->next->next->next->next->next = createNode(240);
head2->next->next->next->next->next->next->next = createNode(249);
lNode *head = getMaxSumPathList(head1, head2);
//print list
while(head != NULL)
{
cout << head -> data << " -> ";
head = head -> next;
}
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/Venue (Split)/src/Venue.java
public class Venue {
String name, city;
}
<file_sep>/c_cpp/c/day 5/maxsum.cpp
#include<iostream>
using namespace std;
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
main()
{
int a[]={ 10,15,2,25};
int include=a[0];
int temp;
int d;
int exclude=0;
for(int i=1;i<4;i++)
{
temp=exclude;
exclude=max(include,exclude);
include=temp+a[i];
}
d=max(include,exclude);
cout<<d;
}
<file_sep>/Java/CTS_SFDC/workspace/Outcome Details/src/Outcome.java
class Outcome {
private
String status ;
String winnerTeam ;
String playerOfMatch ;
String date;
Outcome(){}
Outcome(String date,String status,String winnerTeam,String playerOfMatch)
{
this.date=date;
this.status=status;
this.winnerTeam=winnerTeam;
this.playerOfMatch=playerOfMatch;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getWinnerTeam() {
return winnerTeam;
}
public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}
public String getPlayerOfMatch() {
return playerOfMatch;
}
public void setPlayerOfMatch(String playerOfMatch) {
this.playerOfMatch = playerOfMatch;
}
void setDate(String date)
{
this.date=date;
}
String getDate()
{
return date;
}
public String toString()
{
return String.format("%-20s %-20s %-20s %s",status,winnerTeam,playerOfMatch,date);
}
}
<file_sep>/Java/CSE406/Stream API/Reduction Operations/TestReductionOps.java
import java.util.*;
import java.util.stream.*;
class Employee{
int id, pay, score;
public Employee(int id, int pay, int score){
this.id = id;
this.pay = pay;
this.score = score;
}
public int getId(){
return this.id;
}
public int getPay(){
return this.pay;
}
public int getScore(){
return this.score;
}
}
class TestReductionOps{
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, 10000, 7));
employees.add(new Employee(2, 15000, 4));
employees.add(new Employee(3, 12000, 5));
employees.add(new Employee(4, 26000, 9));
employees.add(new Employee(5, 20000, 8));
ArrayList<Integer> pays = new ArrayList<>();
pays.add(20000);
pays.add(35000);
pays.add(40000);
pays.add(10000);
pays.add(18000);
System.out.println("Count: " + employees.stream().count());
Optional<Integer> averagePay = pays.stream().reduce( (a,b) -> (Integer)(a+b)/2);
if(averagePay.isPresent())
System.out.println("Average Pay: " + averagePay.get());
// Optional<Integer> minScore = scores.stream().min(Integer::compare);
// if(minScore.isPresent())
// System.out.println("min Score: " + minScore.get());
// List<Employee> scores = employees.stream().filter(n -> n.getScore()).collect(Collectors.toList());
// Optional<Integer> maxScore = scores.stream().max(Integer::compare);
// if(maxScore.isPresent())
// System.out.println("max Score: " + maxScore.get());
}
}
<file_sep>/c_cpp/c/palindromeString.c
#include<stdio.h>
#include<string.h>
char temp;
void reverse(int x, int y, char z[])
{
if(y>x)
{
temp = z[x];
z[x] = z[y];
z[y] = temp;
reverse(x+1,y-1,z);
}
}
int main()
{
char a[] = "aba";
char t[strlen(a)];
strcpy(t,a);
reverse(0, strlen(a)-1, a);
printf("%s\n", a);
if(t == a)
{
printf("String is Palindrome.\n");
}
else
{
printf("String is NOT Palindrome.\n");
}
}<file_sep>/c_cpp/c/bubble.c
#include<stdio.h>
#include<time.h>
int i = 0, j = 0, k = 0, swap=0, x = 0, temp = 0;
clock_t begin, end;
double time_spent;
int bubble_sort(int a[], int n)
{
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i; j++)
{
if(a[j] > a[j+1])
{
swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for(k = 0; k < 8; k++)
{
printf("%d\t", a[k]);
}
printf("\n");
}
x++;
}
}
}
int selection_sort(int a[], int n)
{
for(i = 0; i < n; i++)
{
temp = i;
for(j = i; j < n; j++)
{
if(a[temp] > a[j])
{
temp = j;
}
x++;
}
if(a[i] > a[temp])
{
swap = a[i];
a[i] = a[temp];
a[temp] = swap;
for(k = 0; k < 8; k++)
{
printf("%d\t", a[k]);
}
printf("\n");
}
}
}
int main(int argc, char const *argv[]) {
begin = clock();
int a[] = {13, 1, 8, 2, 5, 4, 12, 11};
// int a[] = {1, 1, 1, 1, 1, 1, 1, 1};
// bubble_sort(a, 8);
selection_sort(a, 8);
// for(i = 0; i < 8; i++)
// {
// printf("%d\t", a[i]);
// }
end = clock();
time_spent = (double) (end - begin);
printf("\nComplexity:\t%d\nExecution Time:\t%f\n", x, time_spent );
return 0;
}
<file_sep>/c_cpp/c/minOfTree.c
#include<stdio.h>
#include<stdlib.h>
struct treeNode
{
int d;
struct treeNode* l;
struct treeNode* r;
};
struct treeNode* root;
struct treeNode* newNode(int data)
{
struct treeNode *newN = (struct treeNode*) malloc(sizeof(struct treeNode));
newN -> d = data;
newN -> l = NULL;
newN -> r = NULL;
return newN;
}
void preTrav(struct treeNode* root)
{
if(root != NULL)
{
printf("%d\t", root -> d);
preTrav(root -> l);
preTrav(root -> r);
}
}
void postTrav(struct treeNode* root)
{
if(root != NULL)
{
postTrav(root -> l);
postTrav(root -> r);
printf("%d\t", root -> d);
}
}
void inTrav(struct treeNode* root)
{
if(root != NULL)
{
inTrav(root -> l);
printf("%d\t", root -> d);
inTrav(root -> r);
}
}
struct treeNode* insertNode(struct treeNode* root, int data)
{
if(root == NULL)
{
root = newNode(data);
}
else
{
if(root -> l == NULL)
{
root -> l = insertNode(root -> l, data);
}
else
{
root -> r = insertNode(root -> r, data);
}
}
return root;
}
int min = 100;
void getMin(struct treeNode* root)
{
if(root != NULL)
{
if(root -> d < min)
{
min = root -> d;
}
getMin(root -> l);
getMin(root -> r);
}
}
int main()
{
root = NULL;
root = newNode(1);
root -> l = newNode(2);
root -> r = newNode(3);
root -> l -> l = newNode(4);
root -> l -> r = newNode(5);
root -> r -> r = newNode(6);
printf("\nPre-Order Trversal:\t");
preTrav(root);
printf("\nPost-Order Trversal:\t");
postTrav(root);
printf("\nIn-Order Trversal:\t");
inTrav(root);
getMin(root);
printf("\nMINIMUM value in Tree:\t%d\n", min);
}<file_sep>/Java/CTS_SFDC/workspace/PlayerStatistics 1/src/Player.java
public class Player implements IKabbadiPlayerStatistics {
private
String name;
String teamName;
Integer noOfMatches;
Long totalRaidPoints;
Long totalDefencePoints;
public Player(String name, String teamName, Integer noOfMatches, Long totalRaidPoints, Long totalDefencePoints) {
super();
this.name = name;
this.teamName = teamName;
this.noOfMatches = noOfMatches;
this.totalRaidPoints = totalRaidPoints;
this.totalDefencePoints = totalDefencePoints;
}
public void displayKabbadiPlayerDetails() {
System.out.printf("Player name : %s\nTeam name : %s\nNo of matches : %d\nTotal raid points: %d\nTotal defence points: %d\n",
name, teamName, noOfMatches, totalRaidPoints, totalDefencePoints);
}
}
<file_sep>/Java/CTS_SFDC/workspace/JDBC - Display Team and City/src/Main.java
import java.util.List;
public class Main {
public static void main(String ags[])throws Exception{
System.out.println("List of all team and their city");
System.out.println(String.format("%-15s%-30s%-30s%-15s","Id", "Name", "Coach","CityName"));
List<Team> teamList = null;
TeamDAO teamIns = new TeamDAO();
teamList = teamIns.getAllTeams();
for(Team t : teamList) {
System.out.println(String.format("%-15d%-30s%-30s%-15s",t.getTeamId(), t.getName(), t.getCoach(), t.getCity().getCityName()));
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Match Details/src/Match.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Match {
void displayMatchDetails(Date matchDate) {
System.out.printf("Match Date : %s", String.valueOf(new SimpleDateFormat("MM-dd-yyyy").format(matchDate)));
}
void displayMatchDetails(String venue) {
String[] parts = venue.split(",");
System.out.printf("Match Venue :\nStadium : %s\nCity : %s", parts[0], parts[1]);
}
void displayMatchDetails(String winnerTeam,long runs) {
System.out.printf("Match Outcome :\n%s won by %d runs", winnerTeam, runs);
}
}
<file_sep>/Java/CTS_SFDC/workspace/JDBC - Insert new Team/src/TeamDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class TeamDAO {
public void createTeam(Team team) throws ClassNotFoundException, SQLException {
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String username=rb.getString("db.username");
String pass=rb.getString("db.password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,username,pass);
Statement statement = con.createStatement();
String sql = "select id from team order by id desc";
ResultSet result = statement.executeQuery(sql);
result.next();
long id = result.getLong("id");
result.close();
sql = "insert into team(id,name,coach,home_city_id) values("
+ (++id) + ",'" + team.getName() + "','" + team.getCoach() + "'," + team.getCity().getCityId() + ")";
statement.executeUpdate(sql);
System.out.println("Team has been created");
}
public List<Team> getAllTeams() throws ClassNotFoundException, SQLException{
List<Team> teams = new ArrayList<>();
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String user=rb.getString("db.username");
String pass=<PASSWORD>("<PASSWORD>");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,pass);
Statement statement = con.createStatement();
String sql = "select * from team order by name";
ResultSet result = statement.executeQuery(sql);
CityDAO cityIns = new CityDAO();
while(result.next()) {
teams.add(new Team(result.getString("name"), result.getString("coach"), cityIns.getCityByID(result.getLong("home_city_id"))));
}
return teams;
}
}
<file_sep>/Java/CSE406/DateTime API/que/CalculateWork.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.time.*;
import static java.time.temporal.ChronoUnit.*;
class CalculateWork extends JFrame {
private JTextField tfWork, tfDate, tfMonth, tfYear;
private JButton calculateButton;
private JLabel lblResult;
public CalculateWork() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(7,2));
add(new JLabel("Total Work: "));
tfWork = new JTextField(20);
add(tfWork);
add(new JLabel("START Date:"));
add(new JLabel("------"));
tfDate = new JTextField(20);
add(new JLabel("Date: "));
add(tfDate);
add(new JLabel("Month: "));
tfMonth = new JTextField(20);
add(tfMonth);
add(new JLabel("Year: "));
tfYear = new JTextField(20);
add(tfYear);
add(new JLabel(""));
calculateButton = new JButton("calculate");
add(calculateButton);
lblResult = new JLabel();
add(lblResult);
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int work = Integer.parseInt(tfWork.getText().trim());
int date = Integer.parseInt(tfDate.getText().trim());
int month = Integer.parseInt(tfMonth.getText().trim());
int year = Integer.parseInt(tfYear.getText().trim());
try{
lblResult.setText(calculate(work, LocalDate.of(year, month, date)));
}catch(Exception e){
System.out.println(e);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Student Details");
setSize(500,300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CalculateWork();
}
});
}
static String calculate(int totaltfWork, LocalDate starttfDate) {
LocalDate nowtfDate = LocalDate.now();
String result = "";
float _totalDaysToDotfWork = ((float)totaltfWork/7);
int totalDaysToDotfWork = 0;
if( (_totalDaysToDotfWork - (int)_totalDaysToDotfWork) != 0)
totalDaysToDotfWork = (int)_totalDaysToDotfWork + 1;
else
totalDaysToDotfWork = (int)_totalDaysToDotfWork;
int daysTillToday = (int)starttfDate.until(nowtfDate, DAYS);
if(daysTillToday > totalDaysToDotfWork)
result += "100% of work is completed.";
else {
result += (daysTillToday*100/totalDaysToDotfWork) + "% of tfWork is completed.\n";
result += "\nExpected date to complete work is " + starttfDate.plusDays(totalDaysToDotfWork);
}
return result;
}
}
<file_sep>/c_cpp/afterSummer/JTG Prepare/spiralTraversalMatrix.cpp
#include <iostream>
using namespace std;
void spiralTraverseMatrix(int a[][4], int n)
{
int i1=0, i2=n, j1=0, j2=n, i, j;
while(i1<i2 || j1<j2)
{
i=i1; j=j1;
while(i!=i2)
{
cout<<a[j][i]<<"\t";
i++;
}
i--;j++;
while(j!=j2)
{
cout<<a[j][i]<<"\t";
j++;
}
j--;i--;
while(i!=i1-1)
{
cout<<a[j][i]<<"\t";
i--;
}
i++;j--;
while(j!=j1)
{
cout<<a[j][i]<<"\t";
j--;
}
i1++;i2--;
j1++;j2--;
}
}
void printMatrix(int a[][4], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
}
int main(int argc, char const *argv[])
{
int a[][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} };
// printMatrix(a, 4);
spiralTraverseMatrix(a, 4);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/sorting/mergeSort.c
#include <stdio.h>
// int c[6] = {0};
// void merge(int a[], int x, int y, int z)
// {
// int k = 0, i, j, n, m;
// i = 0;
// j = 0;
// n = (y - x);
// m = (z - y);
// for( ; k < n && k < m; )
// {
// if(a[x + i] < a[x + j]) c[k++] = a[i++];
// else c[k++] = a[j++];
// }
// for( ; i < n; ) c[k++] = a[i++];
// for( ; j < m; ) c[k++] = a[j++];
// }
int merge(int a[],int i,int m,int j)
{
int p,q,k,index;
int n1=m-i+1;
int n2=j-m;
int l[n1],r[n2];
for(k=0;k<n1;k++)
l[k]=a[k+i];
for(k=0;k<n2;k++)
r[k]=a[k+m+1];
p=0;q=0;index=i;
while(p<n1 && q<n2)
{
if(l[p]<r[q])
{
a[index]=l[p];
p++; index++;
}
else
{
a[index]=r[q];
q++; index++;
}
}
while(p<n1)
{
a[index]=l[p];
p++; index++;
}
while(q<n2)
{
a[index]=r[q];
q++; index++;
}
}
void mergeSort(int a[], int i, int j)
{
if(j > i)
{
int m = (i + j) / 2;
mergeSort(a, i, m);
mergeSort(a, m + 1, j);
merge(a, i, m, j);
}
}
int main(int argc, char const *argv[])
{
int arr[] = {5, 2, 10, 4, 1, 3};
int i = 0, n = 6;
mergeSort(arr, 0, n - 1); // sort the array
printf("\nSorted array:\t"); // print sorted array
for(i = 0; i < n; i++)
printf("%d\t",arr[i]);
return 0;
}
/**
* Divide : Divide the n-element array into two n/2-element
* sub-arrays
* Conquer : Sort the two sub-arrays recursively using
* merge sort
* Combine : Merge the two sorted subsequences to form the
* sorted array
**
#include<stdio.h>
int arr[20]; // array to be sorted
int merge(int arr[],int l,int m,int h)
{
int arr1[10],arr2[10]; // Two temporary arrays to
//hold the two arrays to be merged
int n1,n2,i,j,k;
n1=m-l+1;
n2=h-m;
for(i=0; i<n1; i++)
arr1[i]=arr[l+i];
for(j=0; j<n2; j++)
arr2[j]=arr[m+j+1];
arr1[i]=9999; // To mark the end of each temporary array
arr2[j]=9999;
i=0;
j=0;
for(k=l; k<=h; k++) { //process of combining two sorted arrays
if(arr1[i]<=arr2[j])
arr[k]=arr1[i++];
else
arr[k]=arr2[j++];
}
return 0;
}
int merge_sort(int arr[],int low,int high)
{
int mid;
if(low<high) {
mid=(low+high)/2;
// Divide and Conquer
merge_sort(arr,low,mid);
merge_sort(arr,mid+1,high);
// Combine
merge(arr,low,mid,high);
}
return 0;
}
int main()
{
int n,i;
// printf("Enter the size of array\n"); // input the elements
// scanf("%d",&n);
// printf("Enter the elements:");
// for(i=0; i<n; i++)
// scanf("%d",&arr[i]);
int arr[] = {2, -1, 5, -3, 9, -9};
n = 6;
merge_sort(arr,0,n-1); // sort the array
printf("Sorted array:"); // print sorted array
for(i=0; i<n; i++)
printf("%d\t",arr[i]);
return 0;
}
*/<file_sep>/c_cpp/afterSummer/Test/prog.c
#include <stdio.h>
int complexity = 0;
void printNGE(int a[], int n)
{
int i = 0, j = 0, flag = 0;
for(i = 0; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(a[j] > a[i])
{
printf("%d\t", a[j]);
flag = 1;
break;
}
else
{
flag = 0;
}
complexity++;
}
if(flag == 0)
{
printf("%d\t", -1);
}
}
}
void printArray(int a[], int n)
{
int i = 0;
for (i = 0; i < n; ++i)
{
printf("%d\t", a[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int a[] = {21, 13, 4, 14, 5, 9, 2, 0};
printArray(a, 8);
printNGE(a, 8);
printf("\nComplexity:\t%d\n", complexity);
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/linkedList/reverseList.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head, *trav, *temp, *temp2;
struct Node *newNode(int data)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNode(int data)
{
trav = head;
if(head == NULL)
head = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void reverseList()
{
if(head == NULL)
printf("List is Empty.\n");
else if(head -> next == NULL)
return;
else if( (head -> next) -> next == NULL)
{
trav = head;
head = head -> next;
head -> next = trav;
trav -> next = NULL;
}
else
{
temp = head;
trav= temp -> next;
temp2 = trav -> next;
head -> next =NULL;
// trav -> next = temp;
temp = trav;
trav= trav -> next;
temp2 = temp2 -> next;
while(temp2 != NULL)
{
// trav -> next = temp;
// temp = trav;
// trav = temp2;
// temp2 = temp2 -> next;
temp -> next = head;
head = temp;
temp = trav;
trav = trav -> next;
temp2 = temp2 -> next;
}
temp -> next = head;
head = temp;
trav -> next = head;
head = trav;
}
}
void printList()
{
trav = head;
if(head == NULL)
printf("List is Empty.\n");
else
{
printf("\nList:\t");
while(trav != NULL)
{
printf("%d\t", trav -> data);
trav = trav -> next;
}
printf("\n\n");
}
}
int main(int argc, char const *argv[])
{
insertNode(3);
insertNode(5);
insertNode(8);
insertNode(6);
insertNode(9);
// insertNode(1);
reverseList();
printList();
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/q4.c
#include <stdio.h>
int m, max1, max2;
int maxArray(int a[], int i, int j)
{
if( (j - i) == 0) return a[i];
else
{
m = (i + j) / 2;
max1 = maxArray(a, i, m);
max2 = maxArray(a, m + 1, j);
if(max1 > max2) return max1;
else return max2;
}
}
int main(int argc, char const *argv[])
{
int a[] = {3, 1, 2, 5, 10, 1, 4};
printf("Max:\t%d\n", maxArray(a, 0, 7));
return 0;
}
<file_sep>/c_cpp/afterSummer/Questions/DP/maxSquareSubMatrix.cpp
#include <iostream>
using namespace std;
int getMin(int a, int b, int c)
{
if(a<b && a<c)
return a;
else if(b<a && b<c)
return b;
else
return c;
}
int getMaxSquareSubMatrix(int a[][5], int x, int y)
{
int maxSquare = 0;
for (int i = 1; i < y; i++)
{
for (int j = 1; j < x; j++)
{
if(a[i][j] == 1 && a[i-1][j] > 0 && a[i][j-1] > 0 && a[i-1][j-1] > 0)
{
a[i][j] = 1 + getMin(a[i-1][j-1], a[i-1][j], a[i][j-1]);
}
(a[i][j] > maxSquare) ? maxSquare = a[i][j] : maxSquare = maxSquare;
}
}
return maxSquare;
}
int main(int argc, char const *argv[])
{
int matrix[][5] = { {0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0} };
cout<<"Maximum Square Matrix:\t"<<getMaxSquareSubMatrix(matrix, 6, 5)<<endl;
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/printBinary.c
#include <stdio.h>
char s[10] = "000000000";
int i = 0;
int binary(int n)
{
if(n == 1) printf("1");
else
{
binary(n/2);
if(n%2 == 0) printf("0");
else printf("1");
}
}
int main(int argc, char const *argv[])
{
binary(1);
// printf("%s\n", s);
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/evenOccuranceString.c
//find which occur even times in a string
#include <stdio.h>
int evenOccuranceString(char* s, int len)
{
int a[26] = {0};
int i = 0;
for(i = 0; i < len; i++)
{
a[s[i] - 97]++;
}
for(i = 0; i < 26; i++)
{
if( (a[i]%2) == 0 && a[i] != 0)
{
printf("%c\t", i + 97);
}
}
printf("\n");
}
int main(int argc, char const *argv[])
{
evenOccuranceString("abcefa", 6);
evenOccuranceString("aaa", 3);
evenOccuranceString("abcdefghijklmnopqrstuvwxyz", 26);
evenOccuranceString("cc", 2);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Thread - Predict Scores java/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
Integer start;
Integer end;
System.out.println("Enter range of numbers");
Scanner sc = new Scanner(System.in);
start = Integer.parseInt(sc.nextLine());
end = Integer.parseInt(sc.nextLine());
sc.close();
Scores odd = new Scores("Odd", start, end);
odd.start();
Scores even = new Scores("Even", start, end);
even.start();
try{
odd.join();
even.join();
}catch(Exception e){
}
System.out.println("Odd numbers in given range");
odd.display();
System.out.println("\nEven numbers in given range");
even.display();
}
}
<file_sep>/Java/CTS_SFDC/workspace/Delivery Details/src/Delivery.java
public class Delivery {
private
Long over;
Long ball;
String batsman;
String bowler;
String nonStriker;
public Long getOver() {
return over;
}
public void setOver(Long over) {
this.over = over;
}
public Long getBall() {
return ball;
}
public void setBall(Long ball) {
this.ball = ball;
}
public String getBatsman() {
return batsman;
}
public void setBatsman(String batsman) {
this.batsman = batsman;
}
public String getBowler() {
return bowler;
}
public void setBowler(String bowler) {
this.bowler = bowler;
}
public String getNonStriker() {
return nonStriker;
}
public void setNonStriker(String nonStriker) {
this.nonStriker = nonStriker;
}
public Delivery(Long over, Long ball, String batsman, String bowler,
String nonStriker) {
this.over = over;
this.ball = ball;
this.batsman = batsman;
this.bowler = bowler;
this.nonStriker = nonStriker;
}
public String toString()
{
return String.format("Over :"+getOver()+"\nBall :"+getBall()+"\nBatsman :"+getBatsman()+"\nBowler :"+getBowler()+"\nNonStriker :"+getNonStriker());
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/sorting/selectionSort.c
#include <stdio.h>
int c = 0;
void selectionSort(int a[], int n)
{
int i = 0, j = 0, min = 0, temp = 0;
bool flag;
for(i = 0; i < n; i++)
{
min = i;
flag = false;
for(j = i + 1; j < n; j++)
{
if(a[j] < a[min])
{
min = j;
flag = true;
}
c++;
}
if(flag == true)
{
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
int main(int argc, char const *argv[])
{
int a[] = {5, 2, 10, 4, 1, 3};
int i = 0, n = 6;
selectionSort(a, n); // sort the array
printf("Complexity:\t%d\nSorted array:\t", c); // print sorted array
for(i = 0; i < n; i++)
printf("%d\t",a[i]);
return 0;
}<file_sep>/c_cpp/afterSummer/JTG Prepare/sortBinaryArray.cpp
#include <iostream>
using namespace std;
void sortBinaryArray(int a[], int n)
{
int i=0, j=n-1;
while(i<j)
{
while(a[i]==0)
i++;
while(a[j]==1)
j--;
if(i<j)
swap(a[i],a[j]);
}
for (i = 0; i < n; i++)
cout<<a[i]<<"\t";
}
int main(int argc, char const *argv[])
{
int a[] = {0,0,1,0,0,1,1,0};
int b[] = {1,0,0,1,1,1};
sortBinaryArray(a,sizeof(a)/sizeof(a[0]));
cout<<endl;
sortBinaryArray(b,sizeof(b)/sizeof(b[0]));
return 0;
}
<file_sep>/c_cpp/afterSummer/Questions/Graph/graph.cpp
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#define MAX 100
using namespace std;
bool static visited[MAX]={false};
void bfs(std::vector<std::vector<int> > g, int first)
{
queue<int> gq;
gq.push(first);
memset(visited, false, sizeof(bool)*MAX);
int v;
while(!gq.empty())
{
v = gq.front();
gq.pop();
if(visited[v] == true)
continue;
visited[v] = true;
cout<<v<<" -- ";
for (std::vector<int>::iterator iter = g[v].begin(); iter != g[v].end(); iter++)
{
if(visited[*iter] != true)
gq.push(*iter);
}
}
}
void dfs(std::vector<std::vector<int> > g, int first)
{
stack<int> GS;
GS.push(first);
memset(visited, false, sizeof(bool)*MAX);
int v;
while(!GS.empty())
{
v = GS.top();
GS.pop();
if(visited[v] == true)
continue;
visited[v] = true;
cout<<v<<" -- ";
for (std::vector<int>::iterator iter = g[v].begin(); iter != g[v].end(); iter++)
{
if(visited[*iter] != true)
GS.push(*iter);
}
}
}
void _recDFS(std::vector<std::vector<int> > g, int v)
{
visited[v] = true;
cout<<v<<" -- ";
for (int i = 0; i < g[v].size(); i++)
{
if(visited[g[v][i]] == false)
_recDFS(g, g[v][i]);
}
}
void recDFS(std::vector<std::vector<int> > g, int first)
{
memset(visited, false, sizeof(bool)*MAX);
_recDFS(g, first);
}
int main(int argc, char const *argv[])
{
int n=10;
int color[MAX]={-1};
std::vector<std::vector<int> > graph;
graph.resize(10);
graph[1].push_back(2);
graph[1].push_back(3);
graph[3].push_back(6);
graph[2].push_back(4);
graph[2].push_back(5);
graph[5].push_back(7);
graph[5].push_back(8);
graph[5].push_back(9);
cout<<endl<<"BFS:\t\t";
bfs(graph, 1);
cout<<endl<<"DFS:\t\t";
dfs(graph, 1);
cout<<endl<<"recDFS:\t\t";
recDFS(graph, 1);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Game Details By Venue/src/gameDetail/GameDAO.java
package gameDetail;
import java.util.ArrayList;
public class GameDAO {
public ArrayList<Game> listGames(int id) throws ClassNotFoundException {
return new ArrayList<>();
}
}
<file_sep>/Java/CTS_SFDC/workspace/Match Details/src/Main.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
Long r;
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Menu\n1.Match Date\n2.Match Venue\n3.Match Outcome");
i = sc.nextInt();
sc.nextLine();
Match m = new Match();
if(i == 1) {
System.out.println("Enter the date of the match");
s = sc.nextLine();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date dt = sdf.parse(s);
m.displayMatchDetails(dt);
} catch(Exception e) {
}
} else if(i == 2) {
System.out.println("Enter venue of the match");
s = sc.nextLine();
m.displayMatchDetails(s);
} else if(i == 3) {
System.out.println("Enter the winner team of the match");
s = sc.nextLine();
System.out.println("Enter the number of runs");
r = sc.nextLong();
m.displayMatchDetails(s, r);
}
sc.close();
}
}
<file_sep>/Java/CTS_SFDC/workspace/Player (Split)/src/Player.java
public class Player {
String name, country, skill;
}
<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/checkFunnyString.cpp
#include <iostream>
using namespace std;
int absolute(int a)
{
if(a < 0)
return (-a);
return a;
}
int checkFunnyString(string s)
{
for (int i = 1; i < s[i] != '\0'; i++)
if(absolute(s[i] - s[i-1]) != absolute(s[s.length()-i] - s[s.length()-i-1]))
return false;
return true;
}
int main(int argc, char const *argv[])
{
string s = "acxz";
(checkFunnyString(s)) ? cout<<"True - Funny"<<endl : cout<<"False - Not Funny"<<endl;
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/tree/insertBinaryTreeLevelOrder.c
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree *root, *trav;
struct tree *newNode(int data)
{
struct tree *node = (struct tree *) malloc(sizeof(struct tree));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return node;
}
void insertNode(struct tree* head, int data)
{
if(root == NULL)
{
root = newNode(data);
return;
}
else
{
if(head -> left == NULL)
{
printf("lN %d\n\n", data);
head -> left = newNode(data);
}
else if(head -> right == NULL)
{
printf("rN %d\n\n", data);
head -> right = newNode(data);
}
else if(head -> left != NULL)
{
printf("l %d\n", head -> left -> data);
insertNode(head -> left, data);
}
else if(head -> right != NULL)
{
printf("r %d\n", data);
insertNode(head -> right, data);
}
}
}
void printTree(struct tree *head)
{
if(head != NULL)
{
printf("%d\t", head -> data);
printTree(head -> left);
printTree(head -> right);
}
}
int main(int argc, char const *argv[])
{
insertNode(root, 100);
insertNode(root, 50);
insertNode(root, 200);
insertNode(root, 40);
insertNode(root, 90);
insertNode(root, 150);
insertNode(root, 300);
// insertNode(root, 49);
// insertNode(root, 8);
printTree(root);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/.metadata/.plugins/org.eclipse.core.resources/.history/ea/30c8578e5dfe001612c3b365f30cdcfb
db.url=jdbc:mysql://127.0.0.1:3306/ipl
db.username=root
db.password=<PASSWORD>
<file_sep>/c_cpp/afterSummer/Questions/DP/maxSumIncreasingSubSequence.cpp
#include <iostream>
using namespace std;
int getMax(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int maxSumIncreasingSubSequence(int a[], int n)
{
int temp[n] = {0};
int maxSum = 0, j = 0;
if(n <= 1)
return a[0];
temp[0] = a[0];
for (int i = 1; i < n; i++)
{
j = i - 1;
while(a[i] < a[j])
{
if(j<=0)
break;
j--;
}
temp[i] = a[i] + temp[j];
maxSum = getMax(maxSum, temp[i]);
}
return maxSum;
}
int main(int argc, char const *argv[])
{
int a[] = {1, 101, 2, 3, 100, 4, 5};
int b[] = {100, 101, 1, 2, 3, 4};
int c[] = {10, 15, 11, 12, 13};
cout<<maxSumIncreasingSubSequence(a, sizeof(a)/sizeof(a[0]))<<endl;
cout<<maxSumIncreasingSubSequence(b, sizeof(b)/sizeof(b[0]))<<endl;
cout<<maxSumIncreasingSubSequence(c, sizeof(c)/sizeof(c[0]))<<endl;
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Game Details By Venue/src/gameDetail/VenueBO.java
package gameDetail;
import java.sql.SQLException;
public class VenueBO {
public String[] getAllVenues() throws ClassNotFoundException, SQLException {
return new VenueDAO().getAllVenues();
}
}
<file_sep>/c_cpp/c/day 1/binSearch.cpp
#include<iostream>
using namespace std;
int flag=0;
int binSearch(int arr[],int key,int high)
{
int low=0;
int mid;
while(low<=high){
mid=(low+high)/2;
if(arr[mid]==key)
return mid;
if(arr[mid]>key)
high=mid-1;
else low=mid+1;
}
flag=1;
return low;
}
int main()
{
int ar[100],key,len,index;
cout<<"Enter array length = ";
cin>>len;
cout<<" Enter Array \n";
for(int i=0;i<len;i++)
{
cin>>ar[i];
}
cout<<"\nEnter the key to find";
cin>>key;
index=binSearch(ar,key,len-1);
if(flag==1)
cout<<"Not found key, Deserving at "<<index;
else cout<<" found at "<<index;
}
<file_sep>/Java/CSE406/Design Patterns/Builder/MyName.java
public class MyName{
private final String fName;
private final String lName;
private MyName(NestMyName ref){
this.fName = ref.fName;
this.lName = ref.lName;
}
public String toString(){
return this.fName + " " + this.lName;
}
public static class NestMyName{
private final String fName;
private String lName;
public NestMyName(String fName){
this.fName = fName;
}
public NestMyName lName(String lName){
this.lName = lName;
return this;
}
public MyName build(){
MyName mn = new MyName(this);
return mn;
}
}
}
<file_sep>/c_cpp/beforeSummer/Paper 1/q2.c
#include <stdio.h>
void func(int n, int l[])
{
}
int main(int argc, char const *argv[])
{
int n = 3;
int l[] = {4, 5, 80};
func(n , l);
return 0;
}<file_sep>/c_cpp/c/day 5/2arraykey.cpp
#include<iostream>
using namespace std;
main()
{
int i,j,k=10;
int arr1[]={1,4,5,6,7};
int arr2[]={9,10,11,12,13};
for(i=0,j=5;i<5&&j>0;)
{
if(arr1[i]+arr2[j]>k)
j--;
else if(arr1[i]+arr2[j]<k)
i++;
else if(arr1[i]+arr2[j]==k)
cout<<arr1[i]<<arr2[j];
}
}
<file_sep>/Java/CTS_SFDC/workspace/Display Batsmans Details/src/Player.java
public class Player {
int id;
String name;
String country;
Skill skill;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public Player(int id, String name, String country, Skill skill) {
super();
this.id = id;
this.name = name;
this.country = country;
this.skill = skill;
}
}
<file_sep>/c_cpp/c/day 3/mergesort.cpp
#include<iostream>
using namespace std;
void merge(int arr[],int i,int mid,int j)
{
int k;
int c[100];
int n=mid;
int m=j;
int a=i;
int b=mid+1;
for(k=0;a<=n&&b<=m;k++)
{
if(arr[a]<arr[b])
{
c[k]=arr[a];
a++;
}
else{
c[k]=arr[b];
b++;}
}
for(;a<=n;)
c[k++]=arr[a++];
for(;b<=m;)
c[k++]=arr[b++];
for(k=0;k<j-i+1;k++)
arr[k]=c[k];
}
void mergesort(int arr[],int i,int j)
{
int m;
if(i<j)
{
m=(i+j)/2;
mergesort(arr,i,m);
mergesort(arr,m+1,j);
merge(arr,i,m,j);
}
}
int main()
{
int arr[]={3,7,2,5,6,1};
mergesort(arr,0,5);
for(int i=0;i<6;i++)
cout<<arr[i]<<endl;
}
<file_sep>/Python/pythonWorkshop/project/config.py
import os
"""
pip install flask-sqlalchemy flask-script
"""
DEBUG=True
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
<file_sep>/c_cpp/beforeSummer/prep_class/linkedList/countNodeUsingRecursion.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head, *trav, *temp;
struct Node *newNode(int data)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNode(int data)
{
trav = head;
if(head == NULL)
head = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
// int countNode()
// {
// int x;
// trav = head;
// if(head == NULL)
// x = 0;
// else
// {
// while(trav != NULL)
// {
// trav = trav -> next;
// x++;
// }
// }
// return x;
// }
int countNode(struct Node *t)
{
if(t == NULL)
return 0;
else
return 1 + countNode(t -> next);
}
int main(int argc, char const *argv[])
{
insertNode(3);
insertNode(5);
insertNode(8);
insertNode(6);
insertNode(9);
insertNode(1);
printf("No. of Nodes:\t%d\n", countNode(head));
return 0;
}<file_sep>/c_cpp/c/day 5/sizek.cpp
#include<iostream>
using namespace std;
main()
{
int a[]={1,2,3,4,5};
int k=3;
int sum=0;
int max;
for(int i=0;i<k;i++)
{
sum+=a[i];
}
max=sum;
for(int i=k;i<5;i++)
{
sum+=a[i]-a[i-k];
if(sum>max)
{
max=sum;
}
}
cout<<max;
}
<file_sep>/c_cpp/beforeSummer/prep_class/array/maxContSumArrayOfSizeA.c
#include <stdio.h>
int getMaxSumArray(int a[], int l)
{
int i = 0, j = 0, sum = 0, lsum = a[0], c = 0;
//block size of contigous elements
i = 0;
sum = 0;
//sub arrays
for(j = 0; j < l; j++)
{
sum += a[j];
c++;
if(sum > lsum)
lsum = sum;
}
printf("\nComplexity:\t%d\n", c);
return lsum;
}
int main(int argc, char const *argv[])
{
int a[11] = {-2, 1, -3, 4, -1, 2, 1, -5, 4, -10, 12};
printf("Sum:\t%d\n", getMaxSumArray(a, 11));
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/HW Questions/Day 6/zigZagPathProblem.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int x;
int y;
struct Node *next;
};
struct Node *head, *trav, *temp, *t;
struct Node *newNode(int x, int y)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> x = x;
node -> y = y;
node -> next = NULL;
return node;
}
void insertNode(int x, int y)
{
trav = head;
if(head == NULL)
head = newNode(x, y);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(x, y);
}
}
void printList()
{
trav = head;
if(head == NULL)
printf("List is Empty.\n");
else
{
printf("\nList:\n");
while(trav != NULL)
{
printf("%d\t%d\n", trav -> x, trav -> y);
trav = trav -> next;
}
printf("\n\n");
}
}
int removeNode(struct Node *head)
{
temp = head;
trav = temp -> next;
while(trav -> next != NULL)
{
printf("%d\t%d\n", trav -> x, trav -> y);
if ( ( (temp -> y == trav -> y) && (trav -> y == (trav -> next) -> y) ) ||
( (temp -> x == trav -> x) && (trav -> x == (trav -> next) -> x) ) )
{
printf("%d\t%d\n", trav -> x, trav -> y);
temp -> next = trav -> next;
t = trav;
trav = trav -> next;
free(t);
}
else
{
temp = trav;
trav = trav -> next;
}
}
}
int main(int argc, char const *argv[])
{
insertNode(0, 0);
insertNode(1, 0);
insertNode(1, -1);
insertNode(0, -1);
insertNode(0, -2);
insertNode(0, -3);
insertNode(0, -4);
insertNode(1, -4);
insertNode(2, -4);
insertNode(3, -4);
insertNode(4, -4);
insertNode(5, -4);
removeNode(head);
printList();
return 0;
}<file_sep>/c_cpp/c/day 1/wtf.cpp
#include<iostream>
using namespace std;
int a[4][4]={0};
main()
{ int A=4;
int n=1;
int i=0,j=0;
while(n<=A*A){
while(j<A&& n<=A*A && a[i][j]==0) a[i][j++]=n++;
i++;j--;
while(i<A&& n<=A*A && a[i][j]==0) a[i++][j]=n++;
i--;j--;
while(j>=0 && n<=A*A && a[i][j]==0) a[i][j--]=n++;
i--;j++;
while(i>=0 && n<=A*A && a[i][j]==0) a[i--][j]=n++;
i++;j++;
}
for(i=0;i<A;i++)
{
for(j=0;j<A;j++)
cout<<a[i][j];
cout<<"\n";
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/linkedList/isPalindrome.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head, *trav, *temp, *temp2, *t;
struct Node *newNode(int data)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNode(int data)
{
trav = head;
if(head == NULL)
head = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
int countNode(struct Node *t)
{
if(t == NULL)
return 0;
else
return 1 + countNode(t -> next);
}
void reverseList(int x)
{
x -= 2;
temp = head;
trav= temp -> next;
temp2 = trav -> next;
head -> next =NULL;
temp = trav;
trav= trav -> next;
temp2 = temp2 -> next;
while(x >= 0)
{
temp -> next = head;
head = temp;
temp = trav;
trav = trav -> next;
temp2 = temp2 -> next;
x--;
}
t = temp;
// head = temp;
}
void printList()
{
trav = head;
if(head == NULL)
printf("List is Empty.\n");
else
{
printf("\nList:\t");
while(trav != NULL)
{
printf("%d\t", trav -> data);
trav = trav -> next;
}
printf("\n\n");
}
}
bool compare(struct Node *a, struct Node *b)
{
while(a != NULL && b!= NULL)
{
// printf("%d\t%d\n", a -> data, b -> data);
if(a -> data != b -> data)
return false;
a = a -> next;
b = b -> next;
}
return true;
}
int main(int argc, char const *argv[])
{
insertNode(3);
insertNode(5);
insertNode(8);
insertNode(6);
insertNode(8);
insertNode(5);
insertNode(3);
int a = countNode(head);
if(a%2 == 0)
{
reverseList(a/2);
a = compare(head, t);
}
else
{
reverseList( (a/2) + 1 );
head = head -> next;
a = compare(head, t);
}
if(a == 0)
printf("Not Palindrome.\n");
else
printf("Palindrome.\n");
// printf("No. of Nodes:\t%d\n", countNode(head));
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Match Details II/src/Match.java
public class Match {
String date;
String teamOne;
String teamTwo;
String venue;
public Match(String date, String teamOne, String teamTwo, String venue) {
super();
this.date = date;
this.teamOne = teamOne;
this.teamTwo = teamTwo;
this.venue = venue;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTeamOne() {
return teamOne;
}
public void setTeamOne(String teamOne) {
this.teamOne = teamOne;
}
public String getTeamTwo() {
return teamTwo;
}
public void setTeamTwo(String teamTwo) {
this.teamTwo = teamTwo;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
@Override
public String toString() {
return String.format("%-35s %-30s %-15s %s", this.getTeamOne(), this.getTeamTwo(), this.getDate(), this.getVenue());
}
}
<file_sep>/c_cpp/c/day 4/SORT_STACK.cpp
#include<iostream>
using namespace std;
int stack[100];
int top=-1;
void push(int x)
{
if(top==100){
cout<<"Overflow" ;}
else{
top++;
stack[top]=x;
}
}
int peek()
{
return stack[top];
}
int pop()
{
if(top==-1) cout<<"Underflow";
else {
int x=stack[top];
top--;
return x;
}
}
void sortedIns(int y)
{
if(stack[top]<=y || top==-1)
{
push(y);
}
else{
int x=pop();
sortedIns(y);
push(x);
}
}
void sort()
{
if(top==-1) return;
int y=pop();
sort();
sortedIns(y);
}
int main()
{
int n;
for(int i=0;i<4;i++)
{
cin>>n;
push(n);
}
sort();
for(int i=0;i<4;i++){
cout<<pop()<<endl;
}
}
<file_sep>/Java/CSE406/Generics & Collections/List/TestLinkedList.java
import java.util.*;
class TestLinkedList{
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>();
ll.add(20);
ll.add(30);
ll.add(40);
ll.addFirst(10);
ll.addLast(50);
ll.removeLast();
System.out.println(ll);
}
}
<file_sep>/Java/CTS_SFDC/workspace/Comparable - List Match By Date II/src/Match.java
import java.util.Date;
public class Match implements Comparable<Match> {
Date matchDate;
String venue;
String teamOne;
String teamTwo;
public Match(Date matchDate, String venue, String teamOne, String teamTwo) {
super();
this.matchDate = matchDate;
this.venue = venue;
this.teamOne = teamOne;
this.teamTwo = teamTwo;
}
public Date getMatchDate() {
return matchDate;
}
public void setMatchDate(Date matchDate) {
this.matchDate = matchDate;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public String getTeamOne() {
return teamOne;
}
public void setTeamOne(String teamOne) {
this.teamOne = teamOne;
}
public String getTeamTwo() {
return teamTwo;
}
public void setTeamTwo(String teamTwo) {
this.teamTwo = teamTwo;
}
@Override
public int compareTo(Match o) {
return this.getMatchDate().compareTo(o.getMatchDate());
}
}
<file_sep>/c_cpp/afterSummer/Questions/DP/weightedJobScheduling.cpp
#include <iostream>
#include <vector>
using namespace std;
struct Job
{
int start;
int finish;
int profit;
};
bool jobComparator(Job s1, Job s2)
{
return (s1.finish < s2.finish);
}
int weightedJobScheduling(Job s[], int n)
{
sort(s.begin(), s.end(), jobComparator);
cout<<s[3].profit;
}
int main(int argc, char const *argv[])
{
Job s[4];
for (int i = 0; i < 4; i++)
{
cout<<endl<<"Job "<<i+1<<endl<<"start:\t";
cin>>s[i].start;
cout<<"finish:\t";
cin>>s[i].finish;
cout<<"profit:\t";
cin>>s[i].profit;
}
return 0;
}<file_sep>/Python/pythonWorkshop/tushar files/project/app/apis.py
from flask import jsonify
from app import app_api
@app_api.route('/')
def index () :
return jsonify({'message': 'hellom world!'})
<file_sep>/Java/CTS_SFDC/workspace/ExtraType/src/Main.java
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the extratype details");
s = sc.nextLine();
sc.close();
StringTokenizer st = new StringTokenizer(s, "#");
ExtraType e = new ExtraType();
e.setName(st.nextToken());
e.setRuns(Long.parseLong(st.nextToken()));
System.out.printf("ExtraType Details\nExtra Type:%s\nRuns:%d", e.getName(), e.getRuns());
}
}
<file_sep>/Java/CTS_SFDC/workspace/Comparator - Team name and Number of matches/src/Team.java
public class Team implements Comparable<Team> {
String name;
Long numberOfMatches;
public Team(String name, Long numberOfMatches) {
super();
this.name = name;
this.numberOfMatches = numberOfMatches;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getNumberOfMatches() {
return numberOfMatches;
}
public void setNumberOfMatches(Long numberOfMatches) {
this.numberOfMatches = numberOfMatches;
}
@Override
public int compareTo(Team o) {
return (int) (this.getNumberOfMatches() - o.getNumberOfMatches());
}
}
<file_sep>/Java/CTS_SFDC/workspace/JDBC - Insert new Venue/src/VenueDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class VenueDAO {
public void createVenue(Venue venue) throws ClassNotFoundException, SQLException {
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String username=rb.getString("db.username");
String pass=rb.getString("db.password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,username,pass);
Statement statement = con.createStatement();
String sql = "select id from venue order by id desc";
ResultSet result = statement.executeQuery(sql);
result.next();
long id = result.getLong("id");
result.close();
sql = "insert into venue(id,name,city_id) values("
+ (++id) + ",'" + venue.getName() + "'," + venue.getCity().getCityId() + ")";
statement.executeUpdate(sql);
System.out.println("Venue has been created");
}
public List<Venue> getAllVenues() throws ClassNotFoundException, SQLException{
List<Venue> venues = new ArrayList<>();
ResourceBundle rb= ResourceBundle.getBundle("mysql");
String url=rb.getString("db.url");
String user=rb.getString("db.username");
String pass=rb.getString("db.password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,pass);
Statement statement = con.createStatement();
String sql = "select * from venue order by name";
ResultSet result = statement.executeQuery(sql);
CityDAO cityIns = new CityDAO();
while(result.next()) {
venues.add(new Venue(result.getString("name"), cityIns.getCityByID(result.getLong("city_id"))));
}
return venues;
}
}
<file_sep>/c_cpp/c/levelOrderTraversalforBST.c
#include<stdio.h>
#include<stdlib.h>
struct treeNode
{
int d;
struct treeNode* l;
struct treeNode* r;
};
/////////////////////// Queue //////////////////////////////////////////////////
struct node
{
struct treeNode* data;
struct node *next;
};
struct node* head;
struct node* top;
struct node* newNodeQueue(struct treeNode* data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void enque(struct treeNode* data)
{
if(head == NULL)
{
head = newNodeQueue(data);
top = head;
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNodeQueue(data);
}
// printf("Node Added Succesfully\n");
}
struct treeNode* deque()
{
if(head == NULL)
{
// printf("List is NULL\n");
return NULL;
}
else
{
struct node* trav = head;
struct treeNode* temp = trav -> data;
if(head -> next == NULL)
{
head = NULL;
top = NULL;
}
else
{
head = head -> next;
}
free(trav);
// printf("POPPED Succesfully\n");
return temp;
}
}
////////////////////////////////////////////////////////////////////////////////////////
struct treeNode* root;
struct treeNode* newNode(int data)
{
struct treeNode *newN = (struct treeNode*) malloc(sizeof(struct treeNode));
newN -> d = data;
newN -> l = NULL;
newN -> r = NULL;
return newN;
}
void preTrav(struct treeNode* root)
{
if(root != NULL)
{
printf("%d\t", root -> d);
preTrav(root -> l);
preTrav(root -> r);
}
}
void postTrav(struct treeNode* root)
{
if(root != NULL)
{
postTrav(root -> l);
postTrav(root -> r);
printf("%d\t", root -> d);
}
}
void inTrav(struct treeNode* root)
{
if(root != NULL)
{
inTrav(root -> l);
printf("%d\t", root -> d);
inTrav(root -> r);
}
}
struct treeNode* insertNode(struct treeNode* root, int data)
{
if(root == NULL)
{
root = newNode(data);
}
else
{
if(data < (root -> d))
{
root -> l = insertNode(root -> l, data);
}
else
{
root -> r = insertNode(root -> r, data);
}
}
return root;
}
int c;
int countNode(struct treeNode* root)
{
if(root != NULL)
{
c++;
countNode(root -> l);
countNode(root -> r);
}
return c;
}
int count = 0;
void levelTrav()
{
count++;
struct treeNode* temp = deque();
if(temp != NULL)
{
// enque(trav);
printf("%d\t",temp -> d);
if(temp -> l != NULL) enque(temp -> l);
if(temp -> r != NULL) enque(temp -> r);
levelTrav();
}
}
int max(int x, int y)
{
if(x > y) return x;
else return y;
}
int getHeight(struct treeNode* root)
{
if(root == NULL) return 0;
return (1 + max(getHeight(root -> l), getHeight(root -> r)));
}
int getDiameter(struct treeNode* root)
{
if(root == NULL) return 0;
int lheight = getHeight(root -> l);
int rheight = getHeight(root -> r);
int ldiameter = getDiameter(root -> l);
int rdiameter = getDiameter(root -> r);
// return (1 + max(getHeight( root -> l), getHeight( root -> r));
return max( 1 +lheight + rheight, max(ldiameter, rdiameter));
}
bool isMirror(struct treeNode* root1, struct treeNode* root2)
{
if(root1 == NULL || root2 == NULL) return true;
if( (root1 -> l -> d == root2 -> r -> d) && (root2 -> l -> d == root1 -> r -> d) )
{
isMirror(root1 -> l, root1 -> r);
isMirror(root2 -> l, root2 -> r);
return true;
}
else return false;
}
bool isSymmetric(struct treeNode* root1, struct treeNode* root2)
{
if(root == NULL) return true;
return isMirror(root1, root2);
}
bool checkMin(struct treeNode* root1, struct treeNode* root2)
{
if(root1 -> d <= root2 -> d) return true;
else return false;
}
bool isBST(struct treeNode* root)
{
if(root == NULL) return true;
if(root -> l != NULL && !checkMin(root -> l, root)) return false;
if(root -> r != NULL && !checkMin(root, root -> r)) return false;
if(root -> l != NULL && root -> r != NULL && !( (isBST(root -> l)) && (isBST(root -> r)) ) ) return false;
return true;
}
int temp = 0;
int getInOrderPredecessor(struct treeNode* root, int data)
{
if(root != NULL)
{
if(getInOrderPredecessor(root -> l, data) != 0) return getInOrderPredecessor(root -> l, data);
if(data == root -> d) return temp; else temp = root -> d;
if(getInOrderPredecessor(root -> r, data) != 0) return getInOrderPredecessor(root -> r, data);
}
}
int preArr[] = {2,3,4,5,7,10,12}, postArr[] = {5,3,2,4,10,7,12};
int main()
{
root = NULL;
// root = newNode(1);
// root -> l = newNode(2);
// root -> r = newNode(3);
// root -> l -> l = newNode(4);
// root -> l -> r = newNode(5);
// root -> r -> r = newNode(6);
// insertNode(root, 7);
// insertNode(root, 8);
// insertNode(root, 9);
// insertNode(root, 10);
// insertNode(root, 11);
// insertNode(root, 12);
// insertNode(root, 13);
// insertNode(root, 14);
// root = insertNode(root, 10);
// insertNode(root, 7);
// insertNode(root, 5);
// insertNode(root, 9);
// insertNode(root, 15);
// insertNode(root, 11);
// insertNode(root, 20);
// root = insertNode(root, 10);
// insertNode(root, 7);
// insertNode(root, 5);
// insertNode(root, 9);
// insertNode(root, 15);
// insertNode(root, 11);
// insertNode(root, 20);
root = insertNode(root, 10);
insertNode(root, 7);
insertNode(root, 9);
insertNode(root, 5);
insertNode(root, 15);
insertNode(root, 11);
insertNode(root, 20);
printf("\nPre-Order Trversal:\t");
preTrav(root);
printf("\nPost-Order Trversal:\t");
postTrav(root);
printf("\nIn-Order Trversal:\t");
inTrav(root);
countNode(root);
printf("\nCount:\t%d\n", c);
printf("\n\nLevel Wise Trversal:\t");
enque(root);
levelTrav();
printf("Complexity: O(%d)\t---->\tO(n + %d)\n", count, count - c);
printf("\nHeight: %d\t", getHeight(root));
printf("\nDiameter: %d\t", getDiameter(root));
printf("\nSymmetric: %d\t", isSymmetric(root, root));
printf("\nIs BST: %d\t", isBST(root));
int n = 11;
getInOrderPredecessor(root, n);
printf("\nIn Order Predecessor of %d : %d\tTemp:%d\n", n, getInOrderPredecessor(root, n), temp);
}<file_sep>/c_cpp/afterSummer/Questions/DP/longestBitonicSubSequence.cpp
#include <iostream>
using namespace std;
int getMax(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int maxSumIncreasingSubSequence(int a[], int n)
{
int LIS[n] = {0}, LDS[n] = {0};
int max = 0;
if(n <= 1)
return 1;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if(a[i] > a[j] && LIS[i] < LIS[i] + 1)
LIS[i] += 1;
}
}
for (int i = n-2; i >= 0; i--)
{
for (int j = n-1; j > i; j--)
{
if(a[i] > a[j] && LDS[i] < LDS[i] + 1)
LDS[i] += 1;
}
}
for (int i = 0; i < n; i++)
{
max = getMax(max, LIS[i] + LDS[i] - 1);
}
return max;
}
int main(int argc, char const *argv[])
{
int a[] = {1, 11, 2, 10, 4, 5, 2, 1};
int b[] = {4, 5, 3, 2, 1, 40};
int c[] = {80, 60, 30, 40, 20, 10};
int d[] = {12, 11, 40, 5, 3, 1};
cout<<maxSumIncreasingSubSequence(a, sizeof(a)/sizeof(a[0]))<<endl;
cout<<maxSumIncreasingSubSequence(b, sizeof(b)/sizeof(b[0]))<<endl;
cout<<maxSumIncreasingSubSequence(c, sizeof(c)/sizeof(c[0]))<<endl;
cout<<maxSumIncreasingSubSequence(d, sizeof(d)/sizeof(d[0]))<<endl;
return 0;
}<file_sep>/c_cpp/beforeSummer/prep_class/q2.c
#include <stdio.h>
int main(int argc, char const *argv[])
{
int A = 300;
int n = 1;
int i = 0, j = 0;
int ans[300][300] = {0};
while(n <= A*A)
{
while(j < A && n <= A*A && ans[i][j] == 0) ans[i][j++] = n++;
i++; j--;
while(i < A && n <= A*A && ans[i][j] == 0) ans[i++][j] = n++;
i--; j--;
while(j >= 0 && n <= A*A && ans[i][j] == 0) ans[i][j--] = n++;
i--; j++;
while(i >= 0 && n <= A*A && ans[i][j] == 0) ans[i--][j] = n++;
i++; j++;
}
//print results
for(i = 0; i < A; i++)
{
for(j = 0; j < A; j++)
{
printf("%d\t", ans[i][j]);
}
printf("\n");
}
return 0;
}<file_sep>/c_cpp/c/node.c
#include<stdio.h>
#include<stdlib.h>
//NOTE-1 : this is a second way of creating a pointer and pass value by reference to insertNode function
struct node
{
int data;
struct node *next;
};
struct node* head;
struct node* newNode(int data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
// void insertNode(struct node** head) //NOTE-1
void insertNode(int data)
{
if(head == NULL)
{
head = newNode(data);
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
printf("Node Added Succesfully\n");
}
void printNode()
{
struct node* trav = head;
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
printf("%d\n", trav -> data);
while(trav -> next != NULL)
{
trav = trav -> next;
printf("%d\n", trav -> data);
}
}
}
void deleteNode(int data)
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
int i = 0;
if(trav -> next == NULL)
{
if(trav -> data == data)
{
free(trav);
i = 2;
}
}
else
{
while(trav -> next != NULL)
{
if(trav -> data == data)
{
temp -> next = trav -> next;
free(trav);
i = 1;
break;
//write delete code
}
temp = trav;
trav = trav -> next;
}
}
if(i == 0)
{
printf("Node with value : %d\t NOT FOUND\n", data );
}
else if(i == 1)
{
printf("Node with value : %d\t DELETED Succesfully\n", data );
}
else if(i == 2)
{
printf("Node with value : %d\t DELETED Succesfully. LIST is NULL now.\n", data );
}
}
}
void reverseList()
{
struct node* trav = head;
struct node* temp = head;
struct node* temp2 = head;
if(trav == NULL)
{
printf("List is NULL\n");
}
else
{
temp2 = trav -> next;
trav -> next = NULL;
while(trav != NULL)
{
temp =trav;
trav = temp2;
if(temp2 != NULL)
{
temp2 = temp2 -> next;
}
if(trav != NULL)
{
trav -> next = temp;
}
}
head = temp;
printf("List is REVERSED Succesfully\n");
}
}
void lengthList()
{
struct node* trav = head;
int length = 1;
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
length++;
}
}
if(length%2 == 0)
{
printf("Length of List is EVEN");
}
else
{
printf("Length of List is ODD");
}
printf("\n");
}
void printReverseList()
{
reverseList();
printNode();
reverseList();
}
void deleteSpecificNode(int data)
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
int i = 0, j = 0;
while(trav -> next != NULL)
{
if(j == data)
{
temp -> next = trav -> next;
free(trav);
break;
}
temp = trav;
trav = trav -> next;
j++;
}
printf("Node at position : %d\t DELETED Succesfully\n", data );
}
}
int main(int argc, char const *argv[])
{
// struct node* head = NULL; //NOTE-1
head = NULL;
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
insertNode(50);
int x = 1, temp = 0;
printf("***\tLinked List\t***\n");
while(1 == 1)
{
printf("--------------------------------\nEnter your choice.\n1)Print List\n2)Insert Node\n3)Delete Node\n4)Reverse List\n5)Length (ODD | EVEN)\n6)Print List in Reverse Order\n7)Delete specific node\n0)Exit\nYour choice: ");
scanf("%d", &x);
if(x == 0)
{
printf("Thank You!\n");
return 0;
}
else if (x == 1)
{
printNode();
}
else if (x == 2)
{
printf("Enter value for new node: ");
scanf("%d", &temp);
insertNode(temp);
}
else if (x == 3)
{
printf("Enter value of node: ");
scanf("%d", &temp);
deleteNode(temp);
}
else if (x == 4)
{
reverseList();
}
else if (x == 5)
{
lengthList();
}
else if (x == 6)
{
printReverseList();
}
else if (x == 7)
{
printf("Enter value of node: ");
scanf("%d", &temp);
deleteSpecificNode(temp);
}
else
{
printf("INVALID choice... Try Again...\n");
}
}
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Player Details(Array of objects)/src/Main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
String country;
String skill;
Integer n;
System.out.println("Enter the number of players");
n=Integer.parseInt(br.readLine());
Player[] players=new Player[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the player name");
name=br.readLine();
System.out.println("Enter the country name");
country=br.readLine();
System.out.println("Enter the skill");
skill=br.readLine();
players[i]=new Player(name, country, skill);
}
PlayerBO playerBO=new PlayerBO();
playerBO.displayAllPlayerDetails(players);
}
}
<file_sep>/Java/CTS_SFDC/workspace/HashSet 1/src/Main.java
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int p;
Scanner sc = new Scanner(System.in);
HashSet<String> players = new HashSet<>();
p = sc.nextInt();
sc.nextLine();
sc.close();
for(int i=0; i< p; i++ ) {
players.add(sc.nextLine());
}
System.out.print(players.size());
}
}
<file_sep>/Python/pythonWorkshop/a.py
# a = [1,2,3,4,5]
# b = 0
# for x in a:
# b += x
# print b
# def fib(a, b):
# if a == 1:
# print 1
# fib(a-1, b)
<file_sep>/c_cpp/c/day 5/zigzag.cpp
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
void zigzag(int a[] ,int n)
{
int flag=0;
for(int i=0;i<n-2;i++)
{
if(flag%2==0)
{
if(a[i]>a[i+1])
swap(&a[i],&a[i+1]);
}
else
{
if (a[i]<a[i+1])
swap(a[i],a[i+1]);
}
flag=flag+1;
}
}
main()
{
int arr[]={1,2,3,4,6};
zigzag(arr,5);
for(int i=0;i<5;i++)
{
cout<<arr[i];
}
}
<file_sep>/c_cpp/afterSummer/Questions/kthElementFromLastLinkedList.c
//kthElementFromLastLinkedList
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head, *trav, *temp;
struct Node *newNode(int data)
{
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNode(int data)
{
trav = head;
if(head == NULL)
head = newNode(data);
else
{
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void insertNode(int data, int after)
{
trav = head;
temp = trav -> next;
if(head == NULL)
printf("List is NULL.\n");
else
{
while(trav != NULL && trav -> data != after)
{
trav = trav -> next;
temp = temp -> next;
}
struct Node *a = newNode(data);
trav -> next = a;
a -> next = temp;
}
}
void removeNode(int data)
{
temp = head;
trav = temp -> next;
if(head == NULL)
printf("List is Empty.\n");
else
{
if(temp -> data == data)
{
head = trav;
printf("Node: %d\tREMOVED\n", trav -> data);
free(temp);
return;
}
while(trav != NULL)
{
if(trav -> data == data)
{
temp -> next = trav -> next;
printf("Node: %d\tREMOVED\n", trav -> data);
free(trav);
break;
}
temp = trav;
trav = trav -> next;
}
}
}
void printList()
{
trav = head;
if(head == NULL)
printf("List is Empty.\n");
else
{
printf("\nList:\t");
while(trav != NULL)
{
printf("%d\t", trav -> data);
trav = trav -> next;
}
printf("\n\n");
}
}
int kthElementFromLastLinkedList(struct Node *head, int k)
{
struct Node *trav = head;
struct Node *trav2 = head;
int i = 0;
for(i = 0; i < k; i++)
{
trav2 = trav2 -> next;
}
while(trav2 != NULL)
{
trav = trav -> next;
trav2 = trav2 -> next;
}
return trav -> data;
}
int main(int argc, char const *argv[])
{
insertNode(3);
insertNode(5);
insertNode(8);
insertNode(6);
// removeNode(3);
insertNode(3);
insertNode(4,3);
printList();
printf("Kth last element:\t%d\n", kthElementFromLastLinkedList(head, 2) );
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Collection-List(Prime)/src/Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int m, frequency = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<>();
System.out.println("Enter the number of matches");
m = sc.nextInt();
sc.nextLine();
System.out.println("Enter the runs scored by the team");
for(int i = 0; i< m; i++) {
scores.add(sc.nextInt());
}
sc.close();
// for(int score : scores) {
// if(score%2 == 1)
// frequency++;
// }
frequency = Collections.frequency(scores, new Main() {
@Override
public boolean equals(Object another) {
int x = (int) another;
if(x <= 2 && x >= 0)
return true;
for(int i = 2; i < x; i++) {
if (x%i == 0)
return false;
}
return true;
}
});
System.out.print("Number of prime scores : " + frequency);
}
}
<file_sep>/c_cpp/afterSummer/Questions/DP/checkInterleavedString.cpp
#include <iostream>
using namespace std;
int getMax(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int checkInterleavedString(string A, string B, string C)
{
int n = C.length();
int max1 = 0, max2 = 0, i = 0, j = 0, k = 0, temp = 0, t1 = 0, t2 = 0, t3 = 0;
while(i != n)
{
if(j == A.length() && k == B.length())
return false;
max1 = 0, max2 = 0, temp = i, t2 = j;
while(A[j] == C[temp])
{
max1++; temp++; j++;
}
t1 = temp; temp = i; t3 = k;
while(B[k] == C[temp])
{
max2++; temp++; k++;
}
if(max1 > max2)
{
i = t1;
if(k == t3)
k = t3 + 1;
else
k = t3;
}
else
{
i = temp;
if(j == t2)
j = t2 + 1;
else
j = t3;
}
}
return true;
}
int main(int argc, char const *argv[])
{
string s1 = "ABC";
string s2 = "DEF";
string s3 = "ADBECF";
cout<<checkInterleavedString(s1, s2, s3)<<endl;
return 0;
}<file_sep>/Python/pythonWorkshop/tushar files/project/config.py
import os
"""
pip install flask-sqlalchemy pymysql flask-script
install mysql using command line (linux) and .exe for windows
"""
DEBUG=True
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
<file_sep>/Java/CTS_SFDC/workspace/Team/src/Team.java
public class Team {
public String name;
public String coach;
public String location;
public String players;
public String captain;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCoach() {
return coach;
}
public void setCoach(String coach) {
this.coach = coach;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPlayers() {
return players;
}
public void setPlayers(String players) {
this.players = players;
}
public String getCaptain() {
return captain;
}
public void setCaptain(String captain) {
this.captain = captain;
}
public void displayTeamDetails() {
System.out.printf("Team Details\nTeam : %s\nCoach : %s\nLocation : %s\nPlayers : %s\nCaptain : %s\n",
getName(), getCoach(), getLocation(), getPlayers(), getCaptain());
}
}
<file_sep>/c_cpp/c/day 1/sqrt.cpp
#include<iostream>
using namespace std;
int flag=0;
int squareRoot(int low,int key,int high)
{
int mid;
while(low<=high){
mid=(low+high)/2;
if(mid*mid==key)
return mid;
if(mid*mid>key)
high=mid-1;
else low=mid+1;
}
flag=1;
return high;
}
int main()
{
int key,index;
cout<<"Enter the Num to find sqrt";
cin>>key;
index=squareRoot(1,key,key/2);
if(flag==1)
cout<<"lower bound square "<<index;
else cout<<"Perf square of "<<index;
}
<file_sep>/c_cpp/c/reverseList.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* head;
struct node* newNode(int data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void insertNode(int data)
{
if(head == NULL)
{
head = newNode(data);
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void printNode()
{
struct node* trav = head;
while(trav -> next != NULL)
{
printf("%d\n", trav -> data);
trav = trav -> next;
}
}
void reverseNode()
{
struct node* trav = head;
struct node* temp = head;
}
int main(int argc, char const *argv[])
{
// struct node* head = NULL; //NOTE-1
head = NULL;
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
insertNode(50);
insertNode(60);
printNode();
return 0;
}<file_sep>/c_cpp/c/testProg.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* head;
struct node* newNode(int data)
{
struct node* newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void insertNode(int data)
{
if(head == NULL)
{
head = newNode(data);
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
}
void removeNode(int data)
{
struct node* trav = head;
struct node* pTrav = trav;
while(trav != NULL)
{
if(trav -> data == data)
{
pTrav -> next = trav -> next;
free(trav);
printf("The node with data : %d Removed.\n", data);
return;
}
else
{
pTrav = trav;
trav = trav -> next;
}
}
}
void reverseNode()
{
struct node* trav = head;
struct node* pTrav = trav;
trav = pTrav -> next;
struct node* nTrav = trav -> next;
pTrav -> next = NULL;
while(pTrav -> next != NULL)
{
trav -> next = pTrav;
pTrav = trav;
trav = nTrav;
nTrav = nTrav -> next;
}
// head = trav;
// head -> next = pTrav;
}
void printNode()
{
struct node* trav = head;
while(trav != NULL)
{
printf("%d\n", trav -> data);
trav = trav -> next;
}
}
int ans = 0, c = 0, flag = 0;
int GetNode(struct node* head,int positionFromTail)
{
// This is a "method-only" submission.
// You only need to complete this method.
if(head==NULL) return 0;
if(flag==0) {
c=GetNode(head->next,positionFromTail);
if(flag == 1){
return ans;
}
if(c==positionFromTail) {
ans=head->data;
flag=1;
return ans;
}
printf("%d\t",c);
c++;
return c;
}
return ans;
}
int main(int argc, char const *argv[])
{
insertNode(1);
// insertNode(1);
// insertNode(4);
// insertNode(6);
// insertNode(8);
// insertNode(9);
// insertNode(0);
printNode();
// removeNode(30);
// reverseNode();
// printNode();
printf("\n%d",GetNode(head,0));
return 0;
}
<file_sep>/c_cpp/beforeSummer/prep_class/DP/fibonacci.c
#include <stdio.h>
int F[100] = {0};
int c = 0, s = 0;
int fib(int n)
{
c++;
if(n <= 1)
return n;
else
{
if(F[n] != 0)
{
return F[n];
}
F[n] = fib(n - 1) + fib(n - 2);
s++;
return F[n];
}
}
int main(int argc, char const *argv[])
{
int n = 20;
printf("%dth Fibonacci Series Number:\t%d\n", n, fib(n));
printf("Time Complexity:\t%d\nSpace Complexity:\t%d\n\n", c, s);
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Comparable - Display Team/src/Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
int i = 0, n;
String s;
boolean isExist = false;
String teamName;
String playerName;
Team team;
Scanner sc = new Scanner(System.in);
ArrayList<Team> teams = new ArrayList<>();
n = sc.nextInt();
sc.nextLine();
while(i < n) {
i++;
isExist = false;
s = sc.nextLine();
teamName = getTeamName(s);
playerName = getPlayerName(s);
for(Team t : teams) {
if(t.getName().equals(teamName)) {
team = t;
teams.remove(teams.indexOf(t));
team.addPlayer(playerName);
teams.add(team);
isExist = true;
break;
}
}
if(!isExist) {
team = new Team(teamName);
team.addPlayer(playerName);
teams.add(team);
}
}
sc.close();
Collections.sort(teams);
System.out.println("Teams and Players in ascending order");
for(Team t : teams) {
System.out.println(t.getName());
for(Player p : t.getPlayerList()) {
System.out.println("--" + p.getName());
}
}
}
private static String getTeamName(String s) {
StringTokenizer st = new StringTokenizer(s, "|");
return st.nextToken();
}
private static String getPlayerName(String s) {
StringTokenizer st = new StringTokenizer(s, "|");
st.nextToken();
return st.nextToken();
}
}
<file_sep>/c_cpp/c/fibonacci.c
#include<stdio.h>
void fib(int x, int y, int z)
{
if(y<z)
{
printf("%d\t", y);
fib(y,x+y,z);
}
}
int main()
{
fib(0, 1, 15);
}<file_sep>/Java/CSE406/JDBC/GetTablesFromDb.java
import java.sql.*;
class GetTablesFromDb{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mySqlDb","root","mkteq1mu");
DatabaseMetaData dbmd=con.getMetaData();
String table[] = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, null, table);
int x=1;
System.out.println("Tables:\n------------------\n");
while(rs.next())
System.out.println((x++) + ". " + rs.getString(3));
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Player-bowler,batsman Details/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
Long noOfMatches, noOfWickets, noOfRuns;
String name, teamName;
Scanner sc = new Scanner(System.in);
System.out.println("Enter player name");
name = sc.nextLine();
System.out.println("Enter team name");
teamName = sc.nextLine();
System.out.println("Enter number of matches");
noOfMatches = sc.nextLong();
sc.nextLine();
System.out.println("Menu\n1.Bowler details\n2.Batsman details\nEnter choice");
i = sc.nextInt();
sc.nextLine();
Player p;
if(i == 1) {
System.out.println("Enter number of wicktes taken");
noOfWickets = sc.nextLong();
p = new Bowler(name, teamName, noOfMatches, noOfWickets);
p.displayDetails();
} else if(i == 2) {
System.out.println("Enter number of runs scored");
noOfRuns = sc.nextLong();
p = new Batsman(name, teamName, noOfMatches, noOfRuns);
p.displayDetails();
}
sc.close();
}
}
<file_sep>/README.md
#Learn to Program
####
The Internet is filled with an ever-expanding number of courses, books and guides for programmers of all skill levels to improve their skills. Unfortunately, these resources are either hard to find or of low quality. Here is my efforts to learn to program.
<file_sep>/c_cpp/c/queue.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* head;
struct node* top;
struct node* newNode(int data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void enque(int data)
{
if(head == NULL)
{
head = newNode(data);
top = head;
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNode(data);
}
printf("Node Added Succesfully\n");
}
void deque()
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
temp = trav;
trav = trav -> next;
head = trav;
free(temp);
printf("POPPED Succesfully\n");
}
}
void printNode()
{
struct node* trav = head;
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
printf("%d\n", trav -> data);
while(trav -> next != NULL)
{
trav = trav -> next;
printf("%d\n", trav -> data);
}
}
}
int main()
{
head = NULL;
printNode();
enque(10);
enque(20);
enque(30);
enque(40);
deque();
deque();
enque(50);
deque();
enque(60);
printNode();
}<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/checkPangrams.cpp
#include <iostream>
using namespace std;
bool checkPangrams(string s)
{
// int a[26] = {0};
// for (int i = 0; i < s.length(); i++)
// a[s[i] - 'a'] += 1;
// for (int i = 0; i < 26; i++)
// if(a[i] == 0)
// return false;
// return true;
int hash = 0;
for (int i = 0; i < s[i] != '\0'; i++)
if (s[i] >= 'a' && s[i] <= 'z')
hash = hash | (1 << (s[i] - 'a'));
if(hash == 2^26 - 1)
return true;
return false;
}
int main(int argc, char const *argv[])
{
string s = "the quick brown fox jumps over the lazy dog";
(checkPangrams(s)) ? cout<<"True"<<endl : cout<<"False"<<endl;
return 0;
}<file_sep>/c_cpp/c/day 3/maxarea-histogram.cpp
#include <iostream>
using namespace std;
int maxarea_simple(int arr[], int n)
{
int maxArea = 0;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
int minHeight = min(arr[i], arr[j]);
for(int k=j+1;k<j;k++)
{
if (arr[k] < minHeight) minHeight = arr[k];
}
int area = minHeight*(j-i);
maxArea = max(area, maxArea);
}
}
return maxArea;
}
int main()
{
int arr[] = {2,1,5,6,2,3};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxarea_simple(arr, n);
}<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/alternatingCharacters.cpp
#include <iostream>
using namespace std;
int minDeleteChars(string s)
{
char temp;
int min = 0;
for (int i = 0; i < s[i] != '\0'; i++)
{
if(s[i] == temp)
min++;
temp = s[i];
}
return min;
}
int main(int argc, char const *argv[])
{
string s1 = "AAAA";
string s2 = "BBBBB";
string s3 = "ABABABAB";
string s4 = "BABABA";
string s5 = "AAABBB";
cout<<minDeleteChars(s1)<<endl;
cout<<minDeleteChars(s2)<<endl;
cout<<minDeleteChars(s3)<<endl;
cout<<minDeleteChars(s4)<<endl;
cout<<minDeleteChars(s5)<<endl;
return 0;
}<file_sep>/Java/CSE406/Locale & ResourceBundle/Locale0.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
import java.util.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
class Locale0 extends JFrame{
private JComboBox cbCountry;
private JLabel lbTime;
String[] countryNames = new String[160];;
Locale[] availableLocales;
public Locale0(){
availableLocales = Calendar.getAvailableLocales();
Container cp = getContentPane();
cp.setLayout(new GridLayout(10,2));
int i = 0;
for (Locale l : availableLocales) {
countryNames[i++] = l.getDisplayName();
}
add(new JLabel("Select Country: "));
cbCountry = new JComboBox(countryNames);
add(cbCountry);
add(new JLabel("Time: "));
lbTime = new JLabel();
add(lbTime);
cbCountry.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
try{
int selectedCountry = cbCountry.getSelectedIndex();
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(availableLocales[selectedCountry]);
lbTime.setText(String.valueOf(now.format(df)));
}catch(Exception ex){
System.out.println(ex);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Get Time");
setSize(200,300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Locale0();
}
});
}
}
<file_sep>/Java/CSE406/CA4/GUIEmployee.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.sql.*;
import java.util.*;
class GUIEmployee extends JFrame{
private JTextField tfId, tfName, tfSalary;
private JButton btnAdd, btnSave;
int avrg = 0;
LinkedList<Employee> employees = new LinkedList<Employee>();
public GUIEmployee(){
Container cp = getContentPane();
cp.setLayout(new GridLayout(5,2));
add(new JLabel("Id: "));
tfId = new JTextField(8);
add(tfId);
add(new JLabel("Name: "));
tfName = new JTextField(20);
add(tfName);
add(new JLabel("Salary: "));
tfSalary = new JTextField(5);
add(tfSalary);
btnAdd = new JButton("Add");
add(btnAdd);
btnSave = new JButton("Save");
add(btnSave);
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int id = Integer.parseInt(tfId.getText().trim());
String name = tfName.getText().trim();
int salary = Integer.parseInt(tfSalary.getText().trim());
employees.add(new Employee(id, name, salary));
avrg = (avrg + salary) / 2;
// Iterator itr = employees.iterator();
// if(itr.hasNext())
// avrg = ((Employee) itr.next()).getSalary();
// while(itr.hasNext()){
// Employee e = (Employee) itr.next();
// avrg = (avrg + ((Employee) itr.next()).getSalary()) / 2;
// }
System.out.println("Average Salary: " + avrg);
}
});
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Employee");
setSize(300,300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GUIEmployee();
}
});
}
}
class Employee {
public int id, salary;
public String name;
public Employee(int id, String name, int salary) {
this.id = id;
this.name= name;
this.salary = salary;
}
public int getSalary() {
return this.salary;
}
}
<file_sep>/c_cpp/c/day 2/find-rotation-in-array.cpp
#include <iostream>
using namespace std;
int findRotation(int arr[], int n)
{
int low = 0;
int high = n;
while (low < high)
{
int mid = (low + high)/2;
if (arr[mid] < arr[low])
high = mid;
else if (arr[mid] > arr[low])
low = mid + 1;
else if (low == mid)
return arr[low] > arr[high] ? high : low;
}
}
int main()
{
int arr[] = {12, 13, 17, 2, 4, 7, 9};
int n = sizeof(arr)/sizeof(arr[0]);
cout << findRotation(arr, n);
}<file_sep>/c_cpp/beforeSummer/prep_class/searching/binarySearch.c
#include <stdio.h>
int c = 0;
int binarySearch(int a[], int key, int n)
{
int i = 0, j = n - 1, m = 0, ans = -1;
while(i <= j)
{
m = (i + j) / 2;
if(a[m] == key)
{
ans = m;
break;
}
else if(key < a[m]) j = m - 1;
else i = m + 1;
c++;
}
return ans;
}
int main(int argc, char const *argv[])
{
int a[] = {1, 2, 4, 6, 9, 11};
int key = 9, n = 6;
printf("Complexity:\t%d\nElement %d is at position:\t%d\n", c, key, binarySearch(a, key, n - 1));
return 0;
}<file_sep>/c_cpp/c/student.c
#include<stdio.h>
// #define N;
struct student
{
int age;
char *name;
int roll;
char address[20];
};
int main(int argc, char const *argv[])
{
struct student s[3];
s[1].age = 10;
s[1].name = "RS";
printf("%d\n", s[1].age);
printf("%s\n", s[1].name);
return 0;
}<file_sep>/c_cpp/c/InOrderTreeUsingStack.c
#include<stdio.h>
#include<stdlib.h>
struct treeNode
{
int d;
struct treeNode* l;
struct treeNode* r;
};
/////////////////// Stack ///////////////////////
struct node
{
struct treeNode* data;
struct node *next;
};
struct node* head;
struct node* top;
struct node* headMin;
struct node* topMin;
struct node* newNodeStack(struct treeNode* data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void pushNode(struct treeNode* data)
{
if(top == NULL)
{
head = newNodeStack(data);
top = head;
}
else
{
struct node* trav = top;
trav -> next = newNodeStack(data);
top = trav -> next;
}
// if(topMin -> data > data)
// {
// pushMinNode(data);
// }
// printf("Node Added Succesfully\n");
}
void popNode()
{
if(head == NULL)
{
printf("List is NULL\n");
}
else
{
struct node* trav = head;
struct node* temp = head;
int i = 0;
while(trav -> next != NULL)
{
temp = trav;
trav = trav -> next;
}
if(temp -> next == NULL)
{
head =NULL;
}
temp -> next = NULL;
printf("%d\t", trav -> data -> d);
free(trav);
// printf("POPPED Succesfully\n");
}
}
///////////////////////////////////////////////////////
struct treeNode* root;
struct treeNode* newNode(int data)
{
struct treeNode *newN = (struct treeNode*) malloc(sizeof(struct treeNode));
newN -> d = data;
newN -> l = NULL;
newN -> r = NULL;
return newN;
}
void preTrav(struct treeNode* root)
{
if(root != NULL)
{
printf("%d\t", root -> d);
preTrav(root -> l);
preTrav(root -> r);
}
}
void postTrav(struct treeNode* root)
{
if(root != NULL)
{
postTrav(root -> l);
postTrav(root -> r);
printf("%d\t", root -> d);
}
}
void inTrav(struct treeNode* root)
{
if(root != NULL)
{
inTrav(root -> l);
printf("%d\t", root -> d);
inTrav(root -> r);
}
}
struct treeNode* insertNode(struct treeNode* root, int data)
{
if(root == NULL)
{
root = newNode(data);
}
else
{
if(data < (root -> d))
{
root -> l = insertNode(root -> l, data);
}
else
{
root -> r = insertNode(root -> r, data);
}
}
return root;
}
int c;
int count(struct treeNode* root)
{
if(root != NULL)
{
c++;
count(root -> l);
count(root -> r);
}
return c;
}
void InOrderUsingStack(struct treeNode* root)
{
if(root != NULL)
{
InOrderUsingStack(root -> r);
pushNode(root);
InOrderUsingStack(root -> l);
}
}
void PreOrderUsingStack(struct treeNode* root)
{
if(root != NULL)
{
PreOrderUsingStack(root -> r);
PreOrderUsingStack(root -> l);
pushNode(root);
}
}
void PreOrderUsingStackWithoutRecursion(struct treeNode* root)
{
if(root != NULL)
{
PreOrderUsingStack(root -> r);
PreOrderUsingStack(root -> l);
pushNode(root);
}
}
int main()
{
root = NULL;
// root = newNode(1);
// root -> l = newNode(2);
// root -> r = newNode(3);
// root -> l -> l = newNode(4);
// root -> l -> r = newNode(5);
// root -> r -> r = newNode(6);
// insertNode(root, 7);
// insertNode(root, 8);
// insertNode(root, 9);
// insertNode(root, 10);
// insertNode(root, 11);
// insertNode(root, 12);
// insertNode(root, 13);
// insertNode(root, 14);
root = insertNode(root, 5);
insertNode(root, 3);
insertNode(root, 7);
insertNode(root, 1);
insertNode(root, 4);
insertNode(root, 6);
insertNode(root, 9);
printf("\nPre-Order Trversal:\t");
preTrav(root);
printf("\nPost-Order Trversal:\t");
postTrav(root);
printf("\nIn-Order Trversal:\t");
inTrav(root);
count(root);
printf("\nCount:\t%d\n", c);
printf("\nPre-Order Trversal using STACK:\t");
PreOrderUsingStack(root);
while(head != NULL)
{
popNode();
}
printf("\nIn-Order Trversal using STACK:\t");
InOrderUsingStack(root);
while(head != NULL)
{
popNode();
}
}<file_sep>/c_cpp/beforeSummer/Paper 2/q1.c
#include <stdio.h>
int c = 0;
int func(int a[], int n)
{
int i = 0, j= 0, k = 0, cnt = 0;
for(i = 0; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
for(k = j + 1; k < n; k++)
{
c++;
if( ((a[i] + a[j]) > a[k]) && ((a[j] + a[k]) > a[i]) && ((a[i] + a[k]) > a[j])) cnt++;
}
}
}
return cnt;
}
int main(int argc, char const *argv[])
{
// int a[] = {4, 6, 3, 7};
int a[] = {10, 21, 22, 100, 101, 200, 300};
printf("%d\n", func(a, 7));
printf("Complexity:\t%d\n", c);
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/DP/Practice Questions/editDistanceOperations.cpp
#include <iostream>
using namespace std;
int getMin(int a, int b, int c)
{
if(a<b && a<c)
return a;
else if(b<a && b<c)
return b;
else
return c;
}
int editDistanceOperations(string str1, string str2, int m, int n)
{
int dp[m+1][n+1] = {0};
int min = 0;
for (int i = 0; i <= m; i++)
{
cout<<i<<"->\t";
for (int j = 0; j <= n; j++)
{
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(str1[i-1] == str2[j-1])
dp[i][j] = dp[i-1][j-1];
else
{
min = getMin(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]);
dp[i][j] = 1 + min;
if(dp[i][j] != dp[i-1][j-1])
{
// cout<<i<<"\t--\t"<<j<<"\t";
// if(min == dp[i][j-1])
// cout<<"Remove"<<endl;
// else if(min == dp[i-1][j])
// cout<<"Add"<<endl;
// else
// cout<<"Replace"<<endl;
}
}
cout<<dp[i][j]<<"\t";
}
cout<<endl;
}
int i=m;
int j=n;
while(i != 0)
{
while (j != 0)
{
if(dp[i][j] == dp[i-1][j-1])
{
i--;
j--;
}
else
{
cout<<"Replacelace-\t"<<str1[j]<<"\twith-\t"<<str2[i]<<endl;
i--;
j--;
}
}
}
return dp[m][n];
}
int main(int argc, char const *argv[])
{
string str1 = "SUNDAY";
string str2 = "SATURDAY";
cout<<editDistanceOperations(str1, str2, str1.length(), str2.length())<<endl;
return 0;
}<file_sep>/Python/pythonWorkshop/project/app.py
from app import app_api, db
from app.schema import Todo, User
from flask.ext.script import Manager
manager = Manager(app_api)
@manager.command
def createdb():
db.drop_all()
db.create_all()
@manager.command
def dropall():
db.drop_all()
@manager.shell
def make_shell_context():
return dict(app=app_api, db=db, Todo=Todo, User=User)
if __name__ == '__main__':
manager.run()
<file_sep>/Python/pythonWorkshop/tushar files/project/app/__init__.py
from flask import Flask
from schema import db
app_api = Flask(__name__)
app_api.config.from_object('config')
db.init_app(app_api)
from app import apis
<file_sep>/Java/CTS_SFDC/workspace/Validation 2 - Code Challenge/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s;
Scanner sc = new Scanner(System.in);
s = sc.nextLine();
sc.close();
if(UserMainCode.validateTeam(s)) {
System.out.print("Valid");
} else {
System.out.print("Invalid");
}
}
}
<file_sep>/Java/CSE406/DateTime API/que/Problems.java
import java.time.*;
import static java.time.temporal.ChronoUnit.*;
class Problems {
public static void main(String[] args) {
//Abe
LocalDate bDateAbe = LocalDate.of(1970, 9, 25);
LocalDate nowAbe = LocalDate.now();
System.out.println("Abe was " + bDateAbe.until(nowAbe, YEARS) + " when he died.");
System.out.println("Abe lived for " + bDateAbe.until(nowAbe, DAYS) + " days.");
System.out.println();
//Bernadict
LocalDate bDate = LocalDate.of(1984, 9, 24);
LocalDate nowBernadict = LocalDate.now();
System.out.println("Bennadict was born in a leap year: " + bDate.isLeapYear());
System.out.println("Days in the year he was born: " + bDate.lengthOfYear() /*( bDate.isLeapYear() ? 366 : 365) */);
System.out.println("Bernadict is " + bDate.until(nowBernadict, DECADES) + " decades old.");
LocalDate bDay21 = bDate.plusYears(21);
System.out.println("It was a " + bDay21.getDayOfWeek() + " on his 21th birthday.");
System.out.println();
//Travel time
LocalTime travelStartTime = LocalTime.of(8, 44);
LocalTime travelEndTime = LocalTime.of(14, 24);
System.out.println("Planned Travel Time: " + travelStartTime.until(travelEndTime, MINUTES) + " Minutes");
LocalTime travelArrivalTime = travelEndTime.plusMinutes(380);
System.out.println("Delayed arrival time: " + travelArrivalTime);
System.out.println();
//Miami
LocalDateTime flightTime = LocalDateTime.of(2014, 3, 25, 1, 30);
System.out.println("The flight arrival time in Miami: " + flightTime);
LocalDateTime flightDelayedTime = flightTime.plusHours(4).plusMinutes(27);
System.out.println("The flight delayed time in Miami: " + flightDelayedTime);
System.out.println();
//School
LocalDate startDateSchool = LocalDate.of(2014, 9, 9);
LocalDate endDateSchool = LocalDate.of(2015, 6, 25);
System.out.println("School starts: " + startDateSchool);
System.out.println("School ends: " + endDateSchool);
System.out.println("Number of Total days: " + startDateSchool.until(endDateSchool, DAYS));
int schoolDays = 0, i = 0;
while(startDateSchool.plusDays(i).isBefore(endDateSchool)) {
if(startDateSchool.plusDays(i).getDayOfWeek().toString() != "SATURDAY" && startDateSchool.plusDays(i).getDayOfWeek().toString() != "SUNDAY")
schoolDays++;
i++;
}
System.out.println("Number of school days: " + schoolDays);
System.out.println();
//Meeting time
LocalDateTime meetingTime = LocalDateTime.of(2014, 8, 5, 13, 30);
System.out.println("The meeting time is: " + meetingTime);
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/tree/heightTree.c
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree *root, *trav;
struct tree *newNode(int data)
{
struct tree *node = (struct tree *) malloc(sizeof(struct tree));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return node;
}
void insertNode(struct tree* head, int data)
{
if(root == NULL)
{
root = newNode(data);
return;
}
if(head -> data > data)
{
if(head -> left == NULL)
head -> left = newNode(data);
else
insertNode(head -> left, data);
}
else
{
if(head -> right == NULL)
head -> right = newNode(data);
else
insertNode(head -> right, data);
}
}
int getMax(int x, int y)
{
return (x > y) ? x : y;
}
int heightTree(struct tree *head)
{
if(head != NULL)
{
return 1 + getMax( heightTree(head -> left), heightTree(head -> right) );
}
else
return 0;
}
int main(int argc, char const *argv[])
{
insertNode(root, 12);
insertNode(root, 10);
insertNode(root, 30);
insertNode(root, 25);
insertNode(root, 40);
insertNode(root, 45);
insertNode(root, 41);
insertNode(root, 49);
insertNode(root, 8);
printf("No. of Nodes:\t%d\n", heightTree(root));
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/Graph/isBipartite.cpp
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#define MAX 100
using namespace std;
bool static visited[MAX]={false};
int callCheckBipartite(std::vector<std::vector<int> > g, int color[], int n)
{
visited[n] = true;
for (std::vector<int>::iterator iter = g[n].begin(); iter != g[n].end(); iter++)
{
if(visited[*iter] && color[n] == color[*iter])
return 0;
if(visited[*iter] == false)
{
color[*iter] = (color[n] ? 0 : 1);
if(callCheckBipartite(g, color, *iter) == 0)
return 0;
}
}
return 1;
}
int isBiPartite(std::vector<std::vector<int> > g, int n)
{
memset(visited, false, sizeof(bool)*MAX);
int *color = new int(n);
memset(color, -1, sizeof(int)*MAX);
for (int i = 0; i < n; i++)
{
if(visited[i] == false)
if(callCheckBipartite(g, color, i) == 0)
return 0;
}
return 1;
}
int main(int argc, char const *argv[])
{
int n=10;
int color[MAX]={-1};
std::vector<std::vector<int> > graph;
graph.resize(10);
graph[1].push_back(2);
graph[1].push_back(3);
graph[3].push_back(6);
graph[2].push_back(4);
graph[2].push_back(5);
graph[5].push_back(7);
graph[5].push_back(8);
graph[5].push_back(9);
cout<<endl;
isBiPartite(graph, 1) ? cout<<"True" : cout<<"False";
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Venue Details/src/VenueBO.java
public class VenueBO {
void displayVenueDetails(Venue venue)
{
System.out.printf("Venue Details\n%s,%s", venue.getName(), venue.getCity());
}
}
<file_sep>/Java/CTS_SFDC/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/JSP_Code_Challenge_2/org/apache/jsp/index_jsp.java
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.47
* Generated at: 2017-03-02 11:25:20 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n");
out.write("<title>Insert title here</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("<h3>Winning Team Details</h3>\n");
out.write("<table id='skill_details'>\n");
out.write("<tr>\n");
out.write("<th>Player Name</th>\n");
out.write("<th>Skill</th>\n");
out.write("<th>Country</th>\n");
out.write("</tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Wicket Keeping Batting </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> New Zealand </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Wicket Keeping Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> New Zealand </td></tr>\n");
out.write("<tr><td>Jas<NAME>umrah </td><td>All Rounder </td><td> England </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> South African </td></tr>\n");
out.write("<tr><td>Unmukt Chand </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td>Shreyas Gopal </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West Indian </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME>ya </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Wicket Keeping Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> New Zealand </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Wicket Keeping Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td>Albie Morkel </td><td>All Rounder </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> England </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> New Zealand </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> South Africa </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td>Travis Head </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> New Zealand </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> West India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> Australia </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> New Zealand </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>All Rounder </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Bowling </td><td> India </td></tr>\n");
out.write("<tr><td><NAME> </td><td>Batting </td><td> India </td></tr>\n");
out.write("</table>\n");
out.write("</body>\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Validate Player details/src/Main.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String dob = request.getParameter("dob");
String runs = request.getParameter("runs");
String average = request.getParameter("average");
int count=0;
String regex = "^[a-zA-Z]+$";
String output = "<!DOCTYPE html><html><body><div id='error'>";
if(!name.matches(regex)){
output+="Invaild Name<br>";
count++;
}
String ePattern = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if(!email.matches(ePattern)){
output+="Invaild Email<br>";
count++;
}
if(!dob.matches("\\d{2}/\\d{2}/\\d{4}")){
output+="Invaild DOB<br>";
count++;
}
if(!runs.matches("[-+]?\\d*\\.?\\d+")){
output+="Invaild runs<br>";
count++;
}
if(!average.matches("^\\d+\\.\\d{2}$")){
output+="Invaild Average<br>";
count++;
}
output+="</div></body></html>";
if(count==0){
out.print("<b>Inserted Successfully !!!</b>");
}
else{
out.println(output);
out.print("<br><a id=\"home\" href=\"index.html\"><<Home</a>");
}
}
}
<file_sep>/c_cpp/c/day 4/circQue.cpp
#include<iostream>
using namespace std;
int que[10];
int front=-1,rear=-1;
int count=0;
void ins(int x){
if(count==10)
cout<<"Overflow";
else{
if(front==-1 && rear==-1)
{
rear++;
que[rear]=x;
front=rear;
}
else{
rear=(rear+1)%10;
que[rear]=x;
}
count++;
}
}
int del()
{
if(count==0)
cout<<"Underflow";
else{
int x=que[front];
front=(front+1)%10;
count--;
return x;
}
}
int main()
{
ins(10);
ins(20);
ins(20);
ins(30);
ins(40);
del();
del();
ins(10);
ins(20);
ins(20);
ins(30);
ins(40);
for(int i=0;i<10;i++)
cout<<del()<<endl;
}
<file_sep>/Java/CTS_SFDC/workspace/Player Login and Profile page/src/Index.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Index
*/
@WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Index() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String outData = "";
String result = request.getParameter("result");
outData += "<html>"
+ "<head><title>Login</title></head>"
+ "<body>"
+ "<h2>Login</h2>";
if(result != null && result.equals("errorMsg")) {
outData += "<br><br><div id='errorMsg'>Invalid username or password</div>";
} else if(result != null && result.equals("logout")) {
outData += "<br><br><div id='logoutMsg'><h2>Logged out Successfully!!!</h2></div>";
}
outData += "<form method='get' action='LoginServlet'>"
+ "<br>Username<input type='text' name='username' />"
+ "<br>Password<input type='text' name='<PASSWORD>' />"
+ "<input type='submit' value='Login' name='login' />"
+ "</form>"
+ "</body>"
+ "</html>";
response.getWriter().print(outData);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/q7.c
#include <stdio.h>
int c = 0, cnt = 0;
int func(int a[], int k, int i, int sum, int n)
{
if(i == n)
{
if(sum == k) cnt++;
}
else
{
func(a, k, i + 1, sum + a[i], n);
func(a, k, i + 1, sum, n);
}
c++;
return 0;
}
int main(int argc, char const *argv[])
{
int a[] = {2, 4, 1, 3};
func(a, 4, 0, 0, 4);
printf("Number of Pairs:\t%d\nComplexity:\t%d\n", cnt, c);
return 0;
}
<file_sep>/Java/CSE406/Generics & Collections/List/TestArrayList.java
import java.util.*;
class TestArrayList{
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(10);
al.add(20);
al.add(40);
al.add(2, 30);
// System.out.println(al);
ArrayList<Integer> al2 = new ArrayList<>(al);
al2.addAll(al);
al2.remove(3);
System.out.println(al2.subList(0,3));
// System.out.println(al2.get(al2.indexOf(40)));
// System.out.println(al2.get(al2.lastIndexOf(30)));
// ListIterator<Integer> li = al2.listIterator();
// while(li.hasNext()){
// System.out.print(li.next() + "\t");
// }
// ListIterator<Integer> li = al2.listIterator(al2.size());
// while(li.hasPrevious()){
// System.out.print(li.previous() + "\t");
// }
}
}
<file_sep>/Java/CTS_SFDC/workspace/Set - Player List Index Builder (COPY)/src/Index.java
class Index implements Comparable<Index>{
char ch;
int count;
Index(){}
Index(char ch, int count)
{setCh(ch);
setCount(count);
}
void setCh(char ch)
{this.ch=ch;
}
void setCount(int count)
{this.count=count;}
char getCh(){return ch;}
int getCount(){return count;}
@Override
public int compareTo(Index o) {
if(this.ch > o.ch)
return 1;
else if (this.ch < o.ch)
return -1;
else return 0;
}
}<file_sep>/Java/CTS_SFDC/workspace/Display Batsmans Details/src/SkillDAO.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SkillDAO {
public Skill getSkillById(int id) throws ClassNotFoundException, SQLException {
Connection con = DBConnection.getConnection();
Statement statement = con.createStatement();
String sql = "select id,name from skill where id=" + id;
ResultSet result = statement.executeQuery(sql);
result.next();
return new Skill(result.getInt("id"), result.getString("name"));
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/Test/test5.c
#include <stdio.h>
void getNum(int a[], int n)
{
}
int main(int argc, char const *argv[])
{
char a[][2] = {"56", "9", "4767", "109987"};
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/sqrt.cpp
#include <iostream>
using namespace std;
int sqrt(int n)
{
int i = 0, j = n/2, mid = 0, ans = -1;
while(i <= j)
{
mid = (i + j) / 2;
if(mid*mid == n)
{
return mid;
}
else if(mid*mid < n) i = mid + 1;
else j = mid - 1;
}
return -1;
}
int main(int argc, char const *argv[])
{
cout<<sqrt(25)<<endl;
return 0;
}<file_sep>/c_cpp/c/day 5/leaderelement.cpp
#include<iostream>
using namespace std;
main()
{
int max=a[5];
int a[]={1,2,3,0,6,7};
for(int i=5;i>0;i--)
{
if(a[i]>max)
max=a[i];
cout<<a[i];
}
}
<file_sep>/Java/CTS_SFDC/workspace/Thread – Match Summary to Title Case/src/TitleCaseThread.java
public class TitleCaseThread implements Runnable {
String summary;
String modifiedSummary;
public TitleCaseThread(String summary) {
super();
this.summary = summary;
}
public String getModifiedSummary() {
return modifiedSummary;
}
@Override
public void run() {
modifiedSummary = toTitleCase(summary);
}
private String toTitleCase(String summary) {
String s = "";
boolean flag = true;
for(char c : summary.toCharArray()) {
if(flag) {
s += String.valueOf(c).toUpperCase();
flag = false;
} else {
s += String.valueOf(c).toLowerCase();
}
if(c == ' ') {
flag = true;
}
}
return s;
}
}
<file_sep>/c_cpp/beforeSummer/Paper 2/q3.c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head;
struct Node *newNode(int data)
{
struct Node *node = (struct Node *) malloc(sizeof(struct Node));
node -> data = data;
node -> next = NULL;
return node;
}
void insertNode(int data)
{
struct Node *trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
struct Node *node = newNode(data);
trav -> next = node;
}
void printNode(struct Node *head)
{
struct Node *trav = head;
while(trav != NULL)
{
printf("%d\n", trav -> data);
trav = trav -> next;
}
}
struct Node *removeNodes(struct Node *head, int x)
{
struct Node *temp = head;
struct Node *trav = temp -> next, *h;
if(head == NULL)
return head;
else
{
while(trav != NULL)
{
if(trav -> data > x)
{
h = trav;
trav = trav -> next;
temp -> next = trav;
free(h);
}
else
{
h = temp;
temp = trav;
trav = trav -> next;
}
}
if(temp -> data > x)
{
h -> next = NULL;
free(temp);
}
}
return head;
}
int main(int argc, char const *argv[])
{
head = newNode(5);
insertNode(2);
insertNode(9);
insertNode(8);
insertNode(1);
insertNode(6);
insertNode(7);
removeNodes(head, 5);
printNode(head);
return 0;
}<file_sep>/c_cpp/afterSummer/Test/prog2.c
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
node *left;
node *right;
};
struct node* root;
struct node *newNode(int data)
{
struct node* nNode = (struct node*) malloc(sizeof(struct node*));
nNode -> data = data;
nNode -> left = NULL;
nNode -> right = NULL;
return nNode;
}
int getMax(int a, int b, int c)
{
if(a > b && a > c)
{
return a;
}
else if(b > a && b > c)
{
return b;
}
else if(c > a && c > b)
{
return c;
}
}
int getDiameter(struct node* root)
{
if(root == NULL)
{
return 1;
}
else
{
return getMax(getDiameter(root -> left), getDiameter(root -> right), 1 + getDiameter(root -> left) + getDiameter(root -> right));
}
}
int main(int argc, char const *argv[])
{
// printf("%d\n", (newNode(5) -> data));
root = newNode(0);
root -> left = newNode(2);
root -> left -> left = newNode(4);
root -> left -> right = newNode(5);
root -> left -> left -> left = newNode(7);
root -> left -> left -> left -> left = newNode(0);
printf("%d\n", getDiameter(root));
return 0;
}<file_sep>/c_cpp/afterSummer/Questions/Tree/levelOrderTraversal.cpp
##include <iostream>
using namespace std;
typedef struct node
{
int info;
node *left;
node *right;
}tnode;
tnode *createNode(int info, tnode* left = NULL, tnode* right = NULL)
{
tnode* node = new tnode();
node -> info = info;
node -> left = NULL;
node -> right = NULL;
return node;
}
void levelOrderTraversal(tnode* root)
{
}
int main(int argc, char const *argv[]) {
tnode *root;
root = createNode(1);
root -> left = createNode(2);
root -> right = createNode(3);
root -> left -> left = createNode(4);
root -> left -> right = createNode(5);
root -> left -> right -> left = createNode(6);
root -> left -> right -> right = createNode(7);
root -> left -> right -> right = createNode(9);
levelOrderTraversal(root);
return 0;
}
<file_sep>/Java/CTS_SFDC/workspace/Deprecated Annotation/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int base, power;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base value");
base = sc.nextInt();
sc.nextLine();
System.out.println("Enter the power value");
power = sc.nextInt();
sc.close();
Calc c = new Calc();
System.out.printf("Exponential : %d", c.exponential(base, power));
}
}
<file_sep>/Java/CTS_SFDC/workspace/Delivery Class/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Delivery d = new Delivery();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the over");
d.over = sc.nextLong();
sc.nextLine();
System.out.println("Enter the ball");
d.ball = sc.nextLong();
sc.nextLine();
System.out.println("Enter the runs");
d.runs = sc.nextLong();
sc.nextLine();
System.out.println("Enter the batsman name");
d.batsman = sc.nextLine();
System.out.println("Enter the bowler name");
d.bowler = sc.nextLine();
System.out.println("Enter the nonStriker name");
d.nonStriker = sc.nextLine();
sc.close();
d.displayDeliveryDetails();
}
}
<file_sep>/Java/CSE406/Design Patterns/Builder/BuildDemo.java
public class BuildDemo{
public static void main(String[] args) {
MyName n1 = new MyName.NestMyName("Umang").build();
System.out.println(n1);
MyName n2 = new MyName.NestMyName("Umang").lName("Patel").build();
System.out.println(n2);
}
}
<file_sep>/c_cpp/c/reverseStringRecursion.c
#include<stdio.h>
#include<string.h>
char temp;
void reverse(int x, int y, char z[])
{
if(y>x)
{
temp = z[x];
z[x] = z[y];
z[y] = temp;
reverse(x+1,y-1,z);
}
}
int main()
{
char a[] = "um<NAME>lklllllllllllllllllllllllllllllghghfghfdrtyhfhjhghj";
reverse(0, strlen(a)-1, a);
printf("%s\n", a);
}<file_sep>/Java/CTS_SFDC/workspace/IO - Simple File Write/src/Main.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String playerName, teamName, noOfMatches;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the player");
playerName = sc.nextLine();
System.out.println("Enter the team name");
teamName = sc.nextLine();
System.out.println("Enter the number of matches played");
noOfMatches = sc.nextLine();
sc.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("player.csv"));
bw.write(playerName + "," + teamName + "," + noOfMatches);
bw.close();
}
}
<file_sep>/Java/CTS_SFDC/workspace/HashMap - Scores to Bin/src/Histogram.java
import java.util.HashMap;
public class Histogram {
private HashMap<Integer,Integer> bins;
public Histogram() {
bins = new HashMap<>();
bins.put(10, 0);
bins.put(20, 0);
bins.put(30, 0);
bins.put(40, 0);
}
public void addScore(Integer i) {
if(i>0 && i <=10) {
bins.put(10, bins.get(10) + 1);
} else if(i>10 && i <=20) {
bins.put(20, bins.get(20) + 1);
} else if(i>20 && i <=30) {
bins.put(30, bins.get(30) + 1);
} else if(i>30 && i <=40) {
bins.put(40, bins.get(40) + 1);
}
}
public void displayHistogram() {
System.out.printf("Histogram\n10 : %s\n20 : %s\n30 : %s\n40 : %s",
getStars(bins.get(10)), getStars(bins.get(20)), getStars(bins.get(30)), getStars(bins.get(40)));
}
private String getStars(int i) {
String s = "";
while(i>0) {
s += "*";
i--;
}
return s;
}
}
<file_sep>/c_cpp/c/day 4/Binary String.cpp
#include<iostream>
using namespace std;
string que[100];
int front=-1,rear=-1;
void ins(string x){
if(rear==100)
cout<<"Overflow";
else{
if(front==-1 && rear==-1)
{
rear++;
que[rear]=x;
front=rear;
}
else{
rear++;
que[rear]=x;
}
}
}
string del()
{
if(front==-1 || front ==rear+1)
cout<<"Underflow";
else{
string x=que[front];
front++;
return x;
}
}
int main()
{
string s;
int n;
cout<<"Enter value";
cin>>n;
ins("1");
for(int i=1;i<=n;i++)
{
s=del();
cout<<s<<endl;
ins(s+"0");
ins(s+"1");
}
}
<file_sep>/Java/CTS_SFDC/workspace/Hashmap IV/src/Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i = 0, n;
String className;
int id, marks;
Scanner sc = new Scanner(System.in);
HashMap<Integer, String> classList = new HashMap<>();
HashMap<Integer, Integer> marksList = new HashMap<>();
n = sc.nextInt();
sc.nextLine();
while(i < n) {
id = sc.nextInt();
sc.nextLine();
className = sc.nextLine();
marks = sc.nextInt();
classList.put(id, className);
marksList.put(id, marks);
i++;
}
sc.close();
marksList = UserMainCode.increaseMarks(classList, marksList);
for(Map.Entry<Integer, Integer> m : marksList.entrySet()) {
System.out.printf("%d\n%d\n", m.getKey(), m.getValue());
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Servlet-JDBC -Store the Team Details/src/TeamBO.java
import java.sql.SQLException;
public class TeamBO {
public void createCity(City city)throws ClassNotFoundException,SQLException
{
TeamDAO teamins=new TeamDAO();
teamins.createCity(city);
}
public Boolean createTeam(Team team)throws ClassNotFoundException,SQLException
{
TeamDAO teamins=new TeamDAO();
return teamins.createTeam(team);
}
public int getPlayerIdByPlayerName(String name)throws ClassNotFoundException,SQLException
{
TeamDAO teamins=new TeamDAO();
return teamins.getPlayerIdByPlayerName(name);
}
public int getCityIdByCityName(String name)throws ClassNotFoundException,SQLException
{
TeamDAO teamins=new TeamDAO();
return teamins.getCityIdByCityName(name);
}
}
<file_sep>/c_cpp/c/day 3/next-greater-elem-stack.cpp
#include <iostream>
#include<stdio.h>
using namespace std;
struct stack
{
int a[100];
int top;
} s;
void init_stack()
{
s.top = -1;
}
void pause()
{
char ch;
cin >> ch;
}
void push(int item)
{
if (s.top == 99)
{
printf("Overflow");
pause();
}
else
{
s.top++;
s.a[s.top] = item;
}
}
int peek()
{
if (s.top == -1)
{
printf("Underflow");
pause();
}
else
{
return s.a[s.top];
}
}
void pop()
{
if (s.top == -1)
{
printf("Underflow");
pause();
}
else
{
s.top--;
}
}
void nge(int a[], int n)
{
int indx = 1;
push(a[0]);
while (indx < n)
{
while (s.top != -1 && peek() <= a[indx])
{
printf("%d -> %d\n", peek(), a[indx]);
pop();
}
push(a[indx]);
indx++;
}
}
int main()
{
int arr[] = {13, 7, 6, 12, 15};
int n = sizeof(arr)/sizeof(arr[0]);
init_stack();
nge(arr, n);
}
<file_sep>/Java/CTS_SFDC/workspace/User Defined Annotation/src/Arithmetic.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Arithmetic {
String str() default "Arithmetic";
}
<file_sep>/c_cpp/afterSummer/Questions/checkArrayDigitPalindrome.c
//check if digit Array is Palindrome
#include <stdio.h>
bool checkArrayDigitPalindrome(int a[], int len)
{
int i = 0;
for (i = 0; i < (len); i++)
{
printf("%d\t", a[i]);
// if(a[i] != a[len - i])
// return false;
}
return true;
}
int main(int argc, char const *argv[])
{
int len = 5;
int a[len] = {1, 3, 2, 3, 1};
printf("\n\n\n\n%d\n", checkArrayDigitPalindrome(a, len));
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Game Details By Venue/src/gameDetail/GameBO.java
package gameDetail;
public class GameBO {
}
<file_sep>/c_cpp/beforeSummer/prep_class/heap/heap.c
#include <stdio.h>
void heapify(int arr[], int n, int i)
{
int l, r, small, temp;
l = 2 * i;
r = l + 1;
small = i;
if(l <= n && arr[l] < arr[i])
small = l;
if(r <= n && arr[r] < arr[small])
small = r;
if(small != i)
{
temp = arr[i];
arr[i] = arr[small];
arr[small] = temp;
heapify(arr, n, l);
}
}
void buildHeap(int arr[], int n)
{
int i = 0;
for(i = (n/2); i > 0; i /= 2)
{
heapify(arr, n, i);
}
}
int main(int argc, char const *argv[])
{
int a[] = {10, 12, 8, 2, 5, 6};
int n = 6;
printf("Array:\t");
for (int i = 0; i < n; i++)
printf("%d\t", a[i]);
buildHeap(a, 6);
printf("\n\nSorted Array:\t");
for (int i = 0; i < n; i++)
printf("%d\t", a[i]);
return 0;
}<file_sep>/c_cpp/afterSummer/Amazon Hiring Challenge/q1.cpp
// C++ program to read an integer from STDIN and output it to STDOUT
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include<queue>
using namespace std;
typedef struct tree{
int data;
tree *left;
tree *right;
}tNode;
tNode* createNode(int data)
{
tNode* node = new tNode();
node -> data = data;
node ->left = NULL;
node -> right = NULL;
return node;
}
tNode* createTree(tNode* root, int d, int a[], int n)
{
std::queue<int> q;
int t =0;
for(int i=0; i<n; i++)
{
if(pow(2,t)-1 == i)
{
q.push(0);
t++;
}
q.push(a[i]);
}
while(!q.empty())
{
cout<<q.front()<<endl;
q.pop();
}
return NULL;
}
int main() {
// Declare the variable
int d, n, x, y, z;
string s[7];
// Read the variable from STDIN
// cin >> d;
d=3;
int aN = pow(2,d+1)-1;
int a[aN] = {2, 7, 5, 1, 6, -1, 9, -1, -1, 8, 11, -1, -1, 4, -1};
// for(int i=0; i<aN; i++)
// cin >> a[i];
// cin>>n;
n = 7;
// for(int i=0; i<n; i++)
// getline (cin, s[i]);
//create a tree;
tNode *root = NULL;
createTree(root, d, a, aN);
// Output the variable to STDOUT
cout << endl << "OUTPUT";
return 0;
}
<file_sep>/c_cpp/afterSummer/Questions/DP/low-highEffort.cpp
#include <iostream>
using namespace std;
int getMax(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int maxTasks(int L[], int H[], int n)
{
int prev = 0, max = 0, temp = 0;
for (int i = 0; i < n; i++)
{
temp = max;
max += getMax(L[i], H[i] - prev);
prev = max - temp;
}
return max;
}
int main(int argc, char const *argv[])
{
int L[] = {1, 5, 4, 5, 3};
int H[] = {3, 20, 8, 12, 6};
cout<<maxTasks(L, H, sizeof(L)/sizeof(L[0]))<<endl;
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/XML generation/src/Main.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Main {
public static void main(String[] args) throws JAXBException, FileNotFoundException {
String name, artist, duration;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the song name");
name = sc.nextLine();
System.out.println("Enter the artist");
artist = sc.nextLine();
System.out.println("Enter the duration");
duration = sc.nextLine();
sc.close();
Song s = new Song(name, artist, duration);
JAXBContext jaxbContext = JAXBContext.newInstance(Song.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(s, new FileOutputStream("song.xml"));
}
}
<file_sep>/Java/CTS_SFDC/workspace/Innings Details/src/Innings.java
public class Innings {
private
String battingTeam;
Long runs;
public Innings(String battingTeam, Long runs) {
this.battingTeam = battingTeam;
this.runs = runs;
}
public String getBattingTeam() {
return battingTeam;
}
public void setBattingTeam(String battingTeam) {
this.battingTeam = battingTeam;
}
public Long getRuns() {
return runs;
}
public void setRuns(Long runs) {
this.runs = runs;
}
public String toString()
{
return String.format("%-20s %-20s",getBattingTeam(),getRuns());
}
}
<file_sep>/c_cpp/beforeSummer/prep_class/q5.c
#include <stdio.h>
int fib(int n)
{
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
int main(int argc, char const *argv[])
{
printf("Fib:\t%d\n", fib(8));
return 0;
}<file_sep>/Java/CTS_SFDC/workspace/Player Login and Profile page/src/script.sql
drop table if exists player;
create table player(
player_id int(11) not null AUTO_INCREMENT,
name varchar(100) not null,
username varchar(100) not null,
password varchar(100) not null,
country varchar(100) not null,
skill varchar(100) not null,
team varchar(100) not null,
PRIMARY KEY (player_id));
insert into player(player_id,name,username,password,country,skill,team) values (1,'<NAME>','zaheer','zaheer','India','Bowling','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (2,'<NAME>','mayank','mayank','India','Batting','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (3,'<NAME>','khaleel','khaleel','India','Bowling','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (4,'<NAME>','mohammed','mohammed','India','Bowling','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (5,'<NAME>','karun','karun','India','Batting','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (6,'<NAME>','jayant','jayant','India','Bowling','Delhi Daredevils');
insert into player(player_id,name,username,password,country,skill,team) values (7,'<NAME>','carlos','carlos','West India','All-Rounder','Delhi Daredevils');
<file_sep>/Java/CTS_SFDC/workspace/Hashmap V/src/Main.java
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
int i = 0, n;
String id;
int theory, lab;
Scanner sc = new Scanner(System.in);
HashMap<String, Integer> theoryList = new HashMap<>();
HashMap<String, Integer> labList = new HashMap<>();
TreeMap<String, String> gradeList = new TreeMap<>();
n = sc.nextInt();
sc.nextLine();
while(i < n) {
id = sc.nextLine();
theory = sc.nextInt();
sc.nextLine();
lab = sc.nextInt();
if(!(i==n-1))
sc.nextLine();
theoryList.put(id, theory);
labList.put(id, lab);
i++;
}
sc.close();
gradeList = UserMainCode.calculateGrades(labList, theoryList);
for(Entry<String, String> m : gradeList.entrySet()) {
System.out.printf("%s\n%s\n", m.getKey(), m.getValue());
}
}
}
<file_sep>/Java/CSE406/CA4/Employees0.java
import java.sql.*;
import java.util.*;
class Employees0{
public static void main(String args[]){
List<Employee> employees = new LinkedList<Employee>();
employees.add(new Employee(1, "A", 1000));
employees.add(new Employee(2, "B", 2000));
employees.add(new Employee(3, "C", 3000));
int avrg = 0;
Iterator itr = employees.iterator();
if(itr.hasNext())
avrg = ((Employee) itr.next()).getSalary();
while(itr.hasNext()){
Employee e = (Employee) itr.next();
avrg = (avrg + ((Employee) itr.next()).getSalary()) / 2;
}
System.out.println("Average Salary: " + avrg);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB","root","root");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into salary values(" + avrg + ");");
stmt.executeBatch();
con.commit();
con.close();
System.out.println("Average Salary saved to database ");
}catch(Exception e){
System.out.println(e);
}
}
}
<file_sep>/Java/CTS_SFDC/workspace/Player Feedback Form/src/Feedback.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Feedback
*/
@WebServlet("/Feedback")
public class Feedback extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Feedback() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String bowling = request.getParameter("bowling");
String batting = request.getParameter("batting");
String fielding = request.getParameter("fielding");
String attitude = request.getParameter("attitude");
String rating = request.getParameter("rating");
String comments = request.getParameter("comments");
String outData = "<html><head><title>Player Feedback Form</title></head><body><h2>Feedback of player ";
outData += name + "</h2><table id='feedback'><tbody>";
outData += "<tr><td>Bowling</td><td>" + bowling + "</td></tr>";
outData += "<tr><td>Batting</td><td>" + batting + "</td></tr>";
outData += "<tr><td>Fielding</td><td>" + fielding + "</td></tr>";
outData += "<tr><td>Rating</td><td>" + rating + "</td></tr>";
outData += "<tr><td>Attitude</td><td>" + attitude + "</td></tr>";
outData += "<tr><td>Comments</td><td>" + comments + "</td></tr>";
outData += "</tbody></table></body></html>";
PrintWriter out = response.getWriter();
out.print(outData);
}
}
<file_sep>/Java/CTS_SFDC/workspace/Comparable - Display Team/src/Player.java
public class Player implements Comparable<Player> {
String name;
public Player(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Player o) {
return this.getName().compareTo(o.getName());
}
}
<file_sep>/Java/CTS_SFDC/workspace/Match Details II/src/MatchBO.java
public class MatchBO {
void displayAllMatchDetails(Match[] matchList) {
System.out.printf("Match Details\n%-35s %-30s %-15s %s\n", "Team 1", "Team 2", "Date", "Venue");
for(Match m : matchList) {
System.out.println(m);
}
}
void displaySpecificMatchDetails(Match[] matchList, String date) {
System.out.printf("Match Details\n%-35s %-30s %-15s %s\n", "Team 1", "Team 2", "Date", "Venue");
for(Match m : matchList) {
if(date.equals(m.getDate())) {
System.out.println(m);
}
}
}
}
<file_sep>/c_cpp/c/levelwiseTraversalTree.c
//with complexity O(n)
#include<stdio.h>
#include<stdlib.h>
struct treeNode
{
int d;
struct treeNode* l;
struct treeNode* r;
};
/////////////////////// Queue //////////////////////////////////////////////////
struct node
{
struct treeNode* data;
struct node *next;
};
struct node* head;
struct node* top;
struct node* newNodeQueue(struct treeNode* data)
{
struct node *newN = (struct node*) malloc(sizeof(struct node));
newN -> data = data;
newN -> next = NULL;
return newN;
}
void enque(struct treeNode* data)
{
if(head == NULL)
{
head = newNodeQueue(data);
top = head;
}
else
{
struct node* trav = head;
while(trav -> next != NULL)
{
trav = trav -> next;
}
trav -> next = newNodeQueue(data);
}
// printf("Node Added Succesfully\n");
}
struct treeNode* deque()
{
if(head == NULL)
{
// printf("List is NULL\n");
return NULL;
}
else
{
struct node* trav = head;
struct treeNode* temp = trav -> data;
if(head -> next == NULL)
{
head = NULL;
top = NULL;
}
else
{
head = head -> next;
}
free(trav);
// printf("POPPED Succesfully\n");
return temp;
}
}
////////////////////////////////////////////////////////////////////////////////////////
struct treeNode* root;
struct treeNode* newNode(int data)
{
struct treeNode *newN = (struct treeNode*) malloc(sizeof(struct treeNode));
newN -> d = data;
newN -> l = NULL;
newN -> r = NULL;
return newN;
}
void preTrav(struct treeNode* root)
{
if(root != NULL)
{
printf("%d\t", root -> d);
preTrav(root -> l);
preTrav(root -> r);
}
}
void postTrav(struct treeNode* root)
{
if(root != NULL)
{
postTrav(root -> l);
postTrav(root -> r);
printf("%d\t", root -> d);
}
}
void inTrav(struct treeNode* root)
{
if(root != NULL)
{
inTrav(root -> l);
printf("%d\t", root -> d);
inTrav(root -> r);
}
}
struct treeNode* insertNode(struct treeNode* root, int data)
{
if(root == NULL)
{
root = newNode(data);
}
else
{
if(root -> l == NULL)
{
root -> l = insertNode(root -> l, data);
}
else
{
root -> r = insertNode(root -> r, data);
}
}
return root;
}
int count = 0;
void levelTrav()
{
count++;
struct treeNode* temp = deque();
if(temp != NULL)
{
// enque(trav);
printf("%d\t",temp -> d);
if(temp -> l != NULL) enque(temp -> l);
if(temp -> r != NULL) enque(temp -> r);
levelTrav();
}
}
int main()
{
root = NULL;
root = newNode(1);
root -> l = newNode(2);
root -> r = newNode(3);
root -> l -> l = newNode(4);
root -> l -> r = newNode(5);
root -> r -> r = newNode(6);
// insertNode(root, 7);
// insertNode(root, 8);
// insertNode(root, 9);
// insertNode(root, 10);
// insertNode(root, 11);
// insertNode(root, 12);
// insertNode(root, 13);
// insertNode(root, 14);
printf("\nPre-Order Trversal:\t");
preTrav(root);
printf("\nPost-Order Trversal:\t");
postTrav(root);
printf("\nIn-Order Trversal:\t");
inTrav(root);
printf("\n\nLevel Wise Trversal:\t");
enque(root);
levelTrav();
printf("Complexity: O(%d)\n", count);
} | d32a3d8d44aa8eacb3c8b466b82c07d274fbeb9f | [
"SQL",
"HTML",
"JavaScript",
"Markdown",
"INI",
"Java",
"Python",
"C",
"C++"
] | 254 | Java | umng/Learn-to-Program | 9891558dcc1bcecf6468b1668e9cab8bf2d707d0 | 5c6071f3d166673dc90f0ec017ae63cded083b24 |
refs/heads/master | <repo_name>Adondriel/HumbleBundleGameListGrabber<file_sep>/HumbleGamesListGrabber.js
function appendGames(){
$.each($(".game-name h4"), function(key, value){
list = localStorage.getItem("list");
list = list + "\n" + value.title;
localStorage.setItem("list", list);
if(key === $(".game-name h4").length-1){
$("div.js-jump-to-page.jump-to-page")[$("div.js-jump-to-page.jump-to-page").length - 1].click();
}
});
};
function doGamesList(){
localStorage.setItem("list", "");
while($("i.hb.hb-chevron-right").length !==0){
appendGames();
}
appendGames();
console.info(localStorage.getItem("list"));
};
doGamesList();
<file_sep>/README.md
# HumbleBundleGameListGrabber
This script will grab the names of all your available games in your humble bundle key library page, and print the list to the console.
Use this script while on this page: https://www.humblebundle.com/home/keys
This will automatically change the page and then append the next games, it is almost instant after running the script.
This script uses the page's ordering/sorting, so before running this script select the sort order you want, and whether or not to "hide redeemed keys"
Always start this script on the first page of keys.
| 782934f67cd9b0492a5f0d8bbbba8c7b87d103c8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Adondriel/HumbleBundleGameListGrabber | 960a7ca355dfce8b44c72aa6d7725ce1bc4b8b13 | 80b7c21fcaa6ab019feb837a1c964763d17e143c |
refs/heads/master | <repo_name>pete-restall/Cluck2Sesame<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdDisable.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Mock_VoltageRegulator.h"
#include "Mock_PwmTimer.h"
#include "Mock_LcdInternals.h"
#include "Platform/Lcd.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
void onBeforeTest(void)
{
lcdInitialise();
lcdEnable();
}
void onAfterTest(void)
{
}
void test_lcdDisable_called_expectVoltageRegulatorIsDisabled(void)
{
voltageRegulatorDisable_Expect();
lcdDisable();
}
void test_lcdDisable_calledMoreTimesThanEnabled_expectVoltageRegulatorIsNotDisabledMoreTimesThanEnabled(void)
{
voltageRegulatorDisable_Expect();
lcdDisable();
lcdDisable();
}
void test_lcdDisable_called_expectPwmTimerIsDisabled(void)
{
pwmTimerDisable_Expect();
lcdDisable();
}
void test_lcdDisable_calledMoreTimesThanEnabled_expectPwmTimerIsNotDisabledMoreTimesThanEnabled(void)
{
pwmTimerDisable_Expect();
lcdDisable();
lcdDisable();
}
void test_lcdDisable_calledMoreTimesThanEnable_expectEnableCounterDoesNotGetOutOfSync(void)
{
lcdDisable();
lcdDisable();
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdConfigure_Expect();
lcdEnable();
}
// TODO: DISABLING THE LCD SHOULD TURN OFF THE DISPLAY IF THE VOLTAGE REGULATOR IS STILL ENABLED...
//
// TODO: DISABLING WHEN THE LCD IS BUSY (IE. WRITING COMMAND OR WAITING FOR COMMAND TO FINISH EXECUTING OR THE BIG 64ms WAIT DURING CONFIGURATION) - THE LCD SHOULD WAIT UNTIL NOT BUSY BEFORE TURNING OFF THE VOLTAGE REGULATOR...
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorEnable2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
TEST_FILE("Platform/VoltageRegulatorFixture.c")
const struct Event eventEmptyArgs = { };
void test_voltageRegulatorEnable_calledOnce_expectVoltageRegulatorEnabledIsPublishedWhenMcuRailHasStabilised(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
static const struct VoltageRegulatorEnabled emptyArgs = { };
eventPublish_Expect(VOLTAGE_REGULATOR_ENABLED, &emptyArgs);
callScheduleHandlerAndForget();
}
void test_voltageRegulatorEnable_calledTwice_expectNoNewScheduleIsAdded(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
requestedSchedule = (struct NearSchedule *) 0;
voltageRegulatorEnable();
TEST_ASSERT_NULL(requestedSchedule);
}
void test_voltageRegulatorEnable_calledAfterVoltageRailHasStabilised_expectNoNewScheduleIsAdded(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
requestedSchedule = (struct NearSchedule *) 0;
voltageRegulatorEnable();
TEST_ASSERT_NULL(requestedSchedule);
}
void test_voltageRegulatorEnable_calledAfterVoltageRailHasStabilised_expectOnlyOneEventIsPublished(void)
{
static const struct VoltageRegulatorEnabled emptyArgs = { };
eventPublish_Expect(VOLTAGE_REGULATOR_ENABLED, &emptyArgs);
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
}
void test_voltageRegulatorEnable_calledAfterFullyEnabled_expectNoNewScheduleIsAdded(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
voltageRegulatorEnable();
TEST_ASSERT_NULL(requestedSchedule);
}
<file_sep>/src/firmware/tests/Platform/Temperature/TestTemperature.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include <unity.h>
#include "Platform/Temperature.h"
#include "Mock_PeriodicMonitor.h"
#include "../../Fixture.h"
#include "../../NvmSettingsFixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Temperature.c")
#define ROUNDED(t, x) ((t) ((x) < 0 ? (x) - 0.5 : (x) + 0.5))
#define CELSIUS(x) ROUNDED(int16_t, (x) * 10)
#define CELSIUS_HIGH(x) ROUNDED(uint8_t, ((x) - 25) * 10)
#define COEFFICIENT(x) ROUNDED(uint16_t, -(x) * 65536)
static void publishParametersAndAwaitTemperatureSampled(const struct MonitoredParametersSampled *monitoredParametersSampledEventArgs);
static void scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
const char *scenario,
int16_t expectedCelsius,
uint16_t sample);
static void scenario_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
const char *scenario,
int16_t expectedCelsius,
uint16_t sample,
uint16_t coefficient,
uint8_t celsiusHigh,
uint16_t adcHigh);
static void stubNvmSettingsForCalibratedTemperature(uint16_t coefficient, uint8_t celsiusHigh, uint16_t adcHigh);
static struct Event onMonitoredParametersSampledEvent;
static const struct EventSubscription *onMonitoredParametersSampled;
static const struct TemperatureSampled *temperatureSampledEventArgs;
const struct Event eventEmptyArgs = { };
void onBeforeTest(void)
{
onMonitoredParametersSampled = (const struct EventSubscription *) 0;
temperatureSampledEventArgs = (const struct TemperatureSampled *) 0;
}
void onAfterTest(void)
{
}
void test_temperatureInitialise_called_expectSubscriptionToMonitoredParametersSampled(void)
{
temperatureInitialise();
TEST_ASSERT_NOT_NULL(onMonitoredParametersSampled);
}
void test_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithSameSample(void)
{
temperatureInitialise();
struct MonitoredParametersSampled monitoredParametersSampledEventArgs =
{
.temperature = anyWord()
};
publishParametersAndAwaitTemperatureSampled(&monitoredParametersSampledEventArgs);
TEST_ASSERT_EQUAL_UINT16(monitoredParametersSampledEventArgs.temperature, temperatureSampledEventArgs->sample);
}
static void publishParametersAndAwaitTemperatureSampled(const struct MonitoredParametersSampled *monitoredParametersSampledEventArgs)
{
onMonitoredParametersSampledEvent.args = monitoredParametersSampledEventArgs;
onMonitoredParametersSampled->handler(&onMonitoredParametersSampledEvent);
TEST_ASSERT_NOT_NULL_MESSAGE(temperatureSampledEventArgs, "No eventPublish(TemperatureSampled)");
}
void test_onMonitoredParametersSampled_eventAfterInitialise_expectTemperatureSampledIsPublishedWithDeltaSecondsEqualToZero(void)
{
temperatureInitialise();
struct MonitoredParametersSampled monitoredParametersSampledEventArgs =
{
.timestamp = anyByte()
};
publishParametersAndAwaitTemperatureSampled(&monitoredParametersSampledEventArgs);
TEST_ASSERT_EQUAL_UINT8(0, temperatureSampledEventArgs->deltaSeconds);
}
void test_onMonitoredParametersSampled_eventAfterPreviousEvent_expectTemperatureSampledIsPublishedWithDeltaSecondsEqualToDifference(void)
{
temperatureInitialise();
struct MonitoredParametersSampled firstMonitoredParametersSampledEventArgs =
{
.timestamp = anyByte()
};
publishParametersAndAwaitTemperatureSampled(&firstMonitoredParametersSampledEventArgs);
struct MonitoredParametersSampled secondMonitoredParametersSampledEventArgs =
{
.timestamp = anyByteExcept(firstMonitoredParametersSampledEventArgs.timestamp)
};
publishParametersAndAwaitTemperatureSampled(&secondMonitoredParametersSampledEventArgs);
TEST_ASSERT_EQUAL_UINT8(
secondMonitoredParametersSampledEventArgs.timestamp - firstMonitoredParametersSampledEventArgs.timestamp,
temperatureSampledEventArgs->deltaSeconds);
}
void test_onMonitoredParametersSampled_eventAfterInitialise_expectTemperatureSampledIsPublishedWithDeltaCelsiusEqualToZero(void)
{
stubNvmSettingsForCalibratedTemperature(COEFFICIENT(-0.65), CELSIUS_HIGH(43.2), 0x0100);
temperatureInitialise();
struct MonitoredParametersSampled monitoredParametersSampledEventArgs =
{
.temperature = anyWord()
};
publishParametersAndAwaitTemperatureSampled(&monitoredParametersSampledEventArgs);
TEST_ASSERT_EQUAL_INT16(0, temperatureSampledEventArgs->deltaCelsius);
}
void test_onMonitoredParametersSampled_eventAfterPreviousEvent_expectTemperatureSampledIsPublishedWithDeltaCelsiusEqualToDifference(void)
{
stubNvmSettingsForCalibratedTemperature(COEFFICIENT(-0.65), CELSIUS_HIGH(43.2), 0x0100);
temperatureInitialise();
struct MonitoredParametersSampled firstMonitoredParametersSampledEventArgs =
{
.temperature = anyWord()
};
publishParametersAndAwaitTemperatureSampled(&firstMonitoredParametersSampledEventArgs);
int16_t firstCelsius = temperatureSampledEventArgs->currentCelsius;
struct MonitoredParametersSampled secondMonitoredParametersSampledEventArgs =
{
.temperature = anyWordExcept(firstMonitoredParametersSampledEventArgs.timestamp)
};
publishParametersAndAwaitTemperatureSampled(&secondMonitoredParametersSampledEventArgs);
int16_t secondCelsius = temperatureSampledEventArgs->currentCelsius;
TEST_ASSERT_EQUAL_INT16(secondCelsius - firstCelsius, temperatureSampledEventArgs->deltaCelsius);
}
void test_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(void)
{
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"1", CELSIUS(21.9), 0x0296);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"2", CELSIUS(38.4), 0x0281);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"3", CELSIUS(30.5), 0x028b);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"4", CELSIUS(0.7), 0x02b1);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"5", CELSIUS(-0.1), 0x02b2);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"6", CELSIUS(-261.7), 0x03ff);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"7", CELSIUS(39.2), 0x0280);
scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
"8", CELSIUS(542.0), 0x0000);
}
static void scenario_onMonitoredParametersSampled_eventWhenPrototypeCalibration_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
const char *scenario,
int16_t expectedCelsius,
uint16_t sample)
{
char subScenario[8] = {0};
strncpy(subScenario, scenario, 5);
char *subScenarioIndex = subScenario + strlen(subScenario);
*(subScenarioIndex++) = '.';
sample <<= 3;
*subScenarioIndex = '0';
scenario_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
subScenario, expectedCelsius, sample, COEFFICIENT(-0.7857142857142857), CELSIUS_HIGH(38.4), 0x0281);
if (sample > 3)
{
*subScenarioIndex = '1';
scenario_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
subScenario, expectedCelsius, sample - 3, COEFFICIENT(-0.7857142857142857), CELSIUS_HIGH(38.4), 0x0281);
}
*subScenarioIndex = '2';
scenario_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
subScenario, expectedCelsius, sample + 3, COEFFICIENT(-0.7857142857142857), CELSIUS_HIGH(38.4), 0x0281);
}
static void scenario_onMonitoredParametersSampled_event_expectTemperatureSampledIsPublishedWithCalculatedCurrentCelsius(
const char *scenario,
int16_t expectedCelsius,
uint16_t sample,
uint16_t coefficient,
uint8_t celsiusHigh,
uint16_t adcHigh)
{
stubNvmSettingsForCalibratedTemperature(coefficient, celsiusHigh, adcHigh);
temperatureInitialise();
struct MonitoredParametersSampled monitoredParametersSampledEventArgs =
{
.temperature = sample
};
publishParametersAndAwaitTemperatureSampled(&monitoredParametersSampledEventArgs);
TEST_ASSERT_EQUAL_INT16_MESSAGE(expectedCelsius, temperatureSampledEventArgs->currentCelsius, scenario);
}
static void stubNvmSettingsForCalibratedTemperature(uint16_t coefficient, uint8_t celsiusHigh, uint16_t adcHigh)
{
union NvmSettings withCalibratedTemperature =
{
.platform =
{
.temperature =
{
.temperatureHighCelsius = celsiusHigh,
.temperatureHighAdc = adcHigh,
.temperatureCoefficient = coefficient
}
}
};
stubNvmSettings(&withCalibratedTemperature);
}
void eventSubscribe(const struct EventSubscription *subscription)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == MONITORED_PARAMETERS_SAMPLED)
{
onMonitoredParametersSampled = subscription;
onMonitoredParametersSampledEvent.type = subscription->type;
onMonitoredParametersSampledEvent.state = subscription->state;
onMonitoredParametersSampledEvent.args = (void *) 0;
}
else
{
TEST_FAIL_MESSAGE("Unknown subscription type");
}
}
void eventPublish(EventType type, const void *args)
{
TEST_ASSERT_NOT_NULL_MESSAGE(args, "Null args");
if (type == TEMPERATURE_SAMPLED)
temperatureSampledEventArgs = (const struct TemperatureSampled *) args;
}
<file_sep>/README.md
# Cluck<sup>2</sup>Sesame - Yet Another Chicken Coop Door Opener (Revision II)
## What is it ?
It opens and closes the door of my wife's chicken coop based on Sunrise and
Sunset times so that she doesn't have to. This is a refinement of the
[Cluck<sup>2</sup>Sesame](https://github.com/pete-restall/Cluck2Sesame-Prototype/)
project, building on lessons learned from the original attempt. Notably:
- The parts are not based on what I have lying around, but rather on parts
selected for the job or known to do the job. This has also simplified the
design somewhat - more pins on the PIC mean the shift register is no longer
required, for example. The newer PIC is smaller, integrates more
peripherals and comes with more flash; the original project ran out of
flash before all features could be implemented.
- The shortcomings in the end-of-travel detection, namely measuring motor
current for stall torque, hastened battery depletion. A rotary-encoder
based approach will be used instead, which will hopefully lengthen battery
life.
- A solar charger will be included as replacing the battery, fairly regularly
as it turned out, meant unscrewing the enclosure.
- The motor will be a 6V model rather than a 12V model and run directly from
the battery rather than off an SMPS. No SMPS means a smaller BOM and no
power wasted by the high motor currents. This should extend battery life
even further, at the expense of varying speed. But that's not an issue.
- The PCB will be made in China, and the board house charges the same price
regardless of whether the PCB is the size of the enclosure or the size of
the LCD module. This means that the aluminium backplate can be replaced
with a PCB, providing more flexibility and space for layout and mounting
while reducing the cost and time of the build.
That said, some of the parts from the original have been incorporated into
the newer design since they are known to work and are already stocked in my
parts bins.
## Why 'Cluck<sup>2</sup>Sesame' ?
Because 'Cluck Cluck Sesame' is obviously what the chickens would say if
they needed to open a door.
## The Hardware and Firmware
The hardware and firmware are all mine. The board is based around a
[PIC16F15356](doc/datasheets/mcu/PIC16F15356.pdf). It's a beefier evolution
of what was used last time that has allowed considerable simplification of the
board through more integration and a higher pin count.
## Pictures
None yet. But there will be.
## Build
[](https://github.com/pete-restall/Cluck2Sesame/actions/workflows/cluck2sesame.yml)
<file_sep>/src/firmware/tests/unity_config.h
#ifndef __CLUCK2SESAME_TESTS_UNITY_CONFIG_H
#define __CLUCK2SESAME_TESTS_UNITY_CONFIG_H
#define UNITY_EXCLUDE_SETJMP_H
#define UNITY_OUTPUT_START() unityBeforeRunHook()
#define UNITY_OUTPUT_COMPLETE() unityBreakpointHook()
extern void unityBeforeRunHook(void);
extern void unityBreakpointHook(void);
#endif
<file_sep>/src/firmware/src/Platform/PeriodicMonitor.c
#include <xc.h>
#include <stdint.h>
#define __PERIODICMONITOR_EXPOSE_INTERNALS
#include "Event.h"
#include "Clock.h"
#include "Adc.h"
#include "PeriodicMonitor.h"
static void onTimeChanged(const struct Event *event);
static uint8_t nextTimestamp;
void periodicMonitorInitialise(void)
{
static const struct EventSubscription onTimeChangedSubscription =
{
.type = TIME_CHANGED,
.handler = &onTimeChanged,
.state = (void *) 0
};
eventSubscribe(&onTimeChangedSubscription);
nextTimestamp = 0;
}
static void onTimeChanged(const struct Event *event)
{
const struct TimeChanged *args = (const struct TimeChanged *) event->args;
if ((args->now->minute & 0x03) != 1)
return;
static struct MonitoredParametersSampled eventArgs;
periodicMonitorSampleNow(&eventArgs);
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
}
void periodicMonitorSampleNow(struct MonitoredParametersSampled *eventArgs)
{
if (!eventArgs)
return;
eventArgs->timestamp = nextTimestamp;
eventArgs->flags.isVddRegulated = (PORTBbits.RB0 == 0 ? 0 : 1);
nextTimestamp += 240;
PMD0bits.FVRMD = 0;
FVRCON = _FVRCON_ADFVR1_MASK | _FVRCON_FVREN_MASK | _FVRCON_TSRNG_MASK | _FVRCON_TSEN_MASK;
struct AdcSample sample =
{
.channel = ADC_CHANNEL_ADCFVR,
.count = 8,
.flags =
{
.vrefIsFvr = 0,
.acquisitionTimeMultiple = 11
}
};
adcSample(&sample);
eventArgs->fvr = sample.result;
sample.channel = ADC_CHANNEL_TEMPERATURE,
sample.flags.vrefIsFvr = 1;
sample.flags.acquisitionTimeMultiple = 0;
adcSample(&sample);
eventArgs->temperature = sample.result;
PMD0bits.FVRMD = 1;
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorDisable.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorDisable_calledAfterEnable_expectPwmTimerIsDisabled(void)
{
motorEnable();
motorDisable();
TEST_ASSERT_EQUAL_UINT8(1, pwmTimerDisableCalls);
}
void test_motorDisable_calledBeforeEnable_expectPwmTimerIsNotDisabled(void)
{
motorDisable();
TEST_ASSERT_EQUAL_UINT8(0, pwmTimerDisableCalls);
}
void test_motorDisable_calledAfterEnable_expectVoltageRegulatorIsDisabled(void)
{
motorEnable();
motorDisable();
TEST_ASSERT_EQUAL_UINT8(1, voltageRegulatorDisableCalls);
}
void test_motorDisable_calledBeforeEnable_expectVoltageRegulatorIsNotDisabled(void)
{
motorDisable();
TEST_ASSERT_EQUAL_UINT8(0, voltageRegulatorDisableCalls);
}
void test_motorDisable_calledMoreTimesThanEnable_expectVoltageRegulatorIsOnlyDisabledNumberOfTimesEnabled(void)
{
motorEnable();
motorDisable();
motorDisable();
TEST_ASSERT_EQUAL_UINT8(1, voltageRegulatorDisableCalls);
}
void test_motorDisable_called_expectMotorDisabledEventIsPublishedBeforeVoltageRegulatorIsDisabled(void)
{
mockOnVoltageRegulatorDisabled();
stubVoltageRegulatorDisableToPublishEvent();
motorEnable();
motorDisable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorDisabledCalls, "MTR DIS calls");
TEST_ASSERT_TRUE_MESSAGE(
onMotorDisabledSequence < onVoltageRegulatorDisabledSequence,
"Sequence");
}
void test_motorDisable_calledWhenStillEnabled_expectMotorDisabledEventIsNotPublished(void)
{
motorEnable();
motorEnable();
motorDisable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorDisabledCalls);
}
void test_motorDisable_calledMoreTimesThanEnabled_expectEventsDoNotGetOutOfSync(void)
{
motorEnable();
motorDisable();
motorDisable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, onMotorDisabledCalls);
motorEnable();
motorDisable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(2, onMotorDisabledCalls);
}
<file_sep>/src/firmware/src/SunEvents/SunEventsInitialise.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/Event.h"
#include "../Platform/Clock.h"
#include "../Platform/NvmSettings.h"
#include "../Location.h"
#include "SunEvents.h"
static void onLocationChanged(const struct Event *event);
static void onDateChanged(const struct Event *event);
void sunEventsInitialise(void)
{
static const struct EventSubscription onLocationChangedSubscription =
{
.type = LOCATION_CHANGED,
.handler = &onLocationChanged,
.state = (void *) 0
};
eventSubscribe(&onLocationChangedSubscription);
static const struct EventSubscription onDateChangedSubscription =
{
.type = DATE_CHANGED,
.handler = &onDateChanged,
.state = (void *) 0
};
eventSubscribe(&onDateChangedSubscription);
sunEventsCalculationContext.inputs.latitudeOffset = nvmSettings.application.location.latitudeOffset;
sunEventsCalculationContext.inputs.longitudeOffset = nvmSettings.application.location.longitudeOffset;
}
static void onLocationChanged(const struct Event *event)
{
const struct Location *args = ((const struct LocationChanged *) event->args)->location;
sunEventsCalculationContext.inputs.latitudeOffset = args->latitudeOffset;
sunEventsCalculationContext.inputs.longitudeOffset = args->longitudeOffset;
sunEventsCalculate();
}
static void onDateChanged(const struct Event *event)
{
sunEventsCalculationContext.inputs.dayOfYear = ((const struct DateChanged *) event->args)->today->dayOfYear;
sunEventsCalculate();
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorInitialise_called_expectMotorPortCPinsAreAllOutputs(void)
{
static const uint8_t usedPins =
_TRISC_TRISC2_MASK |
_TRISC_TRISC3_MASK |
_TRISC_TRISC6_MASK |
_TRISC_TRISC7_MASK;
TRISC = anyByteWithMaskSet(usedPins);
uint8_t originalTrisc = TRISC;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisc & ~usedPins, TRISC);
}
void test_motorInitialise_called_expectMotorCurrentSensePinIsOutput(void)
{
TRISB = anyByteWithMaskSet(_TRISB_TRISB1_MASK);
uint8_t originalTrisb = TRISB;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB1_MASK, TRISB);
}
void test_motorInitialise_called_expectMotorPortCPinsAreAllDigital(void)
{
static const uint8_t usedPins =
_ANSELC_ANSC2_MASK |
_ANSELC_ANSC3_MASK |
_ANSELC_ANSC6_MASK |
_ANSELC_ANSC7_MASK;
ANSELC = anyByteWithMaskSet(usedPins);
uint8_t originalAnselc = ANSELC;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnselc & ~usedPins, ANSELC);
}
void test_motorInitialise_called_expectMotorCurrentSensePinIsAnalogue(void)
{
ANSELB = anyByteWithMaskClear(_ANSELB_ANSB1_MASK);
uint8_t originalAnselb = ANSELB;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnselb | _ANSELB_ANSB1_MASK, ANSELB);
}
void test_motorInitialise_called_expectMotorPortCPinsAreAllLow(void)
{
static const uint8_t usedPins =
_LATC_LATC2_MASK |
_LATC_LATC3_MASK |
_LATC_LATC6_MASK |
_LATC_LATC7_MASK;
LATC = anyByteWithMaskSet(usedPins);
uint8_t originalLatc = LATC;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLatc & ~usedPins, LATC);
}
void test_motorInitialise_called_expectMotorCurrentSensePinIsLow(void)
{
LATB = anyByteWithMaskSet(_LATB_LATB1_MASK);
uint8_t originalLATB = LATB;
motorInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLATB & ~_LATB_LATB1_MASK, LATB);
}
<file_sep>/src/firmware/tests/Platform/Buttons/TestButtonsInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/Buttons.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Buttons.c")
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_buttonsInitialise_called_expectInterruptOnChangeModuleIsEnabled(void)
{
PMD0 = anyByteWithMaskSet(_PMD0_IOCMD_MASK);
uint8_t originalPmd0 = PMD0;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd0 & ~_PMD0_IOCMD_MASK, PMD0);
}
void test_buttonsInitialise_called_expectAnalogueBehaviourIsDisabledForRa0AndRa1(void)
{
ANSELA = anyByteWithMaskSet(_ANSELA_ANSA0_MASK | _ANSELA_ANSA1_MASK);
uint8_t originalAnsela = ANSELA;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnsela & ~(_ANSELA_ANSA0_MASK | _ANSELA_ANSA1_MASK), ANSELA);
}
void test_buttonsInitialise_called_expectInterruptOnChangeFlagIsCleared(void)
{
IOCAF = anyByteWithMaskSet(_IOCAF_IOCAF0_MASK | _IOCAF_IOCAF1_MASK);
PIR0 = anyByteWithMaskSet(_PIR0_IOCIF_MASK);
uint8_t originalPir0 = PIR0;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPir0 & ~_PIR0_IOCIF_MASK, PIR0);
}
void test_buttonsInitialise_called_expectInterruptOnChangeIsEnabled(void)
{
PIE0 = anyByteWithMaskClear(_PIE0_IOCIE_MASK);
uint8_t originalPie0 = PIE0;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie0 | _PIE0_IOCIE_MASK, PIE0);
}
void test_buttonsInitialise_called_expectRa0AndRa1InterruptOnNegativeEdges(void)
{
IOCAN = anyByteWithMaskClear(_IOCAN_IOCAN0_MASK | _IOCAN_IOCAN1_MASK);
uint8_t originalIocan = IOCAN;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalIocan | (_IOCAN_IOCAN0_MASK | _IOCAN_IOCAN1_MASK), IOCAN);
}
void test_buttonsInitialise_called_expectRa0AndRa1InterruptOnPositiveEdges(void)
{
IOCAP = anyByteWithMaskClear(_IOCAP_IOCAP0_MASK | _IOCAP_IOCAP1_MASK);
uint8_t originalIocap = IOCAP;
buttonsInitialise();
TEST_ASSERT_EQUAL_UINT8(originalIocap | (_IOCAP_IOCAP0_MASK | _IOCAP_IOCAP1_MASK), IOCAP);
}
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerAdd1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("NearSchedulerFixture.c")
void test_nearSchedulerAdd_calledWhenNoPendingSchedules_expectNcoIsEnabled(void)
{
NCO1CON = anyByteWithMaskClear(_NCO1CON_N1EN_MASK);
uint8_t originalNco1con = NCO1CON;
nearSchedulerAdd(&dummySchedule);
TEST_ASSERT_TRUE(NCO1CONbits.N1EN);
}
void test_nearSchedulerAdd_calledWhenNoPendingSchedules_expectNcoAccumulatorIsCleared(void)
{
NCO1ACCU = anyByte();
NCO1ACCH = anyByte();
NCO1ACCL = anyByte();
nearSchedulerAdd(&dummySchedule);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCU, "NCO1ACCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCH, "NCO1ACCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCL, "NCO1ACCL");
}
void test_nearSchedulerAdd_calledWhenPendingSchedules_expectNcoAccumulatorIsNotCleared(void)
{
nearSchedulerAdd(&dummySchedule);
NCO1ACCU = anyByte();
uint8_t originalNco1accu = NCO1ACCU;
NCO1ACCH = anyByte();
uint8_t originalNco1acch = NCO1ACCH;
NCO1ACCL = anyByte();
uint8_t originalNco1accl = NCO1ACCL;
nearSchedulerAdd(&dummySchedule);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accu, NCO1ACCU, "NCO1ACCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1acch, NCO1ACCH, "NCO1ACCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accl, NCO1ACCL, "NCO1ACCL");
}
void test_nearSchedulerAdd_calledWhenNoPendingSchedulesAndInsufficientTicksElapsed_expectNoHandlersCalled(void)
{
struct NearSchedule schedule =
{
.ticks = anyByteExcept(0),
.handler = &spyHandler
};
nearSchedulerAdd(&schedule);
for (uint8_t i = 0; i < schedule.ticks - 1; i++)
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAdd_notCalledButNcoHasTicked_expectNcoInterruptFlagIsCleared(void)
{
PIR7 = anyByteWithMaskClear(_PIR7_NCO1IF_MASK);
uint8_t originalPir7 = PIR7;
tick();
TEST_ASSERT_EQUAL_UINT8(originalPir7, PIR7);
}
void test_nearSchedulerAdd_calledAndWokenFromSleepBecauseOfNonTickEvent_expectNoHandlersAreCalled(void)
{
const struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler
};
nearSchedulerAdd(&schedule);
PIR7 = anyByteWithMaskClear(_PIR7_NCO1IF_MASK);
wokenFromSleep();
assertNoHandlersCalled();
}
void test_nearSchedulerAdd_calledWhenHandlerIsNull_expectNoHandlersAreCalled(void)
{
struct NearSchedule schedule =
{
.ticks = 1,
.handler = (NearScheduleHandler) 0,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAdd_calledWhenNoPendingSchedulesAndExactNumberOfTicksElapsed_expectHandlerIsCalled(void)
{
struct NearSchedule schedule =
{
.ticks = anyByteExcept(0),
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
for (uint8_t i = 0; i < schedule.ticks; i++)
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAdd_calledWithZeroTicksWhenNoPendingSchedules_expectNextTickCallsHandler(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAdd_calledWithZeroTicksWhenPendingSchedules_expectNextTickCallsHandler(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAdd_calledWhenPendingSchedulesAndExactNumberOfTicksElapsed_expectHandlerIsNotCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAdd_calledWhenPendingSchedulesAndRequestedNumberOfTicksPlusOneElapsed_expectHandlerIsCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAdd_calledWhenPendingSchedulesAnd255Ticks_expectHandlerIsNotCalledAfter255Ticks(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
for (uint8_t i = 0; i < 255; i++)
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAdd_calledWhenPendingSchedulesAndRequestedNumberOfTicksIs255_expectHandlerIsCalledAfter256Ticks(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
for (uint16_t i = 0; i < 256; i++)
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAdd_calledWhenMultipleSchedulesAtSameTick_expectHandlerIsCalledForEachOfThem(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule firstSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
struct NearSchedule secondSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&firstSchedule);
nearSchedulerAdd(&secondSchedule);
tick();
assertHandlerCalledTimes(2);
assertHandlerCalledWith(firstSchedule.state);
assertHandlerCalledWith(secondSchedule.state);
}
void test_nearSchedulerAdd_calledWhenMultipleSchedulesAtDifferentTick_expectHandlerIsCalledForEachOfThemInTurn(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAdd(&pendingSchedule);
struct NearSchedule firstSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
struct NearSchedule secondSchedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&firstSchedule);
nearSchedulerAdd(&secondSchedule);
tick();
assertHandlerCalledTimes(1);
assertHandlerCalledWith(firstSchedule.state);
tick();
assertHandlerCalledTimes(2);
assertHandlerCalledWith(secondSchedule.state);
}
<file_sep>/src/firmware/src/Platform/Battery.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include "Event.h"
#include "Nvm.h"
#include "PowerManagement.h"
#include "PeriodicMonitor.h"
#include "Temperature.h"
#include "Battery.h"
#define MINIMUM_FVR_ADC_COUNT (8 * 0x015a)
#define MAXIMUM_FVR_ADC_COUNT (8 * 0x0342)
#define MINIMUM_BATTERY_MILLIVOLTS 2500
#define BATTERY_START_CHARGING_MILLIVOLTS 3850
#define BATTERY_STOP_CHARGING_MILLIVOLTS 3930
static void onMonitoredParametersSampled(const struct Event *event);
static void onWokenFromSleep(const struct Event *event);
static void evaluateChargingConditions(void);
static void onTemperatureSampled(const struct Event *event);
static uint32_t scaledFvrNumerator;
static bool isChargerGood;
static bool isTemperatureWithinChargingRange;
static uint16_t batteryVoltageMillivolts;
static uint8_t batteryVoltageSampledSafetyCount;
void batteryInitialise(void)
{
ANSELB &= ~(_ANSELB_ANSB3_MASK | _ANSELB_ANSB4_MASK | _ANSELB_ANSB5_MASK);
LATBbits.LATB3 = 0;
TRISBbits.TRISB3 = 0;
TRISBbits.TRISB4 = 1;
TRISBbits.TRISB5 = 1;
INLVLBbits.INLVLB4 = 0;
INLVLBbits.INLVLB5 = 0;
PMD0bits.IOCMD = 0;
IOCBPbits.IOCBP5 = 1;
IOCBNbits.IOCBN5 = 1;
PIE0bits.IOCIE = 1;
static const struct EventSubscription onMonitoredParametersSampledSubscription =
{
.type = MONITORED_PARAMETERS_SAMPLED,
.handler = &onMonitoredParametersSampled,
.state = (void *) 0
};
eventSubscribe(&onMonitoredParametersSampledSubscription);
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
static const struct EventSubscription onTemperatureSampledSubscription =
{
.type = TEMPERATURE_SAMPLED,
.handler = &onTemperatureSampled,
.state = (void *) 0
};
eventSubscribe(&onTemperatureSampledSubscription);
scaledFvrNumerator = (uint32_t) 8192 * nvmWordAt(DIA_FVRA2X);
isChargerGood = false;
isTemperatureWithinChargingRange = false;
batteryVoltageMillivolts = 0;
batteryVoltageSampledSafetyCount = 0;
}
static void onMonitoredParametersSampled(const struct Event *event)
{
const struct MonitoredParametersSampled *args = (const struct MonitoredParametersSampled *) event->args;
if (!args->flags.isVddRegulated && args->fvr >= MINIMUM_FVR_ADC_COUNT && args->fvr <= MAXIMUM_FVR_ADC_COUNT)
{
static struct BatteryVoltageSampled eventArgs;
eventArgs.sample = args->fvr;
eventArgs.millivolts = (uint16_t) (scaledFvrNumerator / eventArgs.sample);
eventPublish(BATTERY_VOLTAGE_SAMPLED, &eventArgs);
batteryVoltageMillivolts = eventArgs.millivolts;
batteryVoltageSampledSafetyCount = 0;
}
else if (batteryVoltageSampledSafetyCount < 0xff)
batteryVoltageSampledSafetyCount++;
evaluateChargingConditions();
}
static void evaluateChargingConditions(void)
{
bool isBatteryVoltageWithinChargingRange =
batteryVoltageSampledSafetyCount < 3 &&
batteryVoltageMillivolts >= MINIMUM_BATTERY_MILLIVOLTS && (
(LATBbits.LATB3 && batteryVoltageMillivolts < BATTERY_STOP_CHARGING_MILLIVOLTS) ||
(!LATBbits.LATB3 && batteryVoltageMillivolts < BATTERY_START_CHARGING_MILLIVOLTS));
if (isChargerGood && isTemperatureWithinChargingRange && isBatteryVoltageWithinChargingRange)
{
if (LATBbits.LATB3 == 0)
{
LATBbits.LATB3 = 1;
eventPublish(BATTERY_CHARGER_ENABLED, &eventEmptyArgs);
}
}
else
{
if (LATBbits.LATB3 != 0)
{
LATBbits.LATB3 = 0;
eventPublish(BATTERY_CHARGER_DISABLED, &eventEmptyArgs);
}
}
}
static void onWokenFromSleep(const struct Event *event)
{
IOCBFbits.IOCBF5 = 0;
isChargerGood = !PORTBbits.RB5;
evaluateChargingConditions();
}
static void onTemperatureSampled(const struct Event *event)
{
const struct TemperatureSampled *args = (const struct TemperatureSampled *) event->args;
isTemperatureWithinChargingRange = args->currentCelsius >= CELSIUS(5) && args->currentCelsius <= CELSIUS(30);
evaluateChargingConditions();
}
<file_sep>/src/firmware/src/ApplicationNvmSettings.h
#ifndef __CLUCK2SESAME_SRC_APPLICATIONNVMSETTINGS_H
#define __CLUCK2SESAME_SRC_APPLICATIONNVMSETTINGS_H
#include <stdint.h>
union ApplicationNvmSettings
{
uint8_t raw[16];
struct
{
struct
{
int8_t latitudeOffset;
int8_t longitudeOffset;
} location;
struct
{
struct
{
unsigned int isManuallyOverridden : 1;
unsigned int isSunEventDriven : 1;
unsigned int isTimeDriven : 1;
} mode;
struct
{
uint8_t hour;
uint8_t minute;
} autoOpenTime;
struct
{
uint8_t hour;
uint8_t minute;
} autoCloseTime;
struct
{
int8_t sunriseOffsetMinutes;
int8_t sunsetOffsetMinutes;
} sunEvents;
uint16_t height;
} door;
struct
{
uint8_t screenTimeoutSeconds;
} ui;
};
};
#endif
<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Mock_VoltageRegulator.h"
#include "Mock_LcdInternals.h"
#include "Platform/Lcd.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_lcdInitialise_called_expectPwm3And5ModulesAreEnabled(void)
{
PMD3 = anyByteWithMaskSet(_PMD3_PWM3MD_MASK | _PMD3_PWM5MD_MASK);
uint8_t originalPmd3 = PMD3;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(
originalPmd3 & ~(_PMD3_PWM3MD_MASK | _PMD3_PWM5MD_MASK),
PMD3);
}
void test_lcdInitialise_called_expectLcdContrastPinIsTristated(void)
{
static const uint8_t lcdContrastPin = _TRISA_TRISA2_MASK;
ANSELA = anyByteWithMaskClear(lcdContrastPin);
TRISA = anyByteWithMaskClear(lcdContrastPin);
lcdInitialise();
TEST_ASSERT_BITS_HIGH_MESSAGE(lcdContrastPin, ANSELA, "ANSELA");
TEST_ASSERT_BITS_HIGH_MESSAGE(lcdContrastPin, TRISA, "TRISA");
}
void test_lcdInitialise_called_expectLcdPortANonContrastPinsAreAllOutputs(void)
{
static const uint8_t lcdContrastPin = _TRISA_TRISA2_MASK;
static const uint8_t usedPins =
_TRISA_TRISA3_MASK |
_TRISA_TRISA4_MASK |
_TRISA_TRISA5_MASK |
_TRISA_TRISA6_MASK |
_TRISA_TRISA7_MASK;
TRISA = anyByteWithMaskSet(usedPins);
uint8_t originalTrisa = TRISA & ~lcdContrastPin;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisa & ~usedPins, TRISA & ~lcdContrastPin);
}
void test_lcdInitialise_called_expectLcdPortCPinsAreAllOutputs(void)
{
static const uint8_t usedPins =
_TRISC_TRISC4_MASK |
_TRISC_TRISC5_MASK;
TRISC = anyByteWithMaskSet(usedPins);
uint8_t originalTrisc = TRISC;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisc & ~usedPins, TRISC);
}
void test_lcdInitialise_called_expectLcdPortANonContrastPinsAreAllDigital(void)
{
static const uint8_t lcdContrastPin = _ANSELA_ANSA2_MASK;
static const uint8_t usedPins =
_ANSELA_ANSA3_MASK |
_ANSELA_ANSA4_MASK |
_ANSELA_ANSA5_MASK |
_ANSELA_ANSA6_MASK |
_ANSELA_ANSA7_MASK;
ANSELA = anyByteWithMaskSet(usedPins);
uint8_t originalAnsela = ANSELA & ~lcdContrastPin;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnsela & ~usedPins, ANSELA & ~lcdContrastPin);
}
void test_lcdInitialise_called_expectLcdPortCPinsAreAllDigital(void)
{
static const uint8_t usedPins =
_ANSELC_ANSC4_MASK |
_ANSELC_ANSC5_MASK;
ANSELC = anyByteWithMaskSet(usedPins);
uint8_t originalAnselc = ANSELC;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnselc & ~usedPins, ANSELC);
}
void test_lcdInitialise_called_expectLcdPortAPinsAreAllLow(void)
{
static const uint8_t usedPins =
_LATA_LATA2_MASK |
_LATA_LATA3_MASK |
_LATA_LATA4_MASK |
_LATA_LATA5_MASK |
_LATA_LATA6_MASK |
_LATA_LATA7_MASK;
LATA = anyByteWithMaskSet(usedPins);
uint8_t originalLata = LATA;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLata & ~usedPins, LATA);
}
void test_lcdInitialise_called_expectLcdPortCPinsAreAllLow(void)
{
static const uint8_t usedPins =
_LATC_LATC4_MASK |
_LATC_LATC5_MASK;
LATC = anyByteWithMaskSet(usedPins);
uint8_t originalLatc = LATC;
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLatc & ~usedPins, LATC);
}
void test_lcdInitialise_called_expectContrastPinIsPwm5Output(void)
{
const uint8_t pwm5 = 0x0d;
RA2PPS = anyByteExcept(pwm5);
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(pwm5, RA2PPS);
}
void test_lcdInitialise_called_expectContrastIsDefaultSetting(void)
{
PWM5DCH = anyByte();
PWM5DCL = anyByte();
lcdInitialise();
uint8_t high = (nvmSettings.platform.lcd.contrast >> 2) & 0b00111111;
uint8_t low = (nvmSettings.platform.lcd.contrast << 6) & 0b11000000;
TEST_ASSERT_EQUAL_UINT8_MESSAGE(high, PWM5DCH, "H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(low, PWM5DCL, "L");
}
void test_lcdInitialise_called_expectContrastPwmIsDisabled(void)
{
PWM5CON = anyByteWithMaskSet(_PWM5CON_PWM5EN_MASK);
lcdInitialise();
TEST_ASSERT_FALSE(PWM5CONbits.PWM5EN);
}
void test_lcdInitialise_called_expectContrastPwmIsActiveHigh(void)
{
PWM5CON = anyByteWithMaskSet(_PWM5CON_PWM5POL_MASK);
lcdInitialise();
TEST_ASSERT_FALSE(PWM5CONbits.PWM5POL);
}
void test_lcdInitialise_called_expectBacklightPinIsPwm3Output(void)
{
const uint8_t pwm3 = 0x0b;
RC5PPS = anyByteExcept(pwm3);
lcdInitialise();
TEST_ASSERT_EQUAL_UINT8(pwm3, RC5PPS);
}
void test_lcdInitialise_called_expectBacklightBrightnessIsDefaultSetting(void)
{
PWM3DCH = anyByte();
PWM3DCL = anyByte();
lcdInitialise();
uint8_t high = (nvmSettings.platform.lcd.backlightBrightness >> 2) & 0b00111111;
uint8_t low = (nvmSettings.platform.lcd.backlightBrightness << 6) & 0b11000000;
TEST_ASSERT_EQUAL_UINT8_MESSAGE(high, PWM3DCH, "H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(low, PWM3DCL, "L");
}
void test_lcdInitialise_called_expectBacklightPwmIsDisabled(void)
{
PWM3CON = anyByteWithMaskSet(_PWM3CON_PWM3EN_MASK);
lcdInitialise();
TEST_ASSERT_FALSE(PWM3CONbits.PWM3EN);
}
void test_lcdInitialise_called_expectBacklightPwmIsActiveHigh(void)
{
PWM3CON = anyByteWithMaskSet(_PWM3CON_PWM3POL_MASK);
lcdInitialise();
TEST_ASSERT_FALSE(PWM3CONbits.PWM3POL);
}
<file_sep>/src/firmware/tests/Platform/Adc/TestAdcSample.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Adc.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Adc.c")
#define RESULT_ADDRL(x) __at(0x23a0 + (x) * 2 + 0)
#define RESULT_ADDRH(x) __at(0x23a0 + (x) * 2 + 1)
static uint8_t anyChannel(void);
static uint16_t anyRightJustifiedAdcResult(void);
volatile uint8_t isInvalidSession;
volatile uint8_t adcon0BeforeConversion;
volatile uint8_t adcon1BeforeConversion;
volatile uint8_t adactBeforeConversion;
volatile uint8_t stubAdcResultIndex;
volatile uint16_t stubAdcResult[8] RESULT_ADDRL(0);
volatile uint8_t stubAdcResult0l RESULT_ADDRL(0);
volatile uint8_t stubAdcResult0h RESULT_ADDRH(0);
volatile uint8_t stubAdcResult1l RESULT_ADDRL(1);
volatile uint8_t stubAdcResult1h RESULT_ADDRH(1);
volatile uint8_t stubAdcResult2l RESULT_ADDRL(2);
volatile uint8_t stubAdcResult2h RESULT_ADDRH(2);
volatile uint8_t stubAdcResult3l RESULT_ADDRL(3);
volatile uint8_t stubAdcResult3h RESULT_ADDRH(3);
volatile uint8_t stubAdcResult4l RESULT_ADDRL(4);
volatile uint8_t stubAdcResult4h RESULT_ADDRH(4);
volatile uint8_t stubAdcResult5l RESULT_ADDRL(5);
volatile uint8_t stubAdcResult5h RESULT_ADDRH(5);
volatile uint8_t stubAdcResult6l RESULT_ADDRL(6);
volatile uint8_t stubAdcResult6h RESULT_ADDRH(6);
volatile uint8_t stubAdcResult7l RESULT_ADDRL(7);
volatile uint8_t stubAdcResult7h RESULT_ADDRH(7);
static const uint8_t maxStubResults = sizeof(stubAdcResult) / sizeof(uint16_t);
void onBeforeTest(void)
{
isInvalidSession = 0;
adcon0BeforeConversion = 0;
adcon1BeforeConversion = 0;
adactBeforeConversion = 0;
stubAdcResultIndex = 0;
PMD2bits.ADCMD = 1;
adcInitialise();
}
void onAfterTest(void)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, isInvalidSession, "ADC violations !");
}
void test_adcSample_calledWithNullBuffer_expectReturnsWithoutTrap(void)
{
adcSample((struct AdcSample *) 0);
}
void test_adcSample_calledWithNullBuffer_expectAdcModuleIsNotEnabled(void)
{
PMD2 = anyByteWithMaskSet(_PMD2_ADCMD_MASK);
uint8_t originalPmd2 = PMD2;
adcSample((struct AdcSample *) 0);
TEST_ASSERT_EQUAL_UINT8(originalPmd2, PMD2);
}
void test_adcSample_called_expectAdcModuleIsDisabledAfterSampling(void)
{
PMD2 = anyByteWithMaskClear(_PMD2_ADCMD_MASK);
uint8_t originalPmd2 = PMD2;
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(originalPmd2 | _PMD2_ADCMD_MASK, PMD2);
}
static uint8_t anyChannel(void)
{
uint8_t channel = anyByteWithMaskSet(_ADCON0_ADON_MASK);
uint8_t chs = channel & _ADCON0_CHS_MASK;
if (chs >= 0b01100000 || chs <= 0b11101000)
channel |= 0b11110000;
return channel & ~_ADCON0_GO_MASK;
}
void test_adcSample_called_expectResultIsFromAdres(void)
{
stubAdcResult[0] = anyRightJustifiedAdcResult();
struct AdcSample sample =
{
.count = 1,
.channel = anyChannel(),
.result = anyWordExcept(stubAdcResult[0]),
.flags = { .all = 0 }
};
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT16(stubAdcResult[0], sample.result);
}
static uint16_t anyRightJustifiedAdcResult(void)
{
return anyWord() & 0x03ff;
}
void test_adcSample_called_expectAdcChannelIsSameAsPassedIn(void)
{
ADCON0 = anyByte();
uint8_t channel = anyChannel();
struct AdcSample sample = { .count = 1, .channel = channel, .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(
channel & _ADCON0_CHS_MASK,
adcon0BeforeConversion & _ADCON0_CHS_MASK);
}
void test_adcSample_called_expectAdcIsTurnedOn(void)
{
ADCON0 = anyByteWithMaskClear(_ADCON0_GO_MASK);
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_BITS_HIGH(_ADCON0_ADON_MASK, adcon0BeforeConversion);
}
void test_adcSample_called_expectAdcResultIsRightJustified(void)
{
ADCON1 = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel() };
adcSample(&sample);
TEST_ASSERT_BITS_HIGH(_ADCON1_ADFM_MASK, adcon1BeforeConversion);
}
void test_adcSample_called_expectAdcConversionClockIsFoscOver64For2MicrosecondClockPeriod(void)
{
ADCON1 = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(
0b110,
(adcon1BeforeConversion >> _ADCON1_ADCS_POSITION) & 0b111);
}
void test_adcSample_calledWhenVrefIsFvrFlagIsClear_expectAdcReferenceVoltageIsVdd(void)
{
ADCON1 = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(
0b00,
(adcon1BeforeConversion >> _ADCON1_ADPREF_POSITION) & 0b11);
}
void test_adcSample_calledWhenVrefIsFvrFlagIsSet_expectAdcReferenceVoltageIsInternalFixedVoltageReference(void)
{
ADCON1 = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
sample.flags.vrefIsFvr = 1;
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(
0b11,
(adcon1BeforeConversion >> _ADCON1_ADPREF_POSITION) & 0b11);
}
void test_adcSample_called_expectAdcAutoConversionTriggersAreDisabled(void)
{
ADACT = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(0, adactBeforeConversion);
}
void test_adcSample_calledWithZeroCount_expect0Result(void)
{
stubAdcResult[0] = anyWordExcept(0);
struct AdcSample sample =
{
.count = 0,
.channel = anyChannel(),
.result = anyWordExcept(0),
.flags = { .all = 0 }
};
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT16(0, sample.result);
}
void test_adcSample_calledWithCountGreaterThanOne_expectAccumulationOfResults(void)
{
uint8_t count = anyByteLessThan(maxStubResults + 1);
uint16_t accumulated = 0;
for (uint8_t i = 0; i < count; i++)
{
uint16_t result = anyRightJustifiedAdcResult();
stubAdcResult[i] = result;
accumulated += result;
}
struct AdcSample sample =
{
.count = count,
.channel = anyChannel(),
.result = anyWord(),
.flags = { .all = 0 }
};
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT16(accumulated, sample.result);
}
void test_adcSample_called_expectCountIsNotModified(void)
{
uint8_t count = anyByteLessThan(maxStubResults + 1);
struct AdcSample sample = { .count = count, .channel = anyChannel(), .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(count, sample.count);
}
void test_adcSample_called_expectChannelIsNotModified(void)
{
uint8_t channel = anyChannel();
struct AdcSample sample = { .count = 1, .channel = channel, .flags = { .all = 0 } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(channel, sample.channel);
}
void test_adcSample_called_expectFlagsAreNotModified(void)
{
uint8_t flags = anyByte();
struct AdcSample sample = { .count = 1, .channel = anyChannel(), .flags = { .all = flags } };
adcSample(&sample);
TEST_ASSERT_EQUAL_UINT8(flags, sample.flags.all);
}
<file_sep>/src/firmware/src/Platform/Lcd/Lcd.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_LCD_LCD_H
#define __CLUCK2SESAME_SRC_PLATFORM_LCD_LCD_H
#include <stdint.h>
#include "../Event.h"
#include "../Lcd.h"
#define LCD_NYBBLE_CMD 0b00000000
#define LCD_NYBBLE_DATA 0b10000000
struct LcdState
{
uint8_t enableCount;
union
{
uint8_t all;
struct
{
unsigned int isBusy : 1;
};
} flags;
struct
{
LcdTransactionCallback callback;
void *state;
} transaction;
};
extern void lcdOnVoltageRegulatorEnabled(const struct Event *event);
extern void lcdOnVoltageRegulatorDisabled(const struct Event *event);
extern void lcdConfigure(void);
extern void __reentrant lcdTransactionCompleted(void *unused);
extern void lcdWriteNybble(uint8_t nybble);
extern void lcdWriteCommand(uint8_t byte);
extern void lcdWriteData(uint8_t byte);
extern struct LcdState lcdState;
#endif
<file_sep>/src/firmware/tests/Door/TestDoorClosingOnMotorStopped2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfClose_expectDoorClosedIsPublished(void)
{
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
mockOnDoorClosed();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorClosedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorClosedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfUnchanged_expectDoorClosedIsPublished(void)
{
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
mockOnDoorClosed();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorClosedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorClosedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfOpen_expectDoorClosedIsPublished(void)
{
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
mockOnDoorClosed();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorClosedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorClosedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaults_expectDoorAbortedIsNotPublished(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
publishMotorStoppedWithNoFaults();
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedCalls, "Calls");
}
void test_motorStopped_onPublishedWithFaults_expectDoorClosedIsNotPublished(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
publishMotorStoppedWithFaults();
mockOnDoorClosed();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorClosedCalls, "Calls");
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorCurrentSenseDac.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD2bits.DAC1MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectDacIsEnabled(void)
{
DAC1CON0 = anyByteWithMaskClear(_DAC1CON0_EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(DAC1CON0bits.EN);
}
void test_voltageRegulatorEnabled_onPublished_expectDacOutputPin1IsDisabled(void)
{
DAC1CON0 = anyByteWithMaskSet(_DAC1CON0_DAC1OE1_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(DAC1CON0bits.OE1);
}
void test_voltageRegulatorEnabled_onPublished_expectDacOutputPin2IsDisabled(void)
{
DAC1CON0 = anyByteWithMaskSet(_DAC1CON0_DAC1OE2_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(DAC1CON0bits.OE2);
}
void test_voltageRegulatorEnabled_onPublished_expectDacPositiveReferenceIsVdd(void)
{
DAC1CON0 = anyByteWithMaskSet(
_DAC1CON0_DAC1PSS0_MASK | _DAC1CON0_DAC1PSS1_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, DAC1CON0bits.PSS);
}
void test_voltageRegulatorEnabled_onPublished_expectDacNegativeReferenceIsVss(void)
{
DAC1CON0 = anyByteWithMaskSet(_DAC1CON0_DAC1NSS_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(DAC1CON0bits.NSS);
}
void test_voltageRegulatorEnabled_onPublished_expectCurrentLimitComesFromNvmSettings(void)
{
DAC1CON1 = anyByteExcept(nvmSettings.platform.motor.currentLimitMaximumLoad);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(
nvmSettings.platform.motor.currentLimitMaximumLoad,
DAC1CON1);
}
<file_sep>/src/utilities/sunrise-sunset/Makefile
all:
$(MAKE) -C accurate all
$(MAKE) -C curve-fitting all
$(MAKE) -C lookup all
clean:
$(MAKE) -C accurate clean
$(MAKE) -C curve-fitting clean
$(MAKE) -C lookup clean
<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdSetDdramAddress.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Lcd.h"
#include "FakeLcd.h"
#include "LcdFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Poll.c")
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("Platform/PowerManagement.c")
TEST_FILE("Platform/PwmTimer.c")
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
TEST_FILE("Platform/Lcd/LcdConfigure.c")
TEST_FILE("Platform/Lcd/LcdTransaction.c")
TEST_FILE("Platform/Lcd/LcdWrite.c")
TEST_FILE("Platform/Lcd/LcdSetDdramAddress.c")
extern void poll(void);
static void sendSetDdramAddressToLcdAndWaitUntilDone(void);
static void onAddressSet(void *state);
static struct LcdSetAddressTransaction addressTransaction;
void onBeforeTest(void)
{
lcdFixtureInitialise();
}
void onAfterTest(void)
{
lcdFixtureShutdown();
}
void test_lcdSetDdramAddress_calledAfterLcdEnabled_expectCorrectDdramAddress(void)
{
enableLcdAndWaitUntilDone();
addressTransaction.address = anyByteWithMaskClear(0b10000000);
sendSetDdramAddressToLcdAndWaitUntilDone();
fakeLcdAssertDdramAddressRegisterIs(addressTransaction.address);
}
static void sendSetDdramAddressToLcdAndWaitUntilDone(void)
{
static uint8_t lcdCallbackDone;
addressTransaction.callback = &onAddressSet;
addressTransaction.state = (void *) &lcdCallbackDone;
lcdCallbackDone = 0;
lcdSetDdramAddress(&addressTransaction);
while (!lcdCallbackDone)
poll();
}
static void onAddressSet(void *state)
{
TEST_ASSERT_NOT_NULL(state);
*((uint8_t *) state) = 1;
}
void test_lcdSetDdramAddress_calledWithNullTransaction_expectLcdIsNotSentCommand(void)
{
enableLcdAndWaitUntilDone();
lcdSetDdramAddress((const struct LcdSetAddressTransaction *) 0);
fakeLcdAssertNotBusy();
}
void test_lcdSetDdramAddress_calledWithNullTransaction_expectNearSchedulerIsIdle(void)
{
enableLcdAndWaitUntilDone();
lcdSetDdramAddress((const struct LcdSetAddressTransaction *) 0);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdSetDdramAddress_calledBeforeLcdEnabled_expectLcdIsNotSentCommand(void)
{
lcdSetDdramAddress(&addressTransaction);
fakeLcdAssertNotBusy();
}
void test_lcdSetDdramAddress_calledBeforeLcdEnabled_expectNearSchedulerIsIdle(void)
{
lcdSetDdramAddress(&addressTransaction);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdSetDdramAddress_calledBeforeLcdConfigured_expectLcdIsNotSentCommand(void)
{
lcdEnable();
lcdSetDdramAddress(&addressTransaction);
fakeLcdAssertStateIsValid();
}
void test_lcdSetDdramAddress_calledWhileBusy_expectLcdIsNotSentCommand(void)
{
lcdEnable();
lcdSetDdramAddress(&addressTransaction);
lcdSetDdramAddress(&addressTransaction);
fakeLcdAssertStateIsValid();
}
void test_lcdSetDdramAddress_calledAfterLcdDisabled_expectLcdIsNotSentCommand(void)
{
enableLcdAndWaitUntilDone();
lcdDisable();
lcdSetDdramAddress(&addressTransaction);
fakeLcdAssertNotBusy();
}
void test_lcdSetDdramAddress_calledAfterLcdDisabled_expectNearSchedulerIsIdle(void)
{
enableLcdAndWaitUntilDone();
lcdDisable();
lcdSetDdramAddress(&addressTransaction);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdSetDdramAddress_calledTwice_expectCorrectDdramAddress(void)
{
enableLcdAndWaitUntilDone();
sendSetDdramAddressToLcdAndWaitUntilDone();
addressTransaction.address = anyByteWithMaskClear(0b10000000);
sendSetDdramAddressToLcdAndWaitUntilDone();
fakeLcdAssertDdramAddressRegisterIs(addressTransaction.address);
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/CalibrationModeFixtureWithUart.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_CALIBRATIONMODE_CALIBRATIONMODEFIXTUREWITHUART_H
#define __CLUCK2SESAME_TESTS_PLATFORM_CALIBRATIONMODE_CALIBRATIONMODEFIXTUREWITHUART_H
#include <stdint.h>
#include <stddef.h>
extern volatile uint8_t deviceToHostBytes[18];
extern volatile uint8_t deviceToHostNumberOfBytes;
extern void calibrationModeFixtureSetUp(void);
extern void calibrationModeFixtureTearDown(void);
extern void stubNvmSettingsWithCalibrationRequired(void);
extern void stubNvmSettingsWithoutCalibrationRequired(void);
extern void fakeHostToDeviceSend(const uint8_t *bytes, size_t numberOfBytes);
extern void fakeHostWaitForDeviceResponse(void);
extern void uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes);
extern void uart1_receivesInvalidCommand_expectInvalidArgumentErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes);
#endif
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerAdd2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#define MAX_SCHEDULES 8
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("NearSchedulerFixture.c")
static void assertNcoInterruptFlagIsClear(void *state);
static void handlerAddingAnotherSchedule(void *state);
void test_nearSchedulerAdd_called_expectHandlerIsNotCalledOnTickRollover(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
for (uint16_t i = 0; i < 513; i++)
tick();
assertHandlerCalledTimes(1);
}
void test_nearSchedulerAdd_called_expectHandlerIsCalledWithClearedNcoInterruptFlag(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &assertNcoInterruptFlagIsClear,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
tick();
}
static void assertNcoInterruptFlagIsClear(void *state)
{
TEST_ASSERT_FALSE(PIR7bits.NCO1IF);
}
void test_nearSchedulerAdd_calledMoreThanBufferSize_expectExistingHandlersAreNotOverwritten(void)
{
struct NearSchedule schedules[MAX_SCHEDULES + 1];
for (uint8_t i = 0; i < MAX_SCHEDULES + 1; i++)
{
schedules[i].ticks = 0;
schedules[i].handler = &spyHandler;
schedules[i].state = (void *) ((int) i);
nearSchedulerAdd(&schedules[i]);
}
tick();
assertHandlerCalledTimes(MAX_SCHEDULES);
for (uint8_t i = 0; i < MAX_SCHEDULES; i++)
assertHandlerCalledWith(schedules[i].state);
}
void test_nearSchedulerAdd_calledWithHandlerThatAddsAnotherScheduleWhenBufferExceeded_expectNewHandlerIsInserted(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &handlerAddingAnotherSchedule,
.state = (void *) ((int) anyWord())
};
nearSchedulerAdd(&schedule);
static const struct NearSchedule pendingSchedule =
{
.ticks = 3,
.handler = &dummyHandler
};
for (uint8_t i = 0; i < MAX_SCHEDULES - 1; i++)
nearSchedulerAdd(&pendingSchedule);
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
static void handlerAddingAnotherSchedule(void *state)
{
struct NearSchedule anotherSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = state
};
nearSchedulerAdd(&anotherSchedule);
}
void test_nearSchedulerAdd_calledWhenPendingSchedules_expectNcoIsEnabled(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &dummyHandler
};
nearSchedulerAdd(&schedule);
static const struct NearSchedule pendingSchedule =
{
.ticks = 2,
.handler = &dummyHandler
};
nearSchedulerAdd(&pendingSchedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con | _NCO1CON_N1EN_MASK, NCO1CON);
}
void test_nearSchedulerAdd_calledWhenPendingScheduleAddedFromLastHandler_expectNcoRemainsEnabled(void)
{
static const struct NearSchedule schedule =
{
.ticks = 0,
.handler = &handlerAddingAnotherSchedule
};
nearSchedulerAdd(&schedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con | _NCO1CON_N1EN_MASK, NCO1CON);
}
void test_nearSchedulerAdd_calledWhenNoPendingSchedules_expectNcoIsDisabled(void)
{
static const struct NearSchedule schedule =
{
.ticks = 0,
.handler = &dummyHandler
};
nearSchedulerAdd(&schedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con & ~_NCO1CON_N1EN_MASK, NCO1CON);
}
<file_sep>/src/firmware/tests/Platform/Motor/__TestMotorOn2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
#define MIN(x, y) (x < y ? x : y)
static void fakeMotorAlreadyTurning(void);
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorOn_calledWithClockwiseCount_expectPwmDutyCycleIsZero(void)
{
ensureMotorFullyEnabled();
PWM4DCH = anyByteExcept(0);
PWM4DCL = anyByteExcept(0);
motorOn(anyClockwiseCount());
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCL, "PWM4DCL");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCH, "PWM4DCH");
}
void test_motorOn_calledWithAntiClockwiseCount_expectPwmDutyCycleIsZero(void)
{
ensureMotorFullyEnabled();
PWM4DCH = anyByteExcept(0);
PWM4DCL = anyByteExcept(0);
motorOn(anyAntiClockwiseCount());
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCL, "PWM4DCL");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCH, "PWM4DCH");
}
void test_motorOn_calledWithZeroCount_expectPwmDutyCycleIsNotModified(void)
{
ensureMotorFullyEnabled();
PWM4DCH = anyByteExcept(0);
PWM4DCL = anyByteExcept(0);
uint8_t originalPwm4dcl = PWM4DCL;
uint8_t originalPwm4dch = PWM4DCH;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalPwm4dcl, PWM4DCL, "PWM4DCL");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalPwm4dch, PWM4DCH, "PWM4DCH");
}
void test_motorOn_calledWhenMotorAlreadyTurning_expectPwmDutyCycleIsNotModified(void)
{
ensureMotorFullyEnabled();
PWM4DCH = anyByteExcept(0);
PWM4DCL = anyByteExcept(0);
uint8_t originalPwm4dcl = PWM4DCL;
uint8_t originalPwm4dch = PWM4DCH;
fakeMotorAlreadyTurning();
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalPwm4dcl, PWM4DCL, "PWM4DCL");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalPwm4dch, PWM4DCH, "PWM4DCH");
}
static void fakeMotorAlreadyTurning(void)
{
CWG1STR = anyByte();
if (!(CWG1STR & STEERING_MASK))
CWG1STR |= _CWG1STR_STRC_MASK;
}
void test_motorOn_calledWithZeroCount_expectMotorStartedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
motorOn(0);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStartedCalls);
}
void test_motorOn_called_expectMotorStartedEventIsPublishedWithSameCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyEncoderCount();
motorOn(count);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStartedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStartedArgs.count, "Count");
}
void test_motorOn_called_expectNearScheduleAddedForPwm(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, nearSchedulerAddCalls, "Calls");
TEST_ASSERT_NOT_NULL_MESSAGE(nearSchedulerAddArgs[0], "Args");
TEST_ASSERT_NOT_NULL_MESSAGE(nearSchedulerAddArgs[0]->handler, "Handler");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, nearSchedulerAddArgs[0]->ticks, "Ticks");
}
void test_motorOn_calledWithZero_expectNoNearScheduleAddedForPwm(void)
{
ensureMotorFullyEnabled();
motorOn(0);
TEST_ASSERT_EQUAL_UINT8(0, nearSchedulerAddCalls);
}
void test_motorOn_calledWhenAlreadyTurning_expectNoNearScheduleAddedForPwm(void)
{
ensureMotorFullyEnabled();
fakeMotorAlreadyTurning();
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8(0, nearSchedulerAddCalls);
}
void test_motorOn_called_expectPwmIncrementsBy8UpTo256OnEachNearSchedulerTick(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
uint8_t i = 0;
for (uint16_t pwmDutyCycle = 8; pwmDutyCycle != 0; pwmDutyCycle += 8)
{
const struct NearSchedule *schedule = nearSchedulerAddArgs[i++ & 0x07];
if (schedule && schedule->handler)
schedule->handler(schedule->state);
uint8_t pwmLow = (uint8_t) ((pwmDutyCycle << 6) & 0xc0);
uint8_t pwmHigh = (uint8_t) ((pwmDutyCycle >> 2) & 0xff);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(pwmLow, PWM4DCL, "PWM4DCL");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(pwmHigh, PWM4DCH, "PWM4DCH");
}
}
void test_motorOn_called_expectPwmIsNotIncrementedJustPast8BitMaximumToPreventSpikes(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
const uint8_t total = 256 / 8;
for (uint8_t calls = 0; calls < total + 1; calls++)
{
TEST_ASSERT_EQUAL_UINT16(MIN(total, 1 + calls), nearSchedulerAddCalls);
const struct NearSchedule *schedule = nearSchedulerAddArgs[calls & 0x07];
if (schedule && schedule->handler)
schedule->handler(schedule->state);
}
}
void test_motorOn_calledWhenMotorIsStoppedByInterruptBeforeFullPwmDutyCycle_expectPwmStopsIncrementing(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR7bits.CWG1IF = 1;
publishWokenFromSleep();
dispatchAllEvents();
const struct NearSchedule *schedule = nearSchedulerAddArgs[0];
if (schedule && schedule->handler)
schedule->handler(schedule->state);
TEST_ASSERT_EQUAL_UINT16(1, nearSchedulerAddCalls);
}
void test_motorOn_calledWhenMotorIsStoppedManuallyBeforeFullPwmDutyCycle_expectPwmStopsIncrementing(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
motorOff();
const struct NearSchedule *schedule = nearSchedulerAddArgs[0];
if (schedule && schedule->handler)
schedule->handler(schedule->state);
TEST_ASSERT_EQUAL_UINT16(1, nearSchedulerAddCalls);
}
<file_sep>/src/firmware/tests/Platform/Nvm/TestNvmWordAt.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Nvm.h"
#include "../../NonDeterminism.h"
#include "../../Fixture.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/Nvm.c")
TEST_FILE("Platform/NvmSettings.c")
void onBeforeTest(void)
{
static union NvmSettings stubbedNvmSettings;
anyBytesInto(&stubbedNvmSettings, sizeof(union NvmSettings));
stubNvmSettings(&stubbedNvmSettings);
}
void onAfterTest(void)
{
}
void test_nvmWordAt_calledWithAddressInProgramSpace_expectCorrectWordIsReturned(void)
{
uint8_t offset = anyByteLessThan((uint8_t) sizeof(union NvmSettings));
const uint8_t *ptr = ((const uint8_t *) &nvmSettings) + offset;
uint16_t retlwWord = nvmWordAt(((uint16_t) ptr) & 0x7fff);
TEST_ASSERT_EQUAL_HEX16(0b11010000000000 | *ptr, retlwWord);
}
// TODO: If / when the simulator supports setting NVMCON1.NVMREGS to '1', these _test* functions ought to work and
// can be renamed:
void _test_nvmWordAt_calledWithAddressInConfigurationWordSpace_expectCorrectWordIsReturned(void)
{
static const uint16_t devid __at(0x8006);
static const uint16_t pic16f15356 = 0x30b0;
TEST_ASSERT_EQUAL_HEX16(pic16f15356, nvmWordAt(0x8006));
}
void _test_nvmWordAt_calledWithAddressInDeviceConfigurationInformationSpace_expectCorrectWordIsReturned(void)
{
static const uint16_t pcnt __at(DCI_PCNT);
TEST_ASSERT_EQUAL_HEX16(pcnt, nvmWordAt(DCI_PCNT));
}
void _test_nvmWordAt_calledWithAddressInDeviceInformationAreaSpace_expectCorrectWordIsReturned(void)
{
static const uint16_t mui4 __at(DIA_MUI4);
TEST_ASSERT_EQUAL_HEX16(mui4, nvmWordAt(DIA_MUI4));
}
<file_sep>/src/firmware/src/Door/Door.h
#ifndef __CLUCK2SESAME_SRC_DOOR_DOOR_H
#define __CLUCK2SESAME_SRC_DOOR_DOOR_H
#include "../Platform/Event.h"
#include "../Door.h"
#define SPOOL_CIRCUMFERENCE_MM (20 * 3.1415926535)
#define GEAR_RATIO 65
#define ENCODER_PULSES_PER_TURN 11
#define ROUND_NEAREST_FOR_SIGN(x) ((x) < 0 ? -0.5 : 0.5)
#define MM_TO_ENCODER_PULSES(mm) ((uint16_t) (((mm) / SPOOL_CIRCUMFERENCE_MM * GEAR_RATIO * ENCODER_PULSES_PER_TURN) + ROUND_NEAREST_FOR_SIGN(mm)))
#define MANUAL_MOVEMENT_LIMIT MM_TO_ENCODER_PULSES(1000)
#define FIND_BOTTOM_LOWERING MM_TO_ENCODER_PULSES(-100)
#define FIND_BOTTOM_RAISING MM_TO_ENCODER_PULSES(1000)
#define FIND_BOTTOM_THRESHOLD MM_TO_ENCODER_PULSES(2)
#define MAX_FIND_BOTTOM_ITERATIONS 10
#define DOOR_JAMMED 1
#define DOOR_REVERSED 2
#define LINE_SNAPPED 4
#define LINE_TOO_LONG 8
#define ENCODER_BROKEN 16
struct DoorStateInternal
{
enum DoorState current;
enum DoorTransition transition;
struct DoorOpened opened;
struct DoorClosed closed;
struct DoorAborted aborted;
uint8_t findBottomIterations;
};
extern struct DoorStateInternal doorState;
extern void doorOnOpenScheduleActioned(const struct Event *event);
extern void doorStartOpening(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState);
extern void doorStartFindingBottom(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState);
extern void doorOnCloseScheduleActioned(const struct Event *event);
extern void doorStartClosing(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState);
extern void doorOnMotorStopped(const struct Event *event);
extern void doorOnMotorEnabled(const struct Event *event);
#endif
<file_sep>/src/firmware/tests/Platform/Clock/ClockGetSetNowFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_CLOCK_CLOCKGETSETNOWFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_CLOCK_CLOCKGETSETNOWFIXTURE_H
#include <stdint.h>
extern void clockGetSetNowFixtureSetUp(void);
extern void clockGetSetNowFixtureTearDown(void);
extern void tick(void);
extern uint8_t anyNonLeapYear(void);
extern uint8_t anyNonLeapYearLessThan(uint8_t value);
extern uint8_t anyLeapYear(void);
#endif
<file_sep>/src/utilities/calibrator/calibration_process.py
class CalibrationProcess:
def __init__(self, calibrator_factory):
if calibrator_factory is None:
raise TypeError('calibrator_factory')
self._calibrator_factory = calibrator_factory
def calibrate(self):
calibrate_another = True
while calibrate_another:
while True:
ready = input('Is the device connected and ready for calibration; [y]es, [n]o or [q]uit ? ')
if ready in ('q', 'Q'):
calibrate_another = False
break
elif ready in ('y', 'Y'):
break
else:
print('Enter [y] to start device calibration, or [q] to quit.')
if calibrate_another:
calibrator = self._calibrator_factory()
if calibrator is None:
raise TypeError('calibrator')
calibrator.calibrate()
<file_sep>/src/firmware/src/Platform/PwmTimer.c
#include <xc.h>
#include <stdint.h>
#include "PwmTimer.h"
#define T2CON_PRESCALER_2 (0b001 << _T2CON_CKPS_POSITION)
#define T2CON_POSTSCALER_8 (0b0111 << _T2CON_OUTPS_POSITION)
#define T2CLKCON_FOSC_OVER_4 0b00000001
#define T2HLT_NO_PRESCALER_SYNC 0
#define T2HLT_RISING_EDGE 0
#define T2HLT_ON_SYNC _T2HLT_CKSYNC_MASK
#define T2HLT_MODE_FREE 0
#define T2HLT_MODE_SOFTGATE 0
static uint8_t enableCount;
void pwmTimerInitialise(void)
{
PMD1bits.TMR2MD = 0;
enableCount = 0;
T2CON = T2CON_PRESCALER_2 | T2CON_POSTSCALER_8;
T2CLKCON = T2CLKCON_FOSC_OVER_4;
T2HLT =
T2HLT_NO_PRESCALER_SYNC |
T2HLT_RISING_EDGE |
T2HLT_ON_SYNC |
T2HLT_MODE_FREE |
T2HLT_MODE_SOFTGATE;
PR2 = 63;
PIR4bits.TMR2IF = 0;
PIE4bits.TMR2IE = 0;
}
void pwmTimerEnable(void)
{
if (enableCount++ > 0)
return;
PIR4bits.TMR2IF = 0;
T2CONbits.ON = 1;
}
void pwmTimerDisable(void)
{
if (enableCount <= 1)
{
T2CONbits.ON = 0;
PIR4bits.TMR2IF = 0;
enableCount = 0;
}
else
--enableCount;
}
<file_sep>/src/utilities/calibrator/calibrator.py
import time
from calibration_point import CalibrationPoint
from calibration_results import CalibrationResults
class Calibrator:
def __init__(self, calibration_log, frequency_counter, device_factory, vdd_volts_range):
if calibration_log is None:
raise TypeError('calibration_log')
if frequency_counter is None:
raise TypeError('frequency_counter')
if device_factory is None:
raise TypeError('device_factory')
if vdd_volts_range is None:
raise TypeError('vdd_volts_range')
if len(vdd_volts_range) != 2:
raise Exception('VDD voltage range must be two voltages; one high, one low')
vdd_volts_range = sorted(vdd_volts_range)
if vdd_volts_range[0] < 2.7 or vdd_volts_range[1] > 4.5:
raise Exception('VDD voltages are out of range for the device; 2.7V <= VDD <= 4.5V')
if (vdd_volts_range[1] - vdd_volts_range[0]) < 1:
raise Exception('VDD voltage range is too narrow')
self._calibration_log = calibration_log
self._frequency_counter = frequency_counter
self._device_factory = device_factory
self._vdd_volts_range = vdd_volts_range
def calibrate(self):
with self._device_factory() as device:
dia = device.read_device_information_area()
log = self._calibration_log.for_device(dia.device_id)
log.add_device_information_area(dia)
nvm_settings = device.read_nvm_settings()
log.add_initial_nvm_settings(nvm_settings)
device.refclk_on()
calibration_points = [
self._sample_point(device, self._vdd_volts_range[0]),
self._sample_point(device, self._vdd_volts_range[1]),
self._sample_point(device, self._vdd_volts_range[0]),
self._sample_point(device, self._vdd_volts_range[1]),
self._sample_point(device, self._vdd_volts_range[0]),
self._sample_point(device, self._vdd_volts_range[1])
]
log.add_calibration_points(calibration_points)
results = CalibrationResults(nvm_settings, calibration_points)
log.add_calibration_results(results)
log.add_calibrated_nvm_settings(results.calibrated_nvm_settings)
device.refclk_off()
def _sample_point(self, device, vdd_volts):
Calibrator._confirm_vdd_is(vdd_volts)
temperature_celsius = Calibrator._get_temperature()
self._frequency_counter.start_measuring_frequency()
samples = []
for i in range(0, 10):
sample = device.sample_parameters()
if getattr(sample.flags, 'is_vdd_regulated', False):
raise Exception('Sample taken with +3.3V regulated voltage - calibration depends on variable VDD !')
samples.append(sample)
print(
f'TIMESTAMP={sample.timestamp:02}, ' +
f'FLAGS=0x{sample.flags.raw:02x}, ' +
f'FVR_adc={sample.fvr_adc_mean:f}, ' +
f'TEMP_adc={sample.temperature_adc_mean:f}')
time.sleep(1)
clock_frequency_hz = self._frequency_counter.await_measured_frequency_hz()
print(f'Clock Frequency = {clock_frequency_hz:f}Hz')
return CalibrationPoint(samples, vdd_volts, temperature_celsius, clock_frequency_hz)
@staticmethod
def _confirm_vdd_is(volts):
while True:
confirmation = input(f'Is VDD set to {volts}V; [y]es or [n]o ? ')
if confirmation in ('y', 'Y'):
return
print(f'This calibration point requires a VDD of {volts}V.')
@staticmethod
def _get_temperature():
while True:
temperature_celsius = Calibrator._float_input('Enter Current Temperature (Celsius): ')
if temperature_celsius < -10 or temperature_celsius > 40:
print('Temperature is out of range for the device; -10C <= temp <= 40C')
else:
return temperature_celsius
@staticmethod
def _float_input(prompt):
while True:
value = input(prompt)
try:
return float(value)
except ValueError:
print('Value is not convertible to a float !')
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerAddOrUpdate1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("NearSchedulerFixture.c")
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndNoPendingSchedules_expectNcoIsEnabled(void)
{
NCO1CON = anyByteWithMaskClear(_NCO1CON_N1EN_MASK);
uint8_t originalNco1con = NCO1CON;
nearSchedulerAddOrUpdate(&dummySchedule);
TEST_ASSERT_TRUE(NCO1CONbits.N1EN);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndNoPendingSchedules_expectNcoAccumulatorIsCleared(void)
{
NCO1ACCU = anyByte();
NCO1ACCH = anyByte();
NCO1ACCL = anyByte();
nearSchedulerAddOrUpdate(&dummySchedule);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCU, "NCO1ACCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCH, "NCO1ACCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1ACCL, "NCO1ACCL");
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedules_expectNcoAccumulatorIsNotCleared(void)
{
nearSchedulerAddOrUpdate(&dummySchedule);
NCO1ACCU = anyByte();
uint8_t originalNco1accu = NCO1ACCU;
NCO1ACCH = anyByte();
uint8_t originalNco1acch = NCO1ACCH;
NCO1ACCL = anyByte();
uint8_t originalNco1accl = NCO1ACCL;
nearSchedulerAddOrUpdate(&dummySchedule2);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accu, NCO1ACCU, "NCO1ACCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1acch, NCO1ACCH, "NCO1ACCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accl, NCO1ACCL, "NCO1ACCL");
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndNoPendingSchedulesAndInsufficientTicksElapsed_expectNoHandlersCalled(void)
{
struct NearSchedule schedule =
{
.ticks = anyByteExcept(0),
.handler = &spyHandler
};
nearSchedulerAddOrUpdate(&schedule);
for (uint8_t i = 0; i < schedule.ticks - 1; i++)
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_notCalledButNcoHasTicked_expectNcoInterruptFlagIsCleared(void)
{
PIR7 = anyByteWithMaskClear(_PIR7_NCO1IF_MASK);
uint8_t originalPir7 = PIR7;
tick();
TEST_ASSERT_EQUAL_UINT8(originalPir7, PIR7);
}
void test_nearSchedulerAddOrUpdate_calledAndWokenFromSleepBecauseOfNonTickEvent_expectNoHandlersAreCalled(void)
{
const struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler
};
nearSchedulerAddOrUpdate(&schedule);
PIR7 = anyByteWithMaskClear(_PIR7_NCO1IF_MASK);
wokenFromSleep();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenHandlerIsNull_expectNoHandlersAreCalled(void)
{
struct NearSchedule schedule =
{
.ticks = 1,
.handler = (NearScheduleHandler) 0,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndNoPendingSchedulesAndExactNumberOfTicksElapsed_expectHandlerIsCalled(void)
{
struct NearSchedule schedule =
{
.ticks = anyByteExcept(0),
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
for (uint8_t i = 0; i < schedule.ticks; i++)
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndWithZeroTicksWhenNoPendingSchedules_expectNextTickCallsHandler(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndWithZeroTicksWhenPendingSchedules_expectNextTickCallsHandler(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedulesAndExactNumberOfTicksElapsed_expectHandlerIsNotCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler2,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedulesAndRequestedNumberOfTicksPlusOneElapsed_expectHandlerIsCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler2,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedulesAnd255Ticks_expectHandlerIsNotCalledAfter255Ticks(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
for (uint8_t i = 0; i < 255; i++)
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedulesAndRequestedNumberOfTicksIs255_expectHandlerIsCalledAfter256Ticks(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
for (uint16_t i = 0; i < 256; i++)
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndMultipleSchedulesAtSameTick_expectHandlerIsCalledForEachOfThem(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule firstSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
struct NearSchedule secondSchedule =
{
.ticks = 0,
.handler = &spyHandler2,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&firstSchedule);
nearSchedulerAddOrUpdate(&secondSchedule);
tick();
assertHandlerCalledTimes(2);
assertHandlerCalledWith(firstSchedule.state);
assertHandlerCalledWith(secondSchedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndMultipleSchedulesAtDifferentTick_expectHandlerIsCalledForEachOfThemInTurn(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule firstSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
struct NearSchedule secondSchedule =
{
.ticks = 1,
.handler = &spyHandler2,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&firstSchedule);
nearSchedulerAddOrUpdate(&secondSchedule);
tick();
assertHandlerCalledTimes(1);
assertHandlerCalledWith(firstSchedule.state);
tick();
assertHandlerCalledTimes(2);
assertHandlerCalledWith(secondSchedule.state);
}
<file_sep>/src/firmware/tests/Door/TestDoorClosingOnMotorStopped1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsClose_expectClosedStateWithUnchangedTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closing,
.transition = DoorTransition_Close
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closed, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectClosedStateWithUnchangedTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closing,
.transition = DoorTransition_Unchanged
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closed, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosing_expectFaultStateWithUnmodifiedTransition(void)
{
uint8_t initialTransition = anyByte();
struct DoorStateWithContext state =
{
.current = DoorState_Closing,
.transition = initialTransition
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(initialTransition, state.transition, "T");
}
void test_motorStopped_onPublishedWithCurrentLimitFault_expectDoorAbortedIsPublishedWithReversedFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
static const struct MotorStopped reversed =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .currentLimited = 1 }
};
publishMotorStopped(&reversed);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithEncoderOverflowFault_expectDoorAbortedIsPublishedWithLineTooLongFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
static const struct MotorStopped tooLong =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .encoderOverflow = 1 }
};
publishMotorStopped(&tooLong);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithEncoderTimeoutFault_expectDoorAbortedIsPublishedWithEncoderBrokenFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
static const struct MotorStopped timeout =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .encoderTimeout = 1 }
};
publishMotorStopped(&timeout);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithUnknownFault_expectDoorAbortedIsPublishedWithNoFaultFlags(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Closing, anyTransition);
struct MotorStopped unknown =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .all = anyUnknownMotorFault() }
};
publishMotorStopped(&unknown);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedArgs[0]->fault.all, "F");
}
<file_sep>/src/utilities/calibrator/sdm3065x_frequency_counter.py
import time
class Sdm3065xFrequencyCounter:
def __init__(self, visa):
if visa is None:
raise TypeError('visa')
self._visa = visa
self._reset()
self._configure()
def _reset(self):
self._send_command('*RST')
def _send_command(self, command):
if '?' in command:
return self._visa.query(command, delay=0.01).strip()
return self._visa.write(command)
def _configure(self):
self._device_id = self._send_command('*IDN?')
self._send_command('CONFIGURE:FREQUENCY')
self._send_command('SENSE:FREQUENCY:VOLTAGE:RANGE 2V')
self._send_command('SENSE:FREQUENCY:APERTURE 1s')
self._send_command('SAMPLE:COUNT 10')
self._send_command('TRIGGER:SOURCE IMMEDIATE')
def get_measured_frequency_hz(self):
self.start_measuring_frequency()
return self.await_measured_frequency_hz()
def start_measuring_frequency(self):
self._send_command('INITIATE')
def await_measured_frequency_hz(self):
while int(self._send_command('DATA:POINTS?')) < 10:
time.sleep(0.1)
return float(self._send_command('CALCULATE:AVERAGE:AVERAGE?'))
<file_sep>/src/firmware/tests/unity_config.c
#include <xc.h>
#include <unity.h>
void unityBeforeRunHook(void)
{
}
void unityBreakpointHook(void)
{
while (1);
}
void putch(unsigned char data)
{
if (!TX2STAbits.TXEN)
{
TX2STAbits.TXEN = 1;
RC2STAbits.SPEN = 1;
}
while (!TX2STAbits.TRMT)
continue;
TX2REG = data;
}
<file_sep>/src/firmware/tests/Door/DoorFindBottomFixture.h
#ifndef __CLUCK2SESAME_TESTS_DOOR_DOORFINDBOTTOMFIXTURE_H
#define __CLUCK2SESAME_TESTS_DOOR_DOORFINDBOTTOMFIXTURE_H
#include "Platform/Motor.h"
extern const struct MotorStopped raisingStoppedImmediately;
extern const struct MotorStopped raisingStoppedAtThreshold;
extern const struct MotorStopped raisingStoppedJustAfterThreshold;
extern struct MotorStopped raisingStoppedAfterThreshold;
#endif
<file_sep>/src/firmware/src/Door/DoorGetState.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/NvmSettings.h"
#include "../ApplicationNvmSettings.h"
#include "Door.h"
void doorGetState(struct DoorStateWithContext *state)
{
state->current = doorState.current;
state->transition = doorState.transition;
state->flags.isTimeDriven =
nvmSettings.application.door.mode.isTimeDriven ? 1 : 0;
state->flags.isSunEventDriven =
nvmSettings.application.door.mode.isSunEventDriven ? 1 : 0;
state->flags.isManuallyOverridden =
(state->flags.isTimeDriven || state->flags.isSunEventDriven)
? 0
: 1;
state->fault.all =
doorState.current == DoorState_Fault
? doorState.aborted.fault.all
: 0;
}
<file_sep>/src/firmware/deploy.sh
#!/bin/bash
THIS_DIR="$(dirname "$(readlink -f "$0")")";
LOGS_DIR="${THIS_DIR}/build/deployment";
MPLABX_DIR="/opt/microchip/mplabx/v5.05/mplab_platform";
PICKIT3_IPE="${MPLABX_DIR}/mplab_ipe/ipecmd.sh -TPPK3";
HEX_FILENAME="${THIS_DIR}/build/ceedling/generated/release/Cluck2Sesame.hex";
pushd .;
cd "${LOGS_DIR}";
echo "*** DEPLOYMENT LOGS CAN BE FOUND IN ${LOGS_DIR}";
${PICKIT3_IPE} -P16F15356 -OL -M -Y -F${HEX_FILENAME};
popd;
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerAddOrUpdate2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#define MAX_SCHEDULES 8
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("NearSchedulerFixture.c")
static void assertNcoInterruptFlagIsClear(void *state);
static void handlerAddingAnotherSchedule(void *state);
void test_nearSchedulerAddOrUpdate_calledWhenAddingNew_expectHandlerIsNotCalledOnTickRollover(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
for (uint16_t i = 0; i < 513; i++)
tick();
assertHandlerCalledTimes(1);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNew_expectHandlerIsCalledWithClearedNcoInterruptFlag(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &assertNcoInterruptFlagIsClear,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
}
static void assertNcoInterruptFlagIsClear(void *state)
{
TEST_ASSERT_FALSE(PIR7bits.NCO1IF);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndMoreThanBufferSize_expectExistingHandlersAreNotOverwritten(void)
{
struct NearSchedule schedules[MAX_SCHEDULES + 1];
for (uint8_t i = 0; i < MAX_SCHEDULES + 1; i++)
{
schedules[i].ticks = 0;
schedules[i].handler = (i == MAX_SCHEDULES) ? &spyHandler2 : &spyHandler;
schedules[i].state = (void *) ((int) i);
if (i == MAX_SCHEDULES)
nearSchedulerAddOrUpdate(&schedules[i]);
else
nearSchedulerAdd(&schedules[i]);
}
tick();
assertHandlerCalledTimes(MAX_SCHEDULES);
for (uint8_t i = 0; i < MAX_SCHEDULES; i++)
assertHandlerCalledWith(schedules[i].state);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndWithHandlerThatAddsAnotherScheduleWhenBufferExceeded_expectNewHandlerIsInserted(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &handlerAddingAnotherSchedule,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
static const struct NearSchedule pendingSchedule =
{
.ticks = 3,
.handler = &dummyHandler
};
for (uint8_t i = 0; i < MAX_SCHEDULES - 1; i++)
nearSchedulerAdd(&pendingSchedule);
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
static void handlerAddingAnotherSchedule(void *state)
{
struct NearSchedule anotherSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = state
};
nearSchedulerAddOrUpdate(&anotherSchedule);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingSchedules_expectNcoIsEnabled(void)
{
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &dummyHandler
};
nearSchedulerAddOrUpdate(&schedule);
static const struct NearSchedule pendingSchedule =
{
.ticks = 2,
.handler = &dummyHandler2
};
nearSchedulerAddOrUpdate(&pendingSchedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con | _NCO1CON_N1EN_MASK, NCO1CON);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndPendingScheduleAddedFromLastHandler_expectNcoRemainsEnabled(void)
{
static const struct NearSchedule schedule =
{
.ticks = 0,
.handler = &handlerAddingAnotherSchedule
};
nearSchedulerAddOrUpdate(&schedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con | _NCO1CON_N1EN_MASK, NCO1CON);
}
void test_nearSchedulerAddOrUpdate_calledWhenAddingNewAndNoPendingSchedules_expectNcoIsDisabled(void)
{
static const struct NearSchedule schedule =
{
.ticks = 0,
.handler = &dummyHandler
};
nearSchedulerAddOrUpdate(&schedule);
uint8_t originalNco1con = NCO1CON;
tick();
TEST_ASSERT_EQUAL_UINT8(originalNco1con & ~_NCO1CON_N1EN_MASK, NCO1CON);
}
<file_sep>/src/firmware/tests/NvmSettingsFixture.h
#ifndef __CLUCK2SESAME_TESTS_NVMSETTINGSFIXTURE_H
#define __CLUCK2SESAME_TESTS_NVMSETTINGSFIXTURE_H
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
extern void stubNvmSettings(const union NvmSettings *stubbed);
extern void stubNvmApplicationSettings(
const union ApplicationNvmSettings *stubbed);
#endif
<file_sep>/src/firmware/tests/Platform/Lcd/FakeLcd.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Lcd.h"
#include "FakeLcd.h"
#include "../../NonDeterminism.h"
#define DRAM_ADDR(x) __at(0x23a0 + (x))
volatile uint8_t fakeLcdRs;
volatile uint8_t fakeLcdData;
volatile uint8_t fakeLcdInitialFunctionSetCount;
volatile uint8_t fakeLcdIsConfigured;
volatile uint8_t fakeLcdIsNybbleMode;
volatile uint8_t fakeLcdClocked;
volatile uint8_t fakeLcdCommand;
volatile uint8_t fakeLcdBusyFlag;
volatile uint32_t fakeLcdCommandIndex;
volatile uint8_t fakeLcdSessionIndex;
volatile uint8_t fakeLcdIsSessionInvalid;
volatile uint8_t fakeLcdRegFunction;
volatile uint8_t fakeLcdRegDisplay;
volatile uint8_t fakeLcdRegEntryMode;
volatile uint8_t fakeLcdRegDdramAddress;
volatile uint8_t fakeLcdDdramAddressIncrement;
volatile uint8_t fakeLcdDram[16 * 2] DRAM_ADDR(0);
volatile uint8_t fakeLcdDram0_0 DRAM_ADDR(0);
volatile uint8_t fakeLcdDram0_1 DRAM_ADDR(1);
volatile uint8_t fakeLcdDram0_2 DRAM_ADDR(2);
volatile uint8_t fakeLcdDram0_3 DRAM_ADDR(3);
volatile uint8_t fakeLcdDram0_4 DRAM_ADDR(4);
volatile uint8_t fakeLcdDram0_5 DRAM_ADDR(5);
volatile uint8_t fakeLcdDram0_6 DRAM_ADDR(6);
volatile uint8_t fakeLcdDram0_7 DRAM_ADDR(7);
volatile uint8_t fakeLcdDram0_8 DRAM_ADDR(8);
volatile uint8_t fakeLcdDram0_9 DRAM_ADDR(9);
volatile uint8_t fakeLcdDram0_10 DRAM_ADDR(10);
volatile uint8_t fakeLcdDram0_11 DRAM_ADDR(11);
volatile uint8_t fakeLcdDram0_12 DRAM_ADDR(12);
volatile uint8_t fakeLcdDram0_13 DRAM_ADDR(13);
volatile uint8_t fakeLcdDram0_14 DRAM_ADDR(14);
volatile uint8_t fakeLcdDram0_15 DRAM_ADDR(15);
volatile uint8_t fakeLcdDram1_0 DRAM_ADDR(16);
volatile uint8_t fakeLcdDram1_1 DRAM_ADDR(17);
volatile uint8_t fakeLcdDram1_2 DRAM_ADDR(18);
volatile uint8_t fakeLcdDram1_3 DRAM_ADDR(19);
volatile uint8_t fakeLcdDram1_4 DRAM_ADDR(20);
volatile uint8_t fakeLcdDram1_5 DRAM_ADDR(21);
volatile uint8_t fakeLcdDram1_6 DRAM_ADDR(22);
volatile uint8_t fakeLcdDram1_7 DRAM_ADDR(23);
volatile uint8_t fakeLcdDram1_8 DRAM_ADDR(24);
volatile uint8_t fakeLcdDram1_9 DRAM_ADDR(25);
volatile uint8_t fakeLcdDram1_10 DRAM_ADDR(26);
volatile uint8_t fakeLcdDram1_11 DRAM_ADDR(27);
volatile uint8_t fakeLcdDram1_12 DRAM_ADDR(28);
volatile uint8_t fakeLcdDram1_13 DRAM_ADDR(29);
volatile uint8_t fakeLcdDram1_14 DRAM_ADDR(30);
volatile uint8_t fakeLcdDram1_15 DRAM_ADDR(31);
void fakeLcdInitialise(void)
{
for (uint8_t i = 0; i < sizeof(fakeLcdDram); i++)
fakeLcdDram[i] = i;
fakeLcdSessionIndex++;
}
void fakeLcdShutdown(void)
{
fakeLcdAssertStateIsValid();
}
void fakeLcdAssertStateIsValid(void)
{
TEST_ASSERT_FALSE_MESSAGE(fakeLcdIsSessionInvalid, "LCD violations !");
}
void fakeLcdAssertNotBusy(void)
{
TEST_ASSERT_FALSE(fakeLcdBusyFlag);
}
void fakeLcdAssertFunctionRegister(uint8_t flags)
{
TEST_ASSERT_EQUAL_HEX8(LCD_CMD_FUNCTION | flags, fakeLcdRegFunction);
}
void fakeLcdAssertDisplayRegister(uint8_t flags)
{
TEST_ASSERT_EQUAL_HEX8(LCD_CMD_DISPLAY | flags, fakeLcdRegDisplay);
}
void fakeLcdAssertEntryModeRegister(uint8_t flags)
{
TEST_ASSERT_EQUAL_HEX8(LCD_CMD_ENTRYMODE | flags, fakeLcdRegEntryMode);
}
void fakeLcdAssertDdramAddressRegisterIs(uint8_t address)
{
TEST_ASSERT_EQUAL_HEX8(address, fakeLcdRegDdramAddress);
}
<file_sep>/src/firmware/tests/Door/TestDoorOnDateChanged.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_dateChanged_onPublishedWhenDoorIsTimeDriven_expectScheduleIsAddedForOpeningTimeStoredInNvm(void)
{
stubNvmSettingsForTimeDrivenMode();
struct FarSchedule expectedOpeningSchedule =
{
.time =
{
.hour = nvmSettings.application.door.autoOpenTime.hour,
.minute = nvmSettings.application.door.autoOpenTime.minute
},
.eventType = DOOR_OPEN_SCHEDULE_ACTIONED
};
publishDateChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 1);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedOpeningSchedule,
farSchedulerAddArgs[0]);
}
void test_dateChanged_onPublishedWhenDoorIsTimeDriven_expectScheduleIsAddedForClosingTimeStoredInNvm(void)
{
stubNvmSettingsForTimeDrivenMode();
struct FarSchedule expectedClosingSchedule =
{
.time =
{
.hour = nvmSettings.application.door.autoCloseTime.hour,
.minute = nvmSettings.application.door.autoCloseTime.minute
},
.eventType = DOOR_CLOSE_SCHEDULE_ACTIONED
};
publishDateChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 2);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedClosingSchedule,
farSchedulerAddArgs[1]);
}
void test_dateChanged_onPublishedWhenDoorIsManuallyDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForManuallyDrivenMode();
publishDateChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_dateChanged_onPublishedWhenDoorIsSunEventDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForSunEventDrivenMode();
publishDateChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_dateChanged_onPublishedWhenDoorIsUnspecifiedMode_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForUnspecifiedMode();
publishDateChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
<file_sep>/src/utilities/calibrator/calibrate.py
import sys
import pyvisa
from pathlib import Path
from serial import Serial
from calibration_log import CalibrationLog
from calibration_process import CalibrationProcess
from calibration_results_loader import CalibrationResultsLoader
from calibrator import Calibrator
from cluck2sesame_device import Cluck2SesameDevice
from sdm3065x_frequency_counter import Sdm3065xFrequencyCounter
from tf930_frequency_counter import Tf930FrequencyCounter
calibration_dir = Path('../calibrated')
def calibrate_devices():
# with Serial('/dev/ttyWHATEVER', baudrate=115200, timeout=30, xonxoff=True) as frequency_counter_port:
# frequency_counter = Tf930FrequencyCounter(frequency_counter_port)
global calibration_dir
resources = pyvisa.ResourceManager('@py')
with resources.open_resource('USB0::62700::60984::SDM36GBQ5R0755::0::INSTR') as resource:
frequency_counter = Sdm3065xFrequencyCounter(resource)
calibrator = CalibrationProcess(
lambda: Calibrator(
CalibrationLog(calibration_dir),
frequency_counter,
lambda: Cluck2SesameDevice(lambda: Serial('/dev/ttyS0', baudrate=9600, timeout=30)),
vdd_volts_range=[2.7, 4.5]))
calibrator.calibrate()
def recalculate_results_for(device_id):
global calibration_dir
loader = CalibrationResultsLoader(Path(calibration_dir, device_id))
results = loader.load()
log = CalibrationLog(calibration_dir).for_device(device_id)
log.add_calibration_results(results)
log.add_calibrated_nvm_settings(results.calibrated_nvm_settings)
if __name__ == '__main__':
if len(sys.argv) == 1:
calibrate_devices()
else:
recalculate_results_for(sys.argv[1])
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerAddOrUpdate3.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("NearSchedulerFixture.c")
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingSchedule_expectNcoAccumulatorIsNotCleared(void)
{
nearSchedulerAddOrUpdate(&dummySchedule);
NCO1ACCU = anyByte();
uint8_t originalNco1accu = NCO1ACCU;
NCO1ACCH = anyByte();
uint8_t originalNco1acch = NCO1ACCH;
NCO1ACCL = anyByte();
uint8_t originalNco1accl = NCO1ACCL;
nearSchedulerAddOrUpdate(&dummySchedule);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accu, NCO1ACCU, "NCO1ACCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1acch, NCO1ACCH, "NCO1ACCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalNco1accl, NCO1ACCL, "NCO1ACCL");
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingScheduleWithZeroTicks_expectNextTickCallsHandler(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingScheduleWithZeroTicks_expectOriginalHandlerIsNotCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingScheduleAndExactNumberOfTicksElapsed_expectHandlerIsNotCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingSchedulesAndRequestedNumberOfTicksPlusOneElapsed_expectHandlerIsCalled(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 7,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 1,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
tick();
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingScheduleAnd255Ticks_expectHandlerIsNotCalledAfter255Ticks(void)
{
struct NearSchedule pendingSchedule = { .ticks = 0, .handler = &spyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&schedule);
for (uint8_t i = 0; i < 255; i++)
tick();
assertNoHandlersCalled();
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingPendingScheduleAndRequestedNumberOfTicksIs255_expectHandlerIsCalledAfter256Ticks(void)
{
struct NearSchedule pendingSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule schedule =
{
.ticks = 255,
.handler = &spyHandler,
.state = (void *) ((int) anyWordExcept((uint16_t) pendingSchedule.state))
};
nearSchedulerAddOrUpdate(&schedule);
for (uint16_t i = 0; i < 256; i++)
tick();
assertHandlerCalledOnceWith(schedule.state);
}
void test_nearSchedulerAddOrUpdate_calledWhenUpdatingMultipleSchedulesAtSameTick_expectHandlerIsOnlyCalledForOneOfThem(void)
{
struct NearSchedule pendingSchedule = { .handler = &dummyHandler };
nearSchedulerAddOrUpdate(&pendingSchedule);
struct NearSchedule firstSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWord())
};
struct NearSchedule secondSchedule =
{
.ticks = 0,
.handler = &spyHandler,
.state = (void *) ((int) anyWordExcept((uint16_t) firstSchedule.state))
};
nearSchedulerAddOrUpdate(&firstSchedule);
nearSchedulerAddOrUpdate(&secondSchedule);
tick();
assertHandlerCalledOnceWith(secondSchedule.state);
}
<file_sep>/src/firmware/tests/Platform/TestInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Mock_Event.h"
#include "Fixture.h"
TEST_FILE("Platform/Initialise.c")
struct CallDetails
{
uint8_t sequence;
uint8_t count;
};
void eventInitialiseCallback(int numCalls);
void eventPublishCallback(EventType type, const void *args, int numCalls);
static void clearCallsFor(struct CallDetails *calls);
static void assertCalledOnceAtSequence(
struct CallDetails *call,
uint8_t sequence);
static void registerCallFor(struct CallDetails *calls);
static uint8_t callSequence;
static struct CallDetails eventInitialiseCalls;
static struct CallDetails powerManagementInitialiseCalls;
static struct CallDetails clockInitialiseCalls;
static struct CallDetails nearSchedulerInitialiseCalls;
static struct CallDetails farSchedulerInitialiseCalls;
static struct CallDetails voltageRegulatorInitialiseCalls;
static struct CallDetails temperatureInitialiseCalls;
static struct CallDetails batteryInitialiseCalls;
static struct CallDetails pwmTimerInitialiseCalls;
static struct CallDetails adcInitialiseCalls;
static struct CallDetails lcdInitialiseCalls;
static struct CallDetails motorInitialiseCalls;
static struct CallDetails periodicMonitorInitialiseCalls;
static struct CallDetails buttonsInitialiseCalls;
static struct CallDetails calibrationModeInitialiseCalls;
static struct CallDetails applicationInitialiseCalls;
static struct CallDetails systemInitialisedEventPublishCalls;
const struct Event eventEmptyArgs = { };
void onBeforeTest(void)
{
callSequence = 1;
clearCallsFor(&eventInitialiseCalls);
clearCallsFor(&powerManagementInitialiseCalls);
clearCallsFor(&clockInitialiseCalls);
clearCallsFor(&nearSchedulerInitialiseCalls);
clearCallsFor(&farSchedulerInitialiseCalls);
clearCallsFor(&voltageRegulatorInitialiseCalls);
clearCallsFor(&temperatureInitialiseCalls);
clearCallsFor(&batteryInitialiseCalls);
clearCallsFor(&pwmTimerInitialiseCalls);
clearCallsFor(&adcInitialiseCalls);
clearCallsFor(&lcdInitialiseCalls);
clearCallsFor(&motorInitialiseCalls);
clearCallsFor(&periodicMonitorInitialiseCalls);
clearCallsFor(&buttonsInitialiseCalls);
clearCallsFor(&calibrationModeInitialiseCalls);
clearCallsFor(&applicationInitialiseCalls);
clearCallsFor(&systemInitialisedEventPublishCalls);
eventInitialise_StubWithCallback(&eventInitialiseCallback);
eventPublish_StubWithCallback(&eventPublishCallback);
}
static void clearCallsFor(struct CallDetails *calls)
{
calls->sequence = 0;
calls->count = 0;
}
void onAfterTest(void)
{
}
void test_initialise_called_expectEventSystemIsInitialisedFirst(void)
{
initialise();
assertCalledOnceAtSequence(&eventInitialiseCalls, 1);
}
static void assertCalledOnceAtSequence(
struct CallDetails *call,
uint8_t sequence)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, call->count, "Count");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(sequence, call->sequence, "Sequence");
}
void eventInitialiseCallback(int numCalls)
{
registerCallFor(&eventInitialiseCalls);
}
static void registerCallFor(struct CallDetails *calls)
{
calls->sequence = callSequence++;
calls->count++;
}
void test_initialise_called_expectPowerManagementIsInitialisedAfterEvents(void)
{
initialise();
assertCalledOnceAtSequence(&powerManagementInitialiseCalls, 2);
}
void powerManagementInitialise(void)
{
registerCallFor(&powerManagementInitialiseCalls);
}
void test_initialise_called_expectClockIsInitialisedAfterPowerManagement(void)
{
initialise();
assertCalledOnceAtSequence(&clockInitialiseCalls, 3);
}
void clockInitialise(void)
{
registerCallFor(&clockInitialiseCalls);
}
void test_initialise_called_expectNearSchedulerIsInitialisedAfterClock(void)
{
initialise();
assertCalledOnceAtSequence(&nearSchedulerInitialiseCalls, 4);
}
void nearSchedulerInitialise(void)
{
registerCallFor(&nearSchedulerInitialiseCalls);
}
void test_initialise_called_expectFarSchedulerIsInitialisedAfterNearScheduler(void)
{
initialise();
assertCalledOnceAtSequence(&farSchedulerInitialiseCalls, 5);
}
void farSchedulerInitialise(void)
{
registerCallFor(&farSchedulerInitialiseCalls);
}
void test_initialise_called_expectVoltageRegulatorIsInitialisedAfterFarScheduler(void)
{
initialise();
assertCalledOnceAtSequence(&voltageRegulatorInitialiseCalls, 6);
}
void voltageRegulatorInitialise(void)
{
registerCallFor(&voltageRegulatorInitialiseCalls);
}
void test_initialise_called_expectTemperatureIsInitialisedAfterVoltageRegulator(void)
{
initialise();
assertCalledOnceAtSequence(&temperatureInitialiseCalls, 7);
}
void temperatureInitialise(void)
{
registerCallFor(&temperatureInitialiseCalls);
}
void test_initialise_called_expectBatteryIsInitialisedAfterTemperature(void)
{
initialise();
assertCalledOnceAtSequence(&batteryInitialiseCalls, 8);
}
void batteryInitialise(void)
{
registerCallFor(&batteryInitialiseCalls);
}
void test_initialise_called_expectPwmTimerIsInitialisedAfterBattery(void)
{
initialise();
assertCalledOnceAtSequence(&pwmTimerInitialiseCalls, 9);
}
void pwmTimerInitialise(void)
{
registerCallFor(&pwmTimerInitialiseCalls);
}
void test_initialise_called_expectAdcIsInitialisedAfterPwmTimer(void)
{
initialise();
assertCalledOnceAtSequence(&adcInitialiseCalls, 10);
}
void adcInitialise(void)
{
registerCallFor(&adcInitialiseCalls);
}
void test_initialise_called_expectLcdIsInitialisedAfterAdc(void)
{
initialise();
assertCalledOnceAtSequence(&lcdInitialiseCalls, 11);
}
void lcdInitialise(void)
{
registerCallFor(&lcdInitialiseCalls);
}
void test_initialise_called_expectMotorIsInitialisedAfterLcd(void)
{
initialise();
assertCalledOnceAtSequence(&motorInitialiseCalls, 12);
}
void motorInitialise(void)
{
registerCallFor(&motorInitialiseCalls);
}
void test_initialise_called_expectPeriodicMonitorIsInitialisedAfterMotor(void)
{
initialise();
assertCalledOnceAtSequence(&periodicMonitorInitialiseCalls, 13);
}
void periodicMonitorInitialise(void)
{
registerCallFor(&periodicMonitorInitialiseCalls);
}
void test_initialise_called_expectButtonsAreInitialisedAfterPeriodicMonitor(void)
{
initialise();
assertCalledOnceAtSequence(&buttonsInitialiseCalls, 14);
}
void buttonsInitialise(void)
{
registerCallFor(&buttonsInitialiseCalls);
}
void test_initialise_called_expectCalibrationModeIsInitialisedAfterButtons(void)
{
initialise();
assertCalledOnceAtSequence(&calibrationModeInitialiseCalls, 15);
}
void calibrationModeInitialise(void)
{
registerCallFor(&calibrationModeInitialiseCalls);
}
void test_initialise_called_expectApplicationIsInitialisedAfterCalibrationMode(void)
{
initialise();
assertCalledOnceAtSequence(&applicationInitialiseCalls, 16);
}
void applicationInitialise(void)
{
registerCallFor(&applicationInitialiseCalls);
}
void test_initialise_called_expectSystemInitialisedEventIsPublishedLast(void)
{
initialise();
assertCalledOnceAtSequence(
&systemInitialisedEventPublishCalls,
callSequence - 1);
}
void eventPublishCallback(EventType type, const void *args, int numCalls)
{
if (type == SYSTEM_INITIALISED && args)
registerCallFor(&systemInitialisedEventPublishCalls);
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorSetLimits.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NvmSettingsFixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
TEST_FILE("Platform/Motor/MotorSetLimits.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
union NvmSettings replacementSettings =
{
.platform =
{
.motor =
{
.currentLimitNoLoad = anyByteLessThan(32),
.currentLimitMaximumLoad = anyByteLessThan(32)
}
}
};
stubNvmSettings(&replacementSettings);
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorLimitIsNoLoad_called_expectCurrentLimitIsFromNvmSettings(void)
{
ensureMotorFullyEnabled();
DAC1CON1 = anyByteExcept(nvmSettings.platform.motor.currentLimitNoLoad);
motorLimitIsNoLoad();
TEST_ASSERT_EQUAL_UINT8(
nvmSettings.platform.motor.currentLimitNoLoad,
DAC1CON1);
}
void test_motorLimitIsMaximumLoad_called_expectCurrentLimitIsFromNvmSettings(void)
{
ensureMotorFullyEnabled();
DAC1CON1 = anyByteExcept(nvmSettings.platform.motor.currentLimitMaximumLoad);
motorLimitIsMaximumLoad();
TEST_ASSERT_EQUAL_UINT8(
nvmSettings.platform.motor.currentLimitMaximumLoad,
DAC1CON1);
}
<file_sep>/src/firmware/tests/Door/TestDoorFindBottom3.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void test_findBottomAfterRaisingStopHasCurrentLimitFault_expectDoorAbortedIsNotPublished(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
publishMotorStopped(&raisingStoppedImmediately);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedCalls, "Calls");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsJustMoreThan2mm_expectMotorIsNotLowered(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorOnCalls = 0;
publishMotorStopped(&raisingStoppedJustAfterThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorOnCalls, "Calls");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mm_expectMotorIsNotLowered(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorOnCalls = 0;
publishMotorStopped(&raisingStoppedJustAfterThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorOnCalls, "Calls");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIs2mmOnCloseTransition_expectMotorIsNotDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Close);
publishMotorStopped(&raisingStoppedAtThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorDisableCalls);
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnCloseTransition_expectMotorIsDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorDisableCalls = 0;
stubDoorWithState(DoorState_FindBottom, DoorTransition_Close);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorDisableCalls, "Calls");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnUnchangedTransition_expectMotorIsDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorDisableCalls = 0;
stubDoorWithState(DoorState_FindBottom, DoorTransition_Unchanged);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorDisableCalls, "Calls");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorIsNotDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorDisableCalls, "Calls");
}
<file_sep>/src/firmware/tests/Fixture.h
#ifndef __CLUCK2SESAME_TESTS_FIXTURE_H
#define __CLUCK2SESAME_TESTS_FIXTURE_H
extern void onBeforeTest(void);
extern void onAfterTest(void);
extern void dispatchAllEvents(void);
extern void publishWokenFromSleep(void);
#endif
<file_sep>/src/firmware/tests/Platform/Battery/BatteryFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PeriodicMonitor.h"
#include "Platform/Temperature.h"
#include "Platform/Battery.h"
#include "BatteryFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
static void onBatteryChargerEnabled(const struct Event *event);
static void onBatteryChargerDisabled(const struct Event *event);
static uint16_t stubbedDiaFvra2xMillivolts;
const struct Event eventEmptyArgs = { };
const struct BatteryChargerEnabled *batteryChargerEnabledEventArgs;
const struct BatteryChargerDisabled *batteryChargerDisabledEventArgs;
volatile uint8_t isChargerGoodPinHigh;
void batteryFixtureSetUp(void)
{
eventInitialise();
stubbedDiaFvra2xMillivolts = FVR_IDEAL_MV;
isChargerGoodPinHigh = 1;
static const struct EventSubscription onBatteryChargerEnabledSubscription =
{
.type = BATTERY_CHARGER_ENABLED,
.handler = &onBatteryChargerEnabled,
.state = (void *) 0
};
eventSubscribe(&onBatteryChargerEnabledSubscription);
static const struct EventSubscription onBatteryChargerDisabledSubscription =
{
.type = BATTERY_CHARGER_DISABLED,
.handler = &onBatteryChargerDisabled,
.state = (void *) 0
};
eventSubscribe(&onBatteryChargerDisabledSubscription);
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) 0;
stubAnyDiaFvra2xMillivolts();
}
static void onBatteryChargerEnabled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Null event !");
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) event->args;
TEST_ASSERT_NOT_NULL_MESSAGE(batteryChargerEnabledEventArgs, "Null event args !");
}
static void onBatteryChargerDisabled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Null event !");
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) event->args;
TEST_ASSERT_NOT_NULL_MESSAGE(batteryChargerDisabledEventArgs, "Null event args !");
}
void batteryFixtureTearDown(void)
{
}
uint16_t stubAnyDiaFvra2xMillivolts(void)
{
uint16_t fvrMillivolts = FVR_IDEAL_MV - FVR_TOLERANCE_MV + anyWordLessThan(2 * FVR_TOLERANCE_MV + 1);
stubDiaFvra2xMillivolts(fvrMillivolts);
return fvrMillivolts;
}
void stubDiaFvra2xMillivolts(uint16_t millivolts)
{
stubbedDiaFvra2xMillivolts = millivolts;
}
uint16_t nvmWordAt(uint16_t address)
{
if (address == DIA_FVRA2X)
return stubbedDiaFvra2xMillivolts;
return 0;
}
void stubAllParametersThatWillEnableCharging(void)
{
stubChargerGoodPinLow();
stubTemperatureWithinChargingRange();
stubBatteryVoltageWithinChargingRange();
dispatchAllEvents();
}
void stubChargerGoodPinLow(void)
{
isChargerGoodPinHigh = 0;
publishWokenFromSleep();
}
void stubChargerGoodPinHigh(void)
{
isChargerGoodPinHigh = 1;
publishWokenFromSleep();
}
void stubTemperatureWithinChargingRange(void)
{
stubTemperatureOf((int16_t) (CELSIUS(5) + anyWordLessThan(CELSIUS(25.1))));
}
void stubTemperatureOf(int16_t celsius)
{
static struct TemperatureSampled eventArgs;
eventArgs.sample = anyWord();
eventArgs.currentCelsius = celsius;
eventArgs.deltaCelsius = (int16_t) anyWord();
eventArgs.deltaSeconds = anyByte();
eventPublish(TEMPERATURE_SAMPLED, &eventArgs);
}
void stubBatteryVoltageWithinChargingRange(void)
{
stubBatteryVoltageOf(2500 + anyWordLessThan(1300));
}
void stubBatteryVoltageOf(uint16_t millivolts)
{
static struct MonitoredParametersSampled eventArgs =
{
.flags = { .isVddRegulated = 0 },
.temperature = 12345
};
eventArgs.fvr = (uint16_t) ((uint32_t) 8192 * nvmWordAt(DIA_FVRA2X) / millivolts);
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
}
<file_sep>/src/firmware/tests/Platform/Motor/__TestMotorOn1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorOn_calledWithPositiveCount_expectCcpLimitIsSameValue(void)
{
ensureMotorFullyEnabled();
int16_t clockwise = anyClockwiseCount();
motorOn(clockwise);
TEST_ASSERT_EQUAL_UINT8_MESSAGE((clockwise >> 8) & 0xff, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE((clockwise >> 0) & 0xff, CCPR1L, "CCPR1L");
}
void test_motorOn_calledWithNegativeCount_expectCcpLimitIsNegatedValue(void)
{
ensureMotorFullyEnabled();
int16_t antiClockwise = anyAntiClockwiseCount();
motorOn(antiClockwise);
TEST_ASSERT_EQUAL_UINT8_MESSAGE((-antiClockwise >> 8) & 0xff, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE((-antiClockwise >> 0) & 0xff, CCPR1L, "CCPR1L");
}
void test_motorOn_calledWithMaximumNegativeCount_expectCcpLimitIsMaximumPositiveValue(void)
{
ensureMotorFullyEnabled();
motorOn(-32768);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0x7f, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0xff, CCPR1L, "CCPR1L");
}
void test_motorOn_called_expectTimer1IsCleared(void)
{
ensureMotorFullyEnabled();
TMR1H = anyByteExcept(0);
TMR1L = anyByteExcept(0);
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, TMR1L, "TMR1L");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, TMR1H, "TMR1H");
}
void test_motorOn_called_expectTimer1InterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
PIR4 = anyByteWithMaskSet(_PIR4_TMR1IF_MASK);
uint8_t originalPir4 = PIR4;
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR1IF_MASK, PIR4);
}
void test_motorOn_calledWithZero_expectCcpLimitIsNotCleared(void)
{
ensureMotorFullyEnabled();
CCPR1H = anyByteExcept(0);
CCPR1L = anyByteExcept(0);
uint8_t originalCcpr1h = CCPR1H;
uint8_t originalCcpr1l = CCPR1L;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1h, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1l, CCPR1L, "CCPR1L");
}
void test_motorOn_calledWithZero_expectTimer1IsNotCleared(void)
{
ensureMotorFullyEnabled();
TMR1H = anyByteExcept(0);
TMR1L = anyByteExcept(0);
uint8_t originalTmr1l = TMR1L;
uint8_t originalTmr1h = TMR1H;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalTmr1l, TMR1L, "TMR1L");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalTmr1h, TMR1H, "TMR1H");
}
void test_motorOn_calledWithZero_expectTimer1InterruptFlagIsNotCleared(void)
{
ensureMotorFullyEnabled();
PIR4bits.TMR1IF = 1;
motorOn(0);
TEST_ASSERT_TRUE(PIR4bits.TMR1IF);
}
void test_motorOn_called_expectCcpModeIsCompareWithSetAndHoldOutputWithTmr1Preserved(void)
{
ensureMotorFullyEnabled();
CCP1CON = anyByteWithMaskSet(_CCP1CON_MODE1_MASK);
uint8_t originalCcp1conWithClearMode =
(CCP1CON & ~(0b1111 << _CCP1CON_MODE_POSITION)) | _CCP1CON_OUT_MASK;
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8(
originalCcp1conWithClearMode | (0b1000 << _CCP1CON_MODE_POSITION),
CCP1CON | _CCP1CON_OUT_MASK);
}
void test_motorOn_calledWithZero_expectCcpModeIsUnchanged(void)
{
ensureMotorFullyEnabled();
CCP1CON = anyByteWithMaskSet(_CCP1CON_MODE1_MASK);
uint8_t originalCcp1con = CCP1CON | _CCP1CON_OUT_MASK;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8(originalCcp1con, CCP1CON | _CCP1CON_OUT_MASK);
}
void test_motorOn_called_expectShutdownFlagIsCleared(void)
{
ensureMotorFullyEnabled();
CWG1AS0 = anyByteWithMaskSet(_CWG1AS0_SHUTDOWN_MASK);
uint8_t originalCwg1as0 = CWG1AS0;
motorOn(anyEncoderCount());
TEST_ASSERT_EQUAL_UINT8(originalCwg1as0 & ~_CWG1AS0_SHUTDOWN_MASK, CWG1AS0);
}
void test_motorOn_calledWithZero_expectShutdownFlagIsNotCleared(void)
{
ensureMotorFullyEnabled();
CWG1AS0 = anyByteWithMaskSet(_CWG1AS0_SHUTDOWN_MASK);
uint8_t originalCwg1as0 = CWG1AS0;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8(originalCwg1as0, CWG1AS0);
}
void test_motorOn_calledWithClockwiseCountWhenNotTurning_expectPwmSteeringToStrb(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskClear(STEERING_MASK);
uint8_t originalCwg1strWithClearSteering = CWG1STR;
motorOn(anyClockwiseCount());
TEST_ASSERT_EQUAL_UINT8(
originalCwg1strWithClearSteering | _CWG1STR_STRB_MASK,
CWG1STR);
}
void test_motorOn_calledWithClockwiseCountWhenTurning_expectPwmSteeringIsNotModified(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskSet(STEERING_MASK) & ~_CWG1STR_STRB_MASK;
uint8_t originalCwg1str = CWG1STR;
motorOn(anyClockwiseCount());
TEST_ASSERT_EQUAL_UINT8(originalCwg1str, CWG1STR);
}
void test_motorOn_calledWithAntiClockwiseCountWhenNotTurning_expectPwmSteeringToStra(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskClear(STEERING_MASK);
uint8_t originalCwg1strWithClearSteering = CWG1STR;
motorOn(anyAntiClockwiseCount());
TEST_ASSERT_EQUAL_UINT8(
originalCwg1strWithClearSteering | _CWG1STR_STRA_MASK,
CWG1STR);
}
void test_motorOn_calledWithAntiClockwiseCountWhenTurning_expectPwmSteeringIsNotModified(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskSet(STEERING_MASK) & ~_CWG1STR_STRA_MASK;
uint8_t originalCwg1str = CWG1STR;
motorOn(anyAntiClockwiseCount());
TEST_ASSERT_EQUAL_UINT8(originalCwg1str, CWG1STR);
}
void test_motorOn_calledWithZeroWhenTurning_expectPwmSteeringIsNotModified(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskSet(STEERING_MASK) & ~_CWG1STR_STRA_MASK;
uint8_t originalCwg1str = CWG1STR;
motorOn(0);
TEST_ASSERT_EQUAL_UINT8(originalCwg1str, CWG1STR);
}
// TODO: motorOn() - probably shouldn't clear TMR1IF; that should be the 'on woken from sleep' handler's responsibility (also make sure TMR1IE is set in motorInitialise())
<file_sep>/src/firmware/src/Ui/UiInitialise.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Platform/Event.h"
#include "../Platform/Main.h"
#include "../Platform/Buttons.h"
#include "../Platform/Lcd.h"
#include "../Platform/NvmSettings.h"
#include "Ui.h"
static void uiOnLcdEnabled(const struct Event *event);
static void uiOnLcdDisabled(const struct Event *event);
struct UiState uiState;
union NvmSettings uiNvmSettings;
void uiInitialise(void)
{
static const struct EventSubscription onButtonsPressedSubscription =
{
.type = BUTTONS_PRESSED,
.handler = &uiInputOnButtonsPressed,
.state = (void *) 0
};
eventSubscribe(&onButtonsPressedSubscription);
static const struct EventSubscription onButtonsReleasedSubscription =
{
.type = BUTTONS_RELEASED,
.handler = &uiInputOnButtonsReleased,
.state = (void *) 0
};
eventSubscribe(&onButtonsReleasedSubscription);
static const struct EventSubscription onSystemInitialisedSubscription =
{
.type = SYSTEM_INITIALISED,
.handler = &uiOnSystemInitialised,
.state = (void *) 0
};
eventSubscribe(&onSystemInitialisedSubscription);
static const struct EventSubscription onLcdEnabledSubscription =
{
.type = LCD_ENABLED,
.handler = &uiOnLcdEnabled
};
eventSubscribe(&onLcdEnabledSubscription);
static const struct EventSubscription onLcdDisabledSubscription =
{
.type = LCD_DISABLED,
.handler = &uiOnLcdDisabled
};
eventSubscribe(&onLcdDisabledSubscription);
uiState.input.buttons = &uiInputIsUninitialised;
uiState.input.cursorPosition = UI_NO_CURSOR;
memcpy(&uiNvmSettings, (const void *) &nvmSettings, sizeof(union NvmSettings));
}
static void uiOnLcdEnabled(const struct Event *event)
{
uiState.flags.bits.isLcdEnabled = 1;
uiScreenBlit();
}
static void uiOnLcdDisabled(const struct Event *event)
{
uiState.flags.bits.isLcdEnabled = 0;
}
<file_sep>/src/firmware/tests/Platform/Buttons/TestButtonsWokenFromSleep.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Mock_PowerManagement.h"
#include "Mock_NearScheduler.h"
#include "Platform/Buttons.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Buttons.c")
static void eventSubscribeStub(const struct EventSubscription *subscription, int numCalls);
static void wakeFromSleep(void);
static EventHandler onWokenFromSleep;
static void *onWokenFromSleepState;
void onBeforeTest(void)
{
onWokenFromSleep = (EventHandler) 0;
onWokenFromSleepState = (void *) 0;
eventSubscribe_StubWithCallback(&eventSubscribeStub);
buttonsInitialise();
IOCAF = 0;
}
static void eventSubscribeStub(const struct EventSubscription *subscription, int numCalls)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == WOKEN_FROM_SLEEP)
{
onWokenFromSleep = subscription->handler;
onWokenFromSleepState = subscription->state;
}
}
void onAfterTest(void)
{
}
// TODO: The simulator's being a bit of a pain with IOC - wasted so much time. Leaving it to bench testing...
void IGNORED__test_wokenFromSleep_onPublishedWhenIocFlagsSet_expectAllIocFlagsAreCleared(void)
{
IOCAF = anyByteWithMaskSet(_IOCAF_IOCAF0_MASK | _IOCAF_IOCAF1_MASK);
wakeFromSleep();
TEST_ASSERT_EQUAL_UINT8(0, IOCAF);
}
static void wakeFromSleep(void)
{
if (!onWokenFromSleep)
return;
struct Event eventArgs =
{
.type = WOKEN_FROM_SLEEP,
.args = (const void *) 0,
.state = onWokenFromSleepState
};
onWokenFromSleep(&eventArgs);
}
void test_wokenFromSleep_onPublishedWhenIocFlagsSet_expectIocOredFlagIsCleared(void)
{
IOCAF = anyByteWithMaskSet(_IOCAF_IOCAF0_MASK | _IOCAF_IOCAF1_MASK);
PIR0 = anyByteWithMaskSet(_PIR0_IOCIF_MASK);
uint8_t originalPir0 = PIR0;
wakeFromSleep();
TEST_ASSERT_EQUAL_UINT8(originalPir0 & ~_PIR0_IOCIF_MASK, PIR0);
}
// TODO: EXPECT NEAR SCHEDULE IS ADDED / UPDATED (ONLY WHEN IOCAF IS NOT 0) - IOC IS TOO DIFFICULT TO WORK WITH IN THE SIMULATOR
// TODO: NEAR SCHEDULE EXPIRY TESTS... - IOC IS TOO DIFFICULT TO WORK WITH IN THE SIMULATOR
<file_sep>/src/utilities/calibrator/tf930_frequency_counter.py
import time
class Tf930FrequencyCounter:
def __init__(self, serial):
if serial is None:
raise TypeError('serial')
self._serial = serial
self._serial.open()
self._reset()
self._configure()
def _reset(self):
self._serial.write("\n*RST\n")
time.sleep(1)
self._serial.reset_input_buffer()
def _configure(self):
self._device_id = self._send_query('*IDN?')
self._send_command('Z1')
self._send_command('A1')
self._send_command('AC')
self._send_command('ER')
self._send_command('FI')
self._send_command('F2')
self._send_command('M3')
def _send_query(self, command):
self._send_command(command + "\n")
return self._serial.readline().strip()
def _send_command(self, command):
self._serial.write(command + "\n")
def get_measured_frequency_hz(self):
self.start_measuring_frequency()
return self.await_measured_frequency_hz()
def start_measuring_frequency(self):
self._send_command('N?')
def await_measured_frequency_hz(self):
return float(self._serial.readline().strip())
<file_sep>/src/firmware/src/Platform/FarScheduler.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_FARSCHEDULER_H
#define __CLUCK2SESAME_SRC_PLATFORM_FARSCHEDULER_H
#include <stdint.h>
#include "Event.h"
struct FarSchedule
{
struct
{
uint8_t hour;
uint8_t minute;
} time;
EventType eventType;
const void *eventArgs;
};
extern void farSchedulerInitialise(void);
extern void farSchedulerAdd(const struct FarSchedule *schedule);
extern void farSchedulerRemove(const struct FarSchedule *schedule);
#endif
<file_sep>/src/firmware/tests/Platform/CalibrationMode/CalibrationModeFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Platform/PowerManagement.h"
#include "Platform/CalibrationMode.h"
#include "../../NonDeterminism.h"
#include "../../Fixture.h"
#include "../../NvmSettingsFixture.h"
#include "CalibrationModeFixture.h"
static struct Event onWokenFromSleepEvent;
static const struct EventSubscription *onWokenFromSleep;
const struct Event eventEmptyArgs = { };
static void buggyCompilerWorkaround(void)
{
if (0)
onWokenFromSleep->handler(&onWokenFromSleepEvent);
}
void calibrationModeFixtureSetUp(void)
{
onWokenFromSleep = (const struct EventSubscription *) 0;
buggyCompilerWorkaround();
}
void calibrationModeFixtureTearDown(void)
{
}
void stubNvmSettingsWithCalibrationRequired(void)
{
static const union NvmSettings withCalibrationRequired =
{
.platform =
{
.flags = { .bits = { .isCalibrationRequired = 1 } }
}
};
stubNvmSettings(&withCalibrationRequired);
}
void stubNvmSettingsWithoutCalibrationRequired(void)
{
static const union NvmSettings withoutCalibrationRequired =
{
.platform =
{
.flags = { .bits = { .isCalibrationRequired = 0 } }
}
};
stubNvmSettings(&withoutCalibrationRequired);
}
void eventSubscribe(const struct EventSubscription *subscription)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == WOKEN_FROM_SLEEP)
{
onWokenFromSleep = subscription;
onWokenFromSleepEvent.type = subscription->type;
onWokenFromSleepEvent.state = subscription->state;
onWokenFromSleepEvent.args = (void *) 0;
}
else
{
TEST_FAIL_MESSAGE("Unknown subscription type");
}
}
void assertWokenFromSleepSubscription(void)
{
TEST_ASSERT_NOT_NULL(onWokenFromSleep);
}
void assertNoWokenFromSleepSubscription(void)
{
TEST_ASSERT_NULL(onWokenFromSleep);
}
<file_sep>/src/utilities/calibrator/cluck2sesame_parameters_sample.py
from types import SimpleNamespace
class Cluck2SesameParametersSample:
def __init__(self, timestamp, flags, fvr_adc_aggregate, temperature_adc_aggregate):
if timestamp is None:
raise TypeError('timestamp')
if flags is None:
raise TypeError('flags')
if fvr_adc_aggregate is None:
raise TypeError('fvr_adc_aggregate')
if temperature_adc_aggregate is None:
raise TypeError('temperature_adc_aggregate')
self._timestamp = int(timestamp)
if self._timestamp < 0 or self._timestamp > 59:
raise Exception(f'Timestamp must be an integral number of seconds; timestamp={self._timestamp}')
self._flags = int(flags)
if self._flags < 0 or self._flags > 0xff:
raise Exception(f'Flags must be a single byte; flags=0x{self._flags:2x}')
self._fvr_adc_aggregate = int(fvr_adc_aggregate)
if self._fvr_adc_aggregate < 0 or self._fvr_adc_aggregate > 8 * 1023:
raise Exception(f'FVR ADC aggregate value must be a maximum of 8x unsigned 10-bit samples; value=0x{self._fvr_adc_aggregate:2x}')
self._temperature_adc_aggregate = int(temperature_adc_aggregate)
if self._temperature_adc_aggregate < 0 or self._temperature_adc_aggregate > 8 * 1023:
raise Exception(f'Temperature ADC aggregate value must be a maximum of 8x unsigned 10-bit samples; value=0x{self._temperature_adc_aggregate:2x}')
@classmethod
def from_raw(cls, raw):
fields = raw.split(',')
if len(fields) != 4:
raise Exception('Invalid parameters sample result from device; result=' + raw)
return cls(
int(fields[0], base=16),
int(fields[1], base=16),
int(fields[2], base=16),
int(fields[3], base=16))
@property
def timestamp(self): return self._timestamp
@property
def flags(self): return Cluck2SesameParametersSample._decode_flags(self._flags)
@property
def fvr_adc_aggregate(self): return self._fvr_adc_aggregate
@property
def fvr_adc_mean(self): return self._fvr_adc_aggregate / 8
@property
def temperature_adc_aggregate(self): return self._temperature_adc_aggregate
@property
def temperature_adc_mean(self): return self._temperature_adc_aggregate / 8
@staticmethod
def _decode_flags(flags):
as_obj = SimpleNamespace(raw=flags)
if flags & 0b0000_0001:
as_obj.is_vdd_regulated = True
return as_obj
<file_sep>/src/utilities/sunrise-sunset/accurate/sunrise-sunset.c
/*
From the algorithm described here:
http://www.stargazing.net/kepler/sunrise.html
Which in turn was derived from the Explanatory Supplement to the
Astronomical Almanac section 9.33.
Used in conjunction with the fantastic resources here:
http://aa.usno.navy.mil/data/index.php
Assumptions and notes:
- The year is only allowed to be in the range [2000,2099]; a negative
Julian Date is not allowed. TODO: VERIFY JAN 1 2000 !!!
- Only a 32-by-16 bit division is available.
- The sine and cosine are builtins, not CORDIC. The angle units will
be translated to the same units used by the CORDIC implementation.
- The sine and cosine of phi are computed at the same time by CORDIC,
so identities such as sin(2 * phi) -> 2 * sin(phi) * cos(phi) are
actually cheaper to implement.
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define LITERAL_0_77_Q0_16 0xc51f
#define LITERAL_0_46_Q0_16 0x75c3
#define LITERAL_36000_OVER_36525_Q0_16 0xfc52
#define LITERAL_0_05_Q0_16 0x0ccd
#define LITERAL_0_528_Q0_16 0x872b
#define LITERAL_35999_OVER_36525_Q0_16 0xfc50
#define LITERAL_0_915_Q1_15 ((FixedQ1_15) 0x751f)
#define LITERAL_0_04_Q1_15 ((FixedQ1_15) 0x051f)
#define LITERAL_0_466_Q1_15 ((FixedQ1_15) 0x3ba6)
#define LITERAL_0_053_Q1_15 ((FixedQ1_15) 0x06c9)
#define LITERAL_0_4393_Q1_15 ((FixedQ1_15) 0x383b)
#define LITERAL_0_013_Q1_15 ((FixedQ1_15) 0x01aa)
#define DEGREES_0_Q1_15 ((FixedQ1_15) 0x0000)
#define DEGREES_180_Q1_15 ((FixedQ1_15) 0x8000)
typedef struct
{
int year : 16;
int month : 8;
int day : 8;
} GregorianDate;
typedef int JulianDate;
typedef int Accumulator;
typedef unsigned short FixedQ0_16;
typedef short FixedQ1_15;
typedef struct
{
struct
{
int quiet : 1;
int addCorrection : 1;
} flags;
FixedQ1_15 latitude;
FixedQ1_15 longitude;
FixedQ1_15 eventTime;
FixedQ1_15 eventHeight;
JulianDate epochAsJulianDate;
JulianDate julianDate;
unsigned short daysSinceEpoch;
Accumulator meanLongitudeIncludingAberration;
FixedQ1_15 meanAnomaly;
Accumulator equatorialCentreCorrection;
FixedQ1_15 sunEclipticLongitude;
FixedQ1_15 equationOfTime;
FixedQ1_15 greenwichHourAngle;
FixedQ1_15 obliquityOfTheEcliptic;
FixedQ1_15 sunDeclination;
FixedQ1_15 correction;
} SunState;
static void initialiseState(SunState *state, double latitude, double longitude);
static JulianDate calculateJulianDateAtMidday(
SunState *state,
GregorianDate date);
static GregorianDate date(int year, int month, int day);
static void calculateSunriseOn(SunState *state, GregorianDate date);
static void calculateEventOn(SunState *state, GregorianDate date);
static void calculateDaysSinceEpoch(SunState *state);
static void calculateMeanLongitudeIncludingAberration(SunState *state);
static void calculateMeanAnomaly(SunState *state);
static FixedQ1_15 degreesToUnits(Accumulator phi, int q);
static void calculateEquatorialCentreCorrection(SunState *state);
static FixedQ1_15 sine(FixedQ1_15 phi);
static FixedQ1_15 doubleToFixedQ1_15(double x);
static FixedQ1_15 cosine(FixedQ1_15 phi);
static void calculateSunEclipticLongitude(SunState *state);
static void calculateEquationOfTime(SunState *state);
static void calculateGreenwichHourAngle(SunState *state);
static void calculateObliquityOfTheEcliptic(SunState *state);
static void calculateSunDeclination(SunState *state);
static FixedQ1_15 arcSine(FixedQ1_15 x);
static void calculateCorrection(SunState *state);
static FixedQ1_15 arcCosine(FixedQ1_15 x);
static void calculateEventTime(SunState *state);
static void calculateSunsetOn(SunState *state, GregorianDate date);
int main(int argc, char *argv[])
{
SunState state;
initialiseState(&state, 51.509865, -0.118092);
calculateSunriseOn(&state, date(2000, 2, 1));
calculateSunsetOn(&state, date(2099, 2, 1));
return 0;
}
static void initialiseState(SunState *state, double latitude, double longitude)
{
if (!state->flags.quiet)
printf("Initialising state...\n");
memset(state, 0, sizeof(SunState));
state->latitude = (FixedQ1_15) (32768 * latitude / 180);
state->longitude = (FixedQ1_15) (32768 * longitude / 180);
state->eventTime = DEGREES_180_Q1_15;
state->epochAsJulianDate = calculateJulianDateAtMidday(
state,
date(2000, 1, 1));
}
static int calculateJulianDateAtMidday(
SunState *state,
GregorianDate date)
{
/* http://aa.usno.navy.mil/faq/docs/JD_Formula.php */
int monthMinus14Over12 = (date.month - 14) / 12;
int julianDate =
date.day - 32075 +
1461 * (date.year + 4800 + monthMinus14Over12) / 4 +
367 * (date.month - 2 - monthMinus14Over12 * 12) / 12 -
3 * ((date.year + 4900 + monthMinus14Over12) / 100) / 4;
if (!state->flags.quiet)
{
printf(
"\tJulian date at midday on %d-%.2d-%.2d is %d\n",
date.year,
date.month,
date.day,
julianDate);
}
return julianDate;
}
static GregorianDate date(int year, int month, int day)
{
GregorianDate date = {year, month, day};
return date;
}
static void calculateSunriseOn(SunState *state, GregorianDate date)
{
if (!state->flags.quiet)
{
printf(
"Calculating sunrise on %d-%.2d-%.2d:\n",
date.year,
date.month,
date.day);
}
state->eventHeight = DEGREES_0_Q1_15;
state->flags.addCorrection = ~0;
calculateEventOn(state, date);
}
static void calculateEventOn(SunState *state, GregorianDate date)
{
state->julianDate = calculateJulianDateAtMidday(state, date);
calculateDaysSinceEpoch(state);
calculateMeanLongitudeIncludingAberration(state);
calculateMeanAnomaly(state);
calculateEquatorialCentreCorrection(state);
calculateSunEclipticLongitude(state);
calculateEquationOfTime(state);
calculateGreenwichHourAngle(state);
calculateObliquityOfTheEcliptic(state);
calculateSunDeclination(state);
calculateCorrection(state);
calculateEventTime(state);
}
static void calculateDaysSinceEpoch(SunState *state)
{
state->daysSinceEpoch =
(unsigned short) state->julianDate - state->epochAsJulianDate;
if (!state->flags.quiet)
printf("\tDays since the Epoch: %hu\n", state->daysSinceEpoch);
}
static void calculateMeanLongitudeIncludingAberration(SunState *state)
{
/*
L = 280.46 + 36000.77 * days / 36525
= 280 + 0.46 + 0.77 * days / 36525 + 36000 * days / 36525
Units: degrees (Q16.16)
Maximum: 0x8db93a4c
*/
Accumulator accumulator;
accumulator = state->daysSinceEpoch * LITERAL_0_77_Q0_16;
accumulator /= 36525;
accumulator += state->daysSinceEpoch * LITERAL_36000_OVER_36525_Q0_16;
accumulator += LITERAL_0_46_Q0_16;
accumulator += 280 << 16;
state->meanLongitudeIncludingAberration = accumulator;
if (!state->flags.quiet)
{
printf(
"\tMean Longitude (including aberration): 0x%.8x (%.8g deg)\n",
state->meanLongitudeIncludingAberration,
state->meanLongitudeIncludingAberration / 65536.0);
}
}
static void calculateMeanAnomaly(SunState *state)
{
/*
G = 357.528 + 35999.05 * days / 36525
= 357 + 0.528 + 0.05 * days / 36525 + 35999 * days / 36525
Units: degrees (converted to Q1.15 angle units)
Maximum: 0x8e047608
*/
Accumulator accumulator;
accumulator = state->daysSinceEpoch * LITERAL_0_05_Q0_16;
accumulator /= 36525;
accumulator += state->daysSinceEpoch * LITERAL_35999_OVER_36525_Q0_16;
accumulator += LITERAL_0_528_Q0_16;
accumulator += 357 << 16;
state->meanAnomaly = degreesToUnits(accumulator, 16);
if (!state->flags.quiet)
{
printf(
"\tMean Anomaly: 0x%.8x (%.8g deg) -> 0x%.4hx\n",
accumulator,
accumulator / 65536.0,
state->meanAnomaly);
}
}
static FixedQ1_15 degreesToUnits(Accumulator phi, int q)
{
Accumulator circleMultiple = phi / 360;
circleMultiple >>= q;
circleMultiple *= 360;
circleMultiple <<= q;
phi += -circleMultiple;
phi /= (q == 16 ? 360 : 180);
return (FixedQ1_15) phi;
}
static void calculateEquatorialCentreCorrection(SunState *state)
{
/* TODO: SINCE G IS NOW Q1.15, CAN WE JUST TAKE sin(2G) INSTEAD OF
MODIFYING CORDIC TO OUTPUT BOTH SINE AND COSINE TO USE THE
MULTIPLICATION BY IDENTITY ? SINCE IF 2G OVERFLOWS, WE ONLY
NEED THE 16 LSbs ANYWAY - WE GET FREE CIRCLE MODULO (AND A
LEFT-SHIFT BY ONE PLACE IS QUICK)
CONSIDER THE cosc CALCULATION THAT REQUIRES SINE AND COSINE OF
TWO TERMS, HOWEVER - THE TIME OVERHEAD IS A LOT GREATER */
/*
ec = 1.915 * sin(G) + 0.02 * sin(2 * G)
= 1.915 * sin(G) + 0.02 * (2 * sin(G) * cos(G))
= sin(G) + 0.915 * sin(G) + 0.04 * sin(G) * cos(G)
Units: degrees (Q17.15)
*/
FixedQ1_15 sinG = sine(state->meanAnomaly);
FixedQ1_15 cosG = cosine(state->meanAnomaly);
FixedQ1_15 sinCosProduct = ((int) sinG * cosG) >> 15;
Accumulator accumulator = sinG;
accumulator <<= 15;
accumulator += LITERAL_0_915_Q1_15 * sinG;
accumulator += LITERAL_0_04_Q1_15 * sinCosProduct;
accumulator >>= 15;
state->equatorialCentreCorrection = accumulator;
if (!state->flags.quiet)
{
printf(
"\tEquatorial Centre Correction: 0x%.8x (%.8g deg)\n",
state->equatorialCentreCorrection,
((double) state->equatorialCentreCorrection) / (1 << 15));
}
}
static FixedQ1_15 sine(FixedQ1_15 phi)
{
return doubleToFixedQ1_15(sin(phi / 32768.0 * M_PI));
}
static FixedQ1_15 doubleToFixedQ1_15(double x)
{
double value = x * 32768 + 0.5;
if (value > 32767)
return 0x7fff;
if (value < -32768)
return (FixedQ1_15) 0x8000;
return (FixedQ1_15) value;
}
static FixedQ1_15 cosine(FixedQ1_15 phi)
{
return doubleToFixedQ1_15(cos(phi / 32768.0 * M_PI));
}
static void calculateSunEclipticLongitude(SunState *state)
{
/*
lambda = L + ec
Units: degrees (converted to Q1.15 angle units)
*/
Accumulator accumulator = state->meanLongitudeIncludingAberration >> 1;
accumulator += state->equatorialCentreCorrection;
state->sunEclipticLongitude = degreesToUnits(accumulator, 15);
if (!state->flags.quiet)
{
printf(
"\tEcliptic Longitude of the Sun: 0x%.8x (%.8g deg) -> 0x%.4hx\n",
accumulator,
accumulator / 32768.0,
state->sunEclipticLongitude);
}
}
static void calculateEquationOfTime(SunState *state)
{
/*
E = -ec + 2.466 * sin(2 * lambda) - 0.053 * sin(4 * lambda)
= -ec + sin(2 * lambda) + sin(2 * lambda) + 0.466 * sin(2 * lambda) -
0.053 * sin(4 * lambda)
Units: degrees (converted to Q1.15 angle units)
*/
FixedQ1_15 sin2Lambda = sine(state->sunEclipticLongitude << 1);
FixedQ1_15 sin4Lambda = sine(state->sunEclipticLongitude << 2);
Accumulator accumulatorA = LITERAL_0_466_Q1_15 * sin2Lambda;
Accumulator accumulatorB = LITERAL_0_053_Q1_15 * sin4Lambda;
accumulatorA >>= 15;
accumulatorB >>= 15;
accumulatorA += sin2Lambda;
accumulatorA += sin2Lambda;
accumulatorA += -state->equatorialCentreCorrection;
accumulatorA += -accumulatorB;
state->equationOfTime = degreesToUnits(accumulatorA, 15);
if (!state->flags.quiet)
{
printf(
"\tEquation of Time: 0x%.8x (%.8g deg) -> 0x%.4hx\n",
accumulatorA,
accumulatorA / 32768.0,
state->equationOfTime);
}
}
static void calculateGreenwichHourAngle(SunState *state)
{
/*
GHA = UTo - 180 + E
Units: degrees (converted to Q1.15 angle units)
*/
Accumulator accumulator = state->eventTime;
accumulator += state->equationOfTime;
accumulator += -DEGREES_180_Q1_15;
state->greenwichHourAngle = (FixedQ1_15) (accumulator & 0xffff);
if (!state->flags.quiet)
{
printf(
"\tGrenwich Hour Angle: 0x%.8x (%.8g deg) -> 0x%.4hx\n",
accumulator,
180 * state->greenwichHourAngle / 32768.0,
state->greenwichHourAngle);
}
}
static void calculateObliquityOfTheEcliptic(SunState *state)
{
/*
Obl = 23.4393 - 0.013 * days / 36525
Units: degrees (converted to Q1.15 angle units)
*/
Accumulator accumulatorA = (23 << 15) + LITERAL_0_4393_Q1_15;
Accumulator accumulatorB = LITERAL_0_013_Q1_15 * state->daysSinceEpoch;
accumulatorB /= 36525;
accumulatorA += -accumulatorB;
state->obliquityOfTheEcliptic = degreesToUnits(accumulatorA, 15);
if (!state->flags.quiet)
{
printf(
"\tObliquity of the Ecliptic: 0x%.8x (%.8g deg) -> 0x%.4hx\n",
accumulatorA,
accumulatorA / 32768.0,
state->obliquityOfTheEcliptic);
}
}
static void calculateSunDeclination(SunState *state)
{
/*
delta = asin(sin(Obl) * sin(lambda))
Units: degrees (converted to Q1.15 angle units)
*/
FixedQ1_15 sinObl = sine(state->obliquityOfTheEcliptic);
FixedQ1_15 sinLambda = sine(state->sunEclipticLongitude);
Accumulator accumulator = sinObl * sinLambda;
accumulator >>= 15;
state->sunDeclination = arcSine((FixedQ1_15) (accumulator & 0xffff));
if (!state->flags.quiet)
{
printf(
"\tDeclination of the Sun: 0x%.4hx (%.8g deg)\n",
state->sunDeclination,
180 * state->sunDeclination / 32768.0);
}
}
static FixedQ1_15 arcSine(FixedQ1_15 x)
{
return (FixedQ1_15) (32768 * asin(x / 32768.0) / M_PI);
}
static void calculateCorrection(SunState *state)
{
/*
cosc = (sin(h) - sin(phi) * sin(delta)) / (cos(phi) * cos(delta))
if cosc > 1 then correction = 0 degrees
if cosc < -1 then correction = 180 degrees
if cost >= -1 && cosc <= 1 then correction = acos(cosc)
Units: degrees (converted to Q1.15 angle units)
*/
FixedQ1_15 sinH = sine(state->eventHeight);
FixedQ1_15 sinPhi = sine(state->latitude);
FixedQ1_15 cosPhi = cosine(state->latitude);
FixedQ1_15 sinDelta = sine(state->sunDeclination);
FixedQ1_15 cosDelta = cosine(state->sunDeclination);
Accumulator accumulatorA = sinPhi * sinDelta;
Accumulator accumulatorB = cosPhi * cosDelta;
accumulatorA >>= 15;
accumulatorB >>= 15;
accumulatorA *= -1;
accumulatorA += sinH;
accumulatorA <<= 15;
accumulatorA /= (FixedQ1_15) (accumulatorB & 0xffff);
if ((accumulatorA & 0x80000000) && (accumulatorA & 0xffff0000) != 0xffff0000)
state->correction = DEGREES_180_Q1_15;
else if (!(accumulatorA & 0x80000000) && (accumulatorA & 0x7fff0000))
state->correction = DEGREES_0_Q1_15;
else
state->correction = arcCosine((FixedQ1_15) (accumulatorA & 0xffff));
if (!state->flags.quiet)
{
printf(
"\tCorrection: 0x%.4hx (%.8g deg)\n",
state->correction,
180 * state->correction / 32768.0);
}
}
static FixedQ1_15 arcCosine(FixedQ1_15 x)
{
return (FixedQ1_15) (32768 * acos(x / 32768.0) / M_PI);
}
static void calculateEventTime(SunState *state)
{
Accumulator accumulator = state->correction;
if (!state->flags.addCorrection)
accumulator *= -1;
accumulator += state->greenwichHourAngle;
accumulator += state->longitude;
accumulator *= -1;
accumulator += state->eventTime;
state->eventTime = (FixedQ1_15) (accumulator & 0xffff);
if (!state->flags.quiet)
{
printf(
"\tEvent Time: 0x%.8x (%.8g deg) -> 0x%.4hx (%.8g deg)\n",
accumulator,
180 * accumulator / 32768.0,
state->eventTime,
180 * state->eventTime / 32768.0);
}
}
static void calculateSunsetOn(SunState *state, GregorianDate date)
{
if (!state->flags.quiet)
{
printf(
"Calculating sunset on %d-%.2d-%.2d:\n",
date.year,
date.month,
date.day);
}
state->eventHeight = DEGREES_0_Q1_15;
state->flags.addCorrection = 0;
calculateEventOn(state, date);
}
<file_sep>/src/utilities/sunrise-sunset/lookup/lookup.c
/*
Hacking playground for generating lookups for the Sunrise / Sunset times.
The lookup is a selection of accurate values computed using the algorithm
documented at:
http://www.stargazing.net/kepler/sunrise.html
Linear interpolation is used to calculate values across latitudes and days
that do not have entries in the lookup table.
*/
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define DEG2RAD(phi) (double) ((phi) / 180 * M_PI)
#define LOOKUP_STEP 6
#define LOOKUP_LENGTH (366 / LOOKUP_STEP)
#define LOOKUP_LATITUDE 55
#define LOOKUP_LATITUDE_NORTH (LOOKUP_LATITUDE + 5)
#define LOOKUP_LATITUDE_SOUTH (LOOKUP_LATITUDE - 5)
#define LOOKUP_LONGITUDE 0
#define TO_HOUR(x) ((int) ((x) * 24))
#define TO_MINUTE(x) ((int) (((x) * 24 - TO_HOUR(x)) * 60 + 0.5))
typedef short FixedQ1_15;
typedef unsigned short FixedQ0_16;
typedef struct
{
int year : 16;
int month : 8;
int day : 8;
} GregorianDate;
typedef struct
{
double day;
double latitude;
double longitude;
double eventHeight;
double correctionSign;
double eventTime;
} SunEventState;
typedef struct
{
unsigned int sunriseReferenceMinute : 11;
int sunriseMinuteNorth : 8;
int sunriseMinuteSouth : 8;
unsigned int sunsetReferenceMinute : 11;
int sunsetMinuteNorth : 8;
int sunsetMinuteSouth : 8;
} LookupEntry;
typedef struct
{
unsigned int sunriseReferenceMinute;
int sunriseMinuteOffset;
unsigned int sunsetReferenceMinute;
int sunsetMinuteOffset;
} InterpolatedLookupEntry;
static const GregorianDate epoch = {0, 1, 1};
static LookupEntry lookupTable[LOOKUP_LENGTH];
static void initialiseLookupTable(void);
static unsigned short fractionOfDayToMinute(double fraction);
static double sunriseTime(int day, double latitude, double longitude);
static void sunEventTime(SunEventState *const state);
static void sunEventTimeIteration(SunEventState *const state);
static double sunsetTime(int day, double latitude, double longitude);
static int writeLookupTableForOctave(
const char *const filename,
double latitude,
double longitude);
static double lookupSunriseTime(int day, double latitude, double longitude);
static InterpolatedLookupEntry interpolatedLookupNorth(int day);
static InterpolatedLookupEntry interpolatedLookupSouth(int day);
static int dayOfYearFromDayOfCentury(int day);
static GregorianDate daysSinceEpochToDate(int day);
static GregorianDate daysToDate(int day);
static int dateToDays(const GregorianDate date);
static int daysSinceEpoch(const GregorianDate date);
static short latitudeInterpolationMultiplier(double latitude);
static short longitudeAdjustmentMinutes(double longitude);
static double lookupSunsetTime(int day, double latitude, double longitude);
static int writeLookupTableForAssembler(
const char *const filename,
double latitude,
double longitude);
int main(int argc, char *argv[])
{
double latitude = 51.509865;
double longitude = -0.118092;
initialiseLookupTable();
if (argc == 4)
{
double sunrise, sunset;
int day;
int success =
sscanf(argv[1], "%d", &day) +
sscanf(argv[2], "%lg", &latitude) +
sscanf(argv[3], "%lg", &longitude);
if (success != 3)
{
printf(
"Unable to parse arguments. "
"Expected day, latitude and longitude.\n");
return 1;
}
printf("For %g,%g on day %d:\n", latitude, longitude, day);
sunrise = sunriseTime(day, latitude, longitude);
sunset = sunsetTime(day, latitude, longitude);
printf(
"Actual: sunrise=%.2d:%.2d, sunset=%.2d:%.2d\n",
TO_HOUR(sunrise),
TO_MINUTE(sunrise),
TO_HOUR(sunset),
TO_MINUTE(sunset));
sunrise = lookupSunriseTime(day, latitude, longitude);
sunset = lookupSunsetTime(day, latitude, longitude);
printf(
"Lookup: sunrise=%.2d:%.2d, sunset=%.2d:%.2d\n",
TO_HOUR(sunrise),
TO_MINUTE(sunrise),
TO_HOUR(sunset),
TO_MINUTE(sunset));
return 0;
}
return
writeLookupTableForOctave("SunEventsTables.txt", latitude, longitude) +
writeLookupTableForAssembler("SunEventsTables.S", latitude, longitude);
}
static void initialiseLookupTable(void)
{
for (int i = 0, day = 0; i < LOOKUP_LENGTH; i++, day += LOOKUP_STEP)
{
lookupTable[i].sunriseReferenceMinute = fractionOfDayToMinute(
sunriseTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE));
lookupTable[i].sunriseMinuteNorth = fractionOfDayToMinute(
sunriseTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE)) -
lookupTable[i].sunriseReferenceMinute;
lookupTable[i].sunriseMinuteSouth = fractionOfDayToMinute(
sunriseTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE)) -
lookupTable[i].sunriseReferenceMinute;
lookupTable[i].sunsetReferenceMinute = fractionOfDayToMinute(
sunsetTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE));
lookupTable[i].sunsetMinuteNorth = fractionOfDayToMinute(
sunsetTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE)) -
lookupTable[i].sunsetReferenceMinute;
lookupTable[i].sunsetMinuteSouth = fractionOfDayToMinute(
sunsetTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE)) -
lookupTable[i].sunsetReferenceMinute;
}
}
static unsigned short fractionOfDayToMinute(double fraction)
{
unsigned short minute = (unsigned short) (fraction * 24 * 60 + 0.5);
return minute;
}
static double sunriseTime(int day, double latitude, double longitude)
{
SunEventState state = {
day,
DEG2RAD(latitude),
DEG2RAD(longitude),
DEG2RAD(0),
1,
M_PI
};
sunEventTime(&state);
return state.eventTime / (2 * M_PI);
}
static void sunEventTime(SunEventState *const state)
{
for (int i = 0; i < 5; i++)
sunEventTimeIteration(state);
}
static void sunEventTimeIteration(SunEventState *const state)
{
/* http://www.stargazing.net/kepler/sunrise.html */
double t = (state->day + (state->eventTime / (2 * M_PI))) / 36525.0;
double L = 280.46 + 36000.77 * t;
double G = 357.528 + 35999.05 * t;
double ec = 1.915 * sin(DEG2RAD(G)) + 0.02 * sin(DEG2RAD(2 * G));
double lambda = L + ec;
double E =
-ec + 2.466 * sin(DEG2RAD(2 * lambda)) -
0.053 * sin(DEG2RAD(4 * lambda));
double GHA = state->eventTime - M_PI + DEG2RAD(E);
double obl = 23.4393 - 0.0130 * t;
double delta = asin(sin(DEG2RAD(obl)) * sin(DEG2RAD(lambda)));
double coscNumerator =
sin(state->eventHeight) - sin(state->latitude) * sin(delta);
double coscDenominator = cos(state->latitude) * cos(delta);
double cosc = coscNumerator / coscDenominator;
double correction = (cosc > 1 ? 0 : (cosc < -1 ? M_PI : acos(cosc)));
state->eventTime -=
GHA + state->longitude + correction * state->correctionSign;
}
static double sunsetTime(int day, double latitude, double longitude)
{
SunEventState state = {
day,
DEG2RAD(latitude),
DEG2RAD(longitude),
DEG2RAD(0),
-1,
M_PI
};
sunEventTime(&state);
return state.eventTime / (2 * M_PI);
}
static int writeLookupTableForOctave(
const char *const filename,
double latitude,
double longitude)
{
FILE *fd = fopen(filename, "wt");
if (!fd)
{
printf("Unable to open %s for writing.\n", filename);
return 1;
}
printf("Writing table to %s...\n", filename);
for (int day = 0; day < 36525; day++)
{
double eventTimes[] = {
sunriseTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE),
lookupSunriseTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE),
sunriseTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE),
lookupSunriseTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE),
sunriseTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE),
lookupSunriseTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE),
sunsetTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE),
lookupSunsetTime(day, LOOKUP_LATITUDE, LOOKUP_LONGITUDE),
sunsetTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE),
lookupSunsetTime(day, LOOKUP_LATITUDE_NORTH, LOOKUP_LONGITUDE),
sunsetTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE),
lookupSunsetTime(day, LOOKUP_LATITUDE_SOUTH, LOOKUP_LONGITUDE),
sunriseTime(day, latitude, longitude),
lookupSunriseTime(day, latitude, longitude),
sunsetTime(day, latitude, longitude),
lookupSunsetTime(day, latitude, longitude)
};
fprintf(
fd,
"%d"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\n",
day,
eventTimes[0],
eventTimes[1],
eventTimes[2],
eventTimes[3],
eventTimes[4],
eventTimes[5],
eventTimes[6],
eventTimes[7],
eventTimes[8],
eventTimes[9],
eventTimes[10],
eventTimes[11],
eventTimes[12],
eventTimes[13],
eventTimes[14],
eventTimes[15]);
}
fclose(fd);
return 0;
}
static double lookupSunriseTime(int day, double latitude, double longitude)
{
InterpolatedLookupEntry interpolated = latitude >= LOOKUP_LATITUDE
? interpolatedLookupNorth(day)
: interpolatedLookupSouth(day);
short latitudeMultiplier = latitudeInterpolationMultiplier(latitude);
short offset = (latitudeMultiplier * interpolated.sunriseMinuteOffset) >> 8;
unsigned short minutes =
interpolated.sunriseReferenceMinute +
offset +
longitudeAdjustmentMinutes(longitude);
return minutes / (24.0 * 60.0);
}
static InterpolatedLookupEntry interpolatedLookupNorth(int day)
{
int dayOfYear = dayOfYearFromDayOfCentury(day);
int index = dayOfYear / LOOKUP_STEP;
int offset = dayOfYear % LOOKUP_STEP;
LookupEntry *first = &lookupTable[index];
LookupEntry *second = &lookupTable[
(index + 1) < LOOKUP_LENGTH ? index + 1 : 0];
InterpolatedLookupEntry interpolated = {
first->sunriseReferenceMinute +
(second->sunriseReferenceMinute - first->sunriseReferenceMinute) *
offset / LOOKUP_STEP,
first->sunriseMinuteNorth +
(second->sunriseMinuteNorth - first->sunriseMinuteNorth) *
offset / LOOKUP_STEP,
first->sunsetReferenceMinute +
(second->sunsetReferenceMinute - first->sunsetReferenceMinute) *
offset / LOOKUP_STEP,
first->sunsetMinuteNorth +
(second->sunsetMinuteNorth - first->sunsetMinuteNorth) *
offset / LOOKUP_STEP
};
return interpolated;
}
static int dayOfYearFromDayOfCentury(int day)
{
GregorianDate date = daysSinceEpochToDate(day);
GregorianDate startOfYear = {date.year, 1, 1};
int dayOfYear = day - daysSinceEpoch(startOfYear);
if (dayOfYear < 0 || dayOfYear > 365)
{
printf(
"!!! ERROR !!! THIS SHOULDN'T HAPPEN; "
"dayOfYear = %d, date = %.4d-%.2d-%.2d\n",
dayOfYear,
date.year,
date.month,
date.day);
return 0;
}
return dayOfYear;
}
static GregorianDate daysSinceEpochToDate(int day)
{
return daysToDate(dateToDays(epoch) + day);
}
static GregorianDate daysToDate(int day)
{
/* https://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
/* https://alcor.concordia.ca/~gpkatch/gdate-method.html */
GregorianDate date;
int mi, ddd;
date.year = (10000 * day + 14780) / 3652425;
ddd = day - (
365 * date.year +
date.year / 4 -
date.year / 100 +
date.year / 400);
if (ddd < 0)
{
date.year--;
ddd = day - (
365 * date.year +
date.year / 4 -
date.year / 100 +
date.year / 400);
}
mi = (100 * ddd + 52) / 3060;
date.month = (mi + 2) % 12 + 1;
date.year = date.year + (mi + 2) / 12;
date.day = ddd - (mi * 306 + 5) / 10 + 1;
return date;
}
static int dateToDays(const GregorianDate date)
{
/* https://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
/* https://alcor.concordia.ca/~gpkatch/gdate-method.html */
int month = (date.month + 9) % 12;
int year = date.year - month / 10;
int day = date.day;
return
365 * year + year / 4 - year / 100 + year / 400 +
(month * 306 + 5) / 10 + (day - 1);
}
static int daysSinceEpoch(const GregorianDate date)
{
return dateToDays(date) - dateToDays(epoch);
}
static InterpolatedLookupEntry interpolatedLookupSouth(int day)
{
int dayOfYear = dayOfYearFromDayOfCentury(day);
int index = dayOfYear / LOOKUP_STEP;
int offset = dayOfYear % LOOKUP_STEP;
LookupEntry *first = &lookupTable[index];
LookupEntry *second = &lookupTable[
(index + 1) < LOOKUP_LENGTH ? index + 1 : 0];
InterpolatedLookupEntry interpolated = {
first->sunriseReferenceMinute +
(second->sunriseReferenceMinute - first->sunriseReferenceMinute) *
offset / LOOKUP_STEP,
first->sunriseMinuteSouth +
(second->sunriseMinuteSouth - first->sunriseMinuteSouth) *
offset / LOOKUP_STEP,
first->sunsetReferenceMinute +
(second->sunsetReferenceMinute - first->sunsetReferenceMinute) *
offset / LOOKUP_STEP,
first->sunsetMinuteSouth +
(second->sunsetMinuteSouth - first->sunsetMinuteSouth) *
offset / LOOKUP_STEP
};
return interpolated;
}
static short latitudeInterpolationMultiplier(double latitude)
{
const int degreeResolution = 10;
short difference = (short) (latitude >= LOOKUP_LATITUDE
? (degreeResolution * (latitude - LOOKUP_LATITUDE) + 0.5)
: (degreeResolution * (LOOKUP_LATITUDE - latitude) + 0.5));
short multiplier =
(difference << 8) /
((LOOKUP_LATITUDE_NORTH - LOOKUP_LATITUDE) * degreeResolution);
return multiplier;
}
static short longitudeAdjustmentMinutes(double longitude)
{
const int degreeResolution = 10;
short difference = (short) (
(LOOKUP_LONGITUDE - longitude) * degreeResolution + 0.5);
short minutes = (difference * 4) / 10;
short remainder = (difference * 4) % 10;
return minutes + (remainder >= 5 ? 1 : remainder <= -5 ? -1 : 0);
}
static double lookupSunsetTime(int day, double latitude, double longitude)
{
InterpolatedLookupEntry interpolated = latitude >= LOOKUP_LATITUDE
? interpolatedLookupNorth(day)
: interpolatedLookupSouth(day);
short latitudeMultiplier = latitudeInterpolationMultiplier(latitude);
short offset = (latitudeMultiplier * interpolated.sunsetMinuteOffset) >> 8;
unsigned short minutes =
interpolated.sunsetReferenceMinute +
offset +
longitudeAdjustmentMinutes(longitude);
return minutes / (24.0 * 60.0);
}
static int writeLookupTableForAssembler(
const char *const filename,
double latitude,
double longitude)
{
FILE *fd = fopen(filename, "wt");
if (!fd)
{
printf("Unable to open %s for writing.\n", filename);
return 1;
}
printf("Writing table to %s...\n", filename);
fprintf(fd, "\tpsect SunriseSunset,class=CODE,noexec,pure,delta=2,optim=\n");
fprintf(fd, "\tglobal _sunriseLookupTable\n");
fprintf(fd, "\tglobal _sunsetLookupTable\n\n");
fprintf(fd, "_sunriseLookupTable:\n");
for (int i = 0; i < LOOKUP_LENGTH; i++)
{
LookupEntry *entry = &lookupTable[i];
fprintf(
fd,
"\tdw 0x%.4hx, 0x%.4hx\n",
(unsigned short) (
((entry->sunriseReferenceMinute & 0x7c0) << 2) |
(entry->sunriseMinuteNorth & 0xff)),
(unsigned short) (
((entry->sunriseReferenceMinute & 0x03f) << 8) |
(entry->sunriseMinuteSouth & 0xff)));
}
fprintf(fd, "\n_sunsetLookupTable:\n");
for (int i = 0; i < LOOKUP_LENGTH; i++)
{
LookupEntry *entry = &lookupTable[i];
fprintf(
fd,
"\tdw 0x%.4hx, 0x%.4hx\n",
(unsigned short) (
((entry->sunsetReferenceMinute & 0x7c0) << 2) |
(entry->sunsetMinuteNorth & 0xff)),
(unsigned short) (
((entry->sunsetReferenceMinute & 0x03f) << 8) |
(entry->sunsetMinuteSouth & 0xff)));
}
fprintf(fd, "\n\tend\n");
fclose(fd);
return 0;
}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Mock_NearScheduler.h"
#include "Platform/VoltageRegulator.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
const struct Event eventEmptyArgs = { };
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_voltageRegulatorInitialise_called_expectEnablePinIsOutput(void)
{
TRISB = anyByteWithMaskSet(_TRISB_TRISB2_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(TRISBbits.TRISB2);
}
void test_voltageRegulatorInitialise_called_expectEnablePinIsDigital(void)
{
ANSELB = anyByteWithMaskSet(_ANSELB_ANSB2_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(ANSELBbits.ANSB2);
}
void test_voltageRegulatorInitialise_called_expectEnablePinIsLow(void)
{
LATB = anyByteWithMaskSet(_LATB_LATB2_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(LATBbits.LATB2);
}
void test_voltageRegulatorInitialise_called_expectVmcuSelPinIsOutput(void)
{
TRISB = anyByteWithMaskSet(_TRISB_TRISB0_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(TRISBbits.TRISB0);
}
void test_voltageRegulatorInitialise_called_expectVmcuSelPinIsDigital(void)
{
ANSELB = anyByteWithMaskSet(_ANSELB_ANSB0_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(ANSELBbits.ANSB0);
}
void test_voltageRegulatorInitialise_called_expectVmcuSelPinIsLow(void)
{
LATB = anyByteWithMaskSet(_LATB_LATB0_MASK);
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(LATBbits.LATB0);
}
void test_voltageRegulatorInitialise_called_expectNonVoltageRegulatorTrisBitsAreUnchanged(void)
{
static const uint8_t usedPins = _TRISB_TRISB0_MASK | _TRISB_TRISB2_MASK;
TRISB = anyByte();
uint8_t expectedTrisb = TRISB | usedPins;
voltageRegulatorInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedTrisb, TRISB | usedPins);
}
void test_voltageRegulatorInitialise_called_expectNonVoltageRegulatorAnselBitsAreUnchanged(void)
{
static const uint8_t usedPins = _ANSELB_ANSB0_MASK | _ANSELB_ANSB2_MASK;
ANSELB = anyByte();
uint8_t expectedAnselb = ANSELB | usedPins;
voltageRegulatorInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedAnselb, ANSELB | usedPins);
}
void test_voltageRegulatorInitialise_called_expectNonVoltageRegulatorLatBitsAreUnchanged(void)
{
static const uint8_t usedPins = _LATB_LATB0_MASK | _LATB_LATB2_MASK;
LATB = anyByte();
uint8_t expectedLatb = LATB | usedPins;
voltageRegulatorInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedLatb, LATB | usedPins);
}
<file_sep>/src/firmware/tests/Door/TestDoorOpeningOnMotorStopped1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsOpen_expectOpenedStateWithUnchangedTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Opening,
.transition = DoorTransition_Open
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opened, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectOpenedStateWithUnchangedTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Opening,
.transition = DoorTransition_Unchanged
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opened, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpening_expectFaultStateWithUnmodifiedTransition(void)
{
uint8_t initialTransition = anyByte();
struct DoorStateWithContext state =
{
.current = DoorState_Opening,
.transition = initialTransition
};
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(initialTransition, state.transition, "T");
}
void test_motorStopped_onPublishedWithCurrentLimitFault_expectDoorAbortedIsPublishedWithJammedFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
static const struct MotorStopped jammed =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .currentLimited = 1 }
};
publishMotorStopped(&jammed);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithEncoderOverflowFault_expectDoorAbortedIsPublishedWithLineTooLongFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
static const struct MotorStopped tooLong =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .encoderOverflow = 1 }
};
publishMotorStopped(&tooLong);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithEncoderTimeoutFault_expectDoorAbortedIsPublishedWithEncoderBrokenFlag(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
static const struct MotorStopped timeout =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .encoderTimeout = 1 }
};
publishMotorStopped(&timeout);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_motorStopped_onPublishedWithCurrentUnknownFault_expectDoorAbortedIsPublishedWithNoFaultFlags(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
struct MotorStopped unknown =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .all = anyUnknownMotorFault() }
};
publishMotorStopped(&unknown);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedArgs[0]->fault.all, "F");
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfOpen_expectDoorOpenedIsPublished(void)
{
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
mockOnDoorOpened();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorOpenedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorOpenedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfUnchanged_expectDoorOpenedIsPublished(void)
{
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
mockOnDoorOpened();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorOpenedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorOpenedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaultsAndTransitionOfClose_expectDoorOpenedIsPublished(void)
{
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
mockOnDoorOpened();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorOpenedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorOpenedArgs[0]);
}
void test_motorStopped_onPublishedWithNoFaults_expectDoorAbortedIsNotPublished(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
publishMotorStoppedWithNoFaults();
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedCalls, "Calls");
}
<file_sep>/src/firmware/src/Platform/Buttons.c
#include <xc.h>
#include <stdint.h>
#include "Event.h"
#include "PowerManagement.h"
#include "NearScheduler.h"
#include "Buttons.h"
#define BUTTON1_PORT_MASK _PORTA_RA0_MASK
#define BUTTON2_PORT_MASK _PORTA_RA1_MASK
#define BUTTON_PORT_MASK (BUTTON1_PORT_MASK | BUTTON2_PORT_MASK)
#define BUTTON_STATE_NOW (PORTA & BUTTON_PORT_MASK)
static void onWokenFromSleep(const struct Event *event);
static void onButtonsStoppedBouncing(void *state);
static uint8_t buttonStateSampled;
void buttonsInitialise(void)
{
PMD0bits.IOCMD = 0;
ANSELA &= ~BUTTON_PORT_MASK;
PIE0bits.IOCIE = 1;
IOCAN |= BUTTON_PORT_MASK;
IOCAP |= BUTTON_PORT_MASK;
buttonStateSampled = BUTTON_STATE_NOW;
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
}
static void onWokenFromSleep(const struct Event *event)
{
if (!PIR0bits.IOCIF)
return;
IOCAF = 0;
static const struct NearSchedule onButtonsStoppedBouncingSchedule =
{
.ticks = MS_TO_TICKS(20),
.handler = &onButtonsStoppedBouncing
};
nearSchedulerAddOrUpdate(&onButtonsStoppedBouncingSchedule);
}
static void onButtonsStoppedBouncing(void *state)
{
uint8_t buttonsChanged = buttonStateSampled ^ BUTTON_STATE_NOW;
if (!buttonsChanged)
return;
if (buttonsChanged & BUTTON1_PORT_MASK)
{
static const struct ButtonsPressed button1EventArgs = { .mask = 0x01 };
if ((buttonStateSampled & BUTTON1_PORT_MASK) == 0)
eventPublish(BUTTONS_RELEASED, &button1EventArgs);
else
eventPublish(BUTTONS_PRESSED, &button1EventArgs);
}
if (buttonsChanged & BUTTON2_PORT_MASK)
{
static const struct ButtonsPressed button2EventArgs = { .mask = 0x02 };
if ((buttonStateSampled & BUTTON2_PORT_MASK) == 0)
eventPublish(BUTTONS_RELEASED, &button2EventArgs);
else
eventPublish(BUTTONS_PRESSED, &button2EventArgs);
}
buttonStateSampled ^= buttonsChanged;
}
<file_sep>/src/firmware/tests/Door/TestDoorFindBottomWaitingForEnabledMotorOnMotorEnabled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotor_expectFindBottomStateWithUnchangedTransition(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsEnabled();
publishMotorEnabled();
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(anyTransition, state.transition, "T");
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotorAndMotorIsDisabled_expectUnknownStateWithUnchangedTransition(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsDisabled();
publishMotorEnabled();
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Unknown, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(anyTransition, state.transition, "T");
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotor_expectMotorCurrentLimitIsNoLoad(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsEnabled();
publishMotorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotorAndMotorIsDisabled_expectMotorCurrentLimitIsNotModified(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsDisabled();
publishMotorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotor_expectMotorIsTurnedOnAfterCurrentLimitIsSet(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsEnabled();
publishMotorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_TRUE_MESSAGE(motorOnSequence > motorLimitIsNoLoadSequence, "Seq");
TEST_ASSERT_EQUAL_INT16_MESSAGE(-PULSES_PER_10CM, motorOnArgs[0], "Arg");
}
void test_motorEnabled_onPublishedWhenStateIsFindBottomWaitingForEnabledMotorAndMotorIsDisabled_expectMotorIsNotTurnedOn(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom_WaitingForEnabledMotor, anyTransition);
stubMotorIsDisabled();
publishMotorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorOnCalls, "Calls");
}
<file_sep>/src/firmware/tests/Platform/PwmTimer/TestPwmTimerInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/PwmTimer.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/PwmTimer.c")
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_pwmTimerInitialise_called_expectTimer2ModuleIsEnabled(void)
{
PMD1 = anyByteWithMaskSet(_PMD1_TMR2MD_MASK);
uint8_t originalPmd1 = PMD1;
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd1 & ~_PMD1_TMR2MD_MASK, PMD1);
}
void test_pwmTimerInitialise_called_expectTimerClockSourceIsInstructionClock(void)
{
T2CLKCON = anyByte();
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(1, T2CLKCON);
}
void test_pwmTimerInitialise_called_expectTimerIsDisabled(void)
{
T2CON = anyByteWithMaskSet(_T2CON_ON_MASK);
pwmTimerInitialise();
TEST_ASSERT_FALSE(T2CONbits.ON);
}
void test_pwmTimerInitialise_called_expectTimerPrescalerOfTwo(void)
{
T2CON = anyByte();
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(
0b001 << _T2CON_CKPS_POSITION,
T2CON & _T2CON_CKPS_MASK);
}
void test_pwmTimerInitialise_called_expectTimerPostscalerOfEight(void)
{
T2CON = anyByte();
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(
7 << _T2CON_OUTPS_POSITION,
T2CON & _T2CON_OUTPS_MASK);
}
void test_pwmTimerInitialise_called_expectNoTimerPrescalerSynchronisation(void)
{
T2HLT = anyByteWithMaskSet(_T2HLT_PSYNC_MASK);
pwmTimerInitialise();
TEST_ASSERT_FALSE(T2HLTbits.PSYNC);
}
void test_pwmTimerInitialise_called_expectTimerActiveEdgeIsRising(void)
{
T2HLT = anyByteWithMaskSet(_T2HLT_CKPOL_MASK);
pwmTimerInitialise();
TEST_ASSERT_FALSE(T2HLTbits.CKPOL);
}
void test_pwmTimerInitialise_called_expectTimerEnableSynchronisation(void)
{
T2HLT = anyByteWithMaskClear(_T2HLT_CKSYNC_MASK);
pwmTimerInitialise();
TEST_ASSERT_TRUE(T2HLTbits.CKSYNC);
}
void test_pwmTimerInitialise_called_expectTimerModeIsFreeRunningSoftwareGated(void)
{
T2HLT = anyByteWithMaskSet(_T2HLT_MODE_MASK);
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(0, T2HLT & _T2HLT_MODE_MASK);
}
void test_pwmTimerInitialise_called_expectPeriodResultsIn62500HzPwm(void)
{
PR2 = anyByte();
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(63, PR2);
}
void test_pwmTimerInitialise_called_expectTimerInterruptFlagIsCleared(void)
{
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR2IF_MASK, PIR4);
}
void test_pwmTimerInitialise_called_expectTimerInterruptDoesNotWakeDeviceFromSleep(void)
{
PIR4 = anyByteWithMaskSet(_PIE4_TMR2IE_MASK);
uint8_t originalPie4 = PIE4;
pwmTimerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie4 & ~_PIE4_TMR2IE_MASK, PIE4);
}
<file_sep>/src/firmware/src/Platform/CalibrationMode.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define __PERIODICMONITOR_EXPOSE_INTERNALS
#include "Event.h"
#include "Nvm.h"
#include "NvmSettings.h"
#include "PowerManagement.h"
#include "HexDigits.h"
#include "PeriodicMonitor.h"
#include "CalibrationMode.h"
#define PPS_IN_RB7 0x0f
#define PPS_OUT_CLKR 0x1b
#define PPS_OUT_UART1TX 0x0f
#define CLKRCON_DUTY_CYCLE_50 (0b10 << _CLKRCON_CLKRDC_POSITION)
#define CLKRCON_NO_DIVIDER 0
#define CLKRCLK_SOURCE_SOSC (0b0101 << _CLKRCLK_CLKRCLK_POSITION)
static void configureReferenceClockModuleFor32768HzCrystalOutput(void);
static void configureUart1AsAsynchronous8bit9600BaudContinuousReception(void);
static void onWokenFromSleep(const struct Event *event);
static void tryToTransmitNextByteToHost(void);
static void onNoCommandReceived(void);
static void transmitToHost(const uint8_t buffer[]);
static void onSampleParametersCommandReceived(void);
static void onRefclkCommandReceived(uint8_t onOff);
static void onReadCommandReceived(const uint8_t addressString[]);
static void onUnknownCommandReceived(void);
static const uint8_t replyResult0[] = {CALIBRATIONMODE_REPLY_RESULT, '0', CALIBRATIONMODE_CMD_EOL};
static const uint8_t replyResult1[] = {CALIBRATIONMODE_REPLY_RESULT, '1', CALIBRATIONMODE_CMD_EOL};
static const uint8_t replyErrorUnknownCommand[] = {CALIBRATIONMODE_REPLY_ERROR, '0', '1', CALIBRATIONMODE_CMD_EOL};
static const uint8_t replyErrorUnknownCommandArgument[] = {CALIBRATIONMODE_REPLY_ERROR, '0', '2', CALIBRATIONMODE_CMD_EOL};
static uint8_t receiveBuffer[6];
static uint8_t receiveBufferIndex;
static bool isTransmitting;
static uint8_t transmitBuffer[] = {
CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL,
CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL,
CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL,
CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL,
CALIBRATIONMODE_CMD_EOL, CALIBRATIONMODE_CMD_EOL
};
static const uint8_t *transmitBufferPtr;
void calibrationModeInitialise(void)
{
receiveBufferIndex = 0;
isTransmitting = false;
LATBbits.LATB6 = 0;
LATBbits.LATB7 = 0;
ANSELBbits.ANSB6 = 0;
ANSELBbits.ANSB7 = 0;
if (!nvmSettings.platform.flags.bits.isCalibrationRequired)
{
PMD4bits.UART1MD = 1;
PMD0bits.CLKRMD = 1;
RB6PPS = 0;
RB7PPS = 0;
RX1DTPPS = 0;
ODCONBbits.ODCB7 = 0;
TRISBbits.TRISB6 = 0;
TRISBbits.TRISB7 = 0;
return;
}
configureReferenceClockModuleFor32768HzCrystalOutput();
configureUart1AsAsynchronous8bit9600BaudContinuousReception();
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
}
static void configureReferenceClockModuleFor32768HzCrystalOutput(void)
{
PMD0bits.CLKRMD = 0;
TRISBbits.TRISB6 = 0;
CLKRCON = CLKRCON_DUTY_CYCLE_50 | CLKRCON_NO_DIVIDER;
CLKRCLK = CLKRCLK_SOURCE_SOSC;
RB6PPS = PPS_OUT_CLKR;
}
static void configureUart1AsAsynchronous8bit9600BaudContinuousReception(void)
{
PMD4bits.UART1MD = 0;
TRISBbits.TRISB7 = 0;
ODCONBbits.ODCB7 = 1;
RB7PPS = PPS_OUT_UART1TX;
RX1DTPPS = PPS_IN_RB7;
SP1BRG = 51;
TX1STA = _TX1STA_TXEN_MASK;
RC1STA = _RC1STA_CREN_MASK | _RC1STA_SPEN_MASK;
BAUD1CON = 0;
PIE3bits.RC1IE = 1;
PIE3bits.TX1IE = 0;
}
static void onWokenFromSleep(const struct Event *event)
{
while (PIR3bits.RC1IF)
{
uint8_t received = RC1REG;
if (isTransmitting)
{
isTransmitting = received != CALIBRATIONMODE_CMD_EOL;
if (isTransmitting)
tryToTransmitNextByteToHost();
}
else if (received == '\r')
{
/* Ignore - dubious hack to allow some miniterm implementation's default line endings */
}
else if (received == CALIBRATIONMODE_CMD_EOL)
{
if (receiveBufferIndex == 0)
onNoCommandReceived();
else if (receiveBuffer[0] == CALIBRATIONMODE_CMD_SAMPLEPARAMETERS && receiveBufferIndex == 1)
onSampleParametersCommandReceived();
else if (receiveBuffer[0] == CALIBRATIONMODE_CMD_REFCLK && receiveBufferIndex == 2)
onRefclkCommandReceived(receiveBuffer[1]);
else if (receiveBuffer[0] == CALIBRATIONMODE_CMD_READ && receiveBufferIndex == 5)
onReadCommandReceived(&receiveBuffer[1]);
else
onUnknownCommandReceived();
receiveBufferIndex = 0;
isTransmitting = true;
}
else if (receiveBufferIndex < sizeof(receiveBuffer))
{
receiveBuffer[receiveBufferIndex] = received;
receiveBufferIndex++;
}
else
receiveBufferIndex = 0xff;
}
}
static void tryToTransmitNextByteToHost(void)
{
if (TX1STAbits.TRMT)
{
TX1REG = *transmitBufferPtr;
transmitBufferPtr++;
}
}
static void onNoCommandReceived(void)
{
static const uint8_t ok[] = {CALIBRATIONMODE_REPLY_RESULT, 'O', 'K', CALIBRATIONMODE_CMD_EOL};
transmitToHost(ok);
}
static void transmitToHost(const uint8_t buffer[])
{
transmitBufferPtr = buffer;
tryToTransmitNextByteToHost();
}
static void onSampleParametersCommandReceived(void)
{
struct MonitoredParametersSampled sample;
periodicMonitorSampleNow(&sample);
transmitBuffer[0] = CALIBRATIONMODE_REPLY_RESULT;
hexDigitsForByte(transmitBuffer + 1, sample.timestamp);
transmitBuffer[3] = ',';
hexDigitsForByte(transmitBuffer + 4, sample.flags.all);
transmitBuffer[6] = ',';
hexDigitsForWord(transmitBuffer + 7, sample.fvr);
transmitBuffer[11] = ',';
hexDigitsForWord(transmitBuffer + 12, sample.temperature);
transmitBuffer[16] = CALIBRATIONMODE_CMD_EOL;
transmitToHost(transmitBuffer);
}
static void onRefclkCommandReceived(uint8_t onOff)
{
if (onOff == '0')
{
CLKRCONbits.CLKREN = 0;
transmitToHost(replyResult0);
}
else if (onOff == '1')
{
CLKRCONbits.CLKREN = 1;
transmitToHost(replyResult1);
}
else
transmitToHost(replyErrorUnknownCommandArgument);
}
static void onReadCommandReceived(const uint8_t addressString[])
{
uint16_t value;
if (hexDigitsToWord(&value, addressString))
{
value = nvmWordAt(value);
receiveBuffer[0] = CALIBRATIONMODE_REPLY_RESULT;
hexDigitsForWord(&receiveBuffer[1], value);
receiveBuffer[5] = CALIBRATIONMODE_CMD_EOL;
transmitToHost(receiveBuffer);
}
else
transmitToHost(replyErrorUnknownCommandArgument);
}
static void onUnknownCommandReceived(void)
{
transmitToHost(replyErrorUnknownCommand);
}
<file_sep>/src/utilities/calibrator/calibration_results.py
from statistics import mean
from types import SimpleNamespace
from calibration_point import CalibrationPoint
from cluck2sesame_parameters_sample import Cluck2SesameParametersSample
from parabola import Parabola
class CalibrationResults:
def __init__(self, nvm_settings, calibration_points):
if nvm_settings is None:
raise TypeError('nvm_settings')
if calibration_points is None:
raise TypeError('calibration_points')
if len(calibration_points) != 6:
raise Exception('Expected 6 calibration points, high and low VDD over three temperatures')
self._calibration_points = sorted(calibration_points, key=lambda point: (point.vdd_volts, point.temperature_celsius))
self._low_vdd = VddSpecificCalibrationResults(self._calibration_points[0:3])
self._high_vdd = VddSpecificCalibrationResults(self._calibration_points[3:6])
self._mean_vdd = VddSpecificCalibrationResults([
CalibrationPoint(
[Cluck2SesameParametersSample(
timestamp=0x00,
flags=0x00,
fvr_adc_aggregate=(
sum(map(lambda point: point.fvr_adc_aggregate, self._calibration_points[i].samples)) +
sum(map(lambda point: point.fvr_adc_aggregate, self._calibration_points[i + 3].samples))
) / (len(self._calibration_points[i].samples) + len(self._calibration_points[i + 3].samples)) + 0.5,
temperature_adc_aggregate=(
sum(map(lambda point: point.temperature_adc_aggregate, self._calibration_points[i].samples)) +
sum(map(lambda point: point.temperature_adc_aggregate, self._calibration_points[i + 3].samples))
) / (len(self._calibration_points[i].samples) + len(self._calibration_points[i + 3].samples)) + 0.5
)],
mean([self._calibration_points[i].vdd_volts, self._calibration_points[i + 3].vdd_volts]),
mean([self._calibration_points[i].temperature_celsius, self._calibration_points[i + 3].temperature_celsius]),
mean([self._calibration_points[i].clock_frequency_hz, self._calibration_points[i + 3].clock_frequency_hz]))
for i in range(0, 3)
])
self._nvm_settings = nvm_settings
self._calibrated_nvm_settings = self._calculate_nvm_settings()
def _calculate_nvm_settings(self):
return self._nvm_settings \
.with_temperature_adc_high(self._mean_vdd.highest_temperature_calibration_point.temperature_adc) \
.with_temperature_celsius_high(self._mean_vdd.highest_temperature_calibration_point.temperature_celsius) \
.with_temperature_coefficient(self._mean_vdd.temperature_coefficient) \
.without_calibration_required_flag() \
.with_recalculated_crc8()
@property
def calibrated_nvm_settings(self): return self._calibrated_nvm_settings
@property
def low_vdd(self): return self._low_vdd
@property
def high_vdd(self): return self._high_vdd
@property
def mean_vdd(self): return self._mean_vdd
class VddSpecificCalibrationResults:
def __init__(self, calibration_points):
if calibration_points is None:
raise TypeError('calibration_points')
if len(calibration_points) != 3:
raise Exception('Expected three calibration points for three temperatures')
self._calibration_points = sorted(
calibration_points,
key=lambda point: point.temperature_celsius)
self._crystal_parabola = Parabola([
VddSpecificCalibrationResults._point_to_xy(point) for point in self._calibration_points])
self._lowest_temperature_calibration_point = min(self._calibration_points, key=lambda point: point.temperature_celsius)
self._highest_temperature_calibration_point = max(self._calibration_points, key=lambda point: point.temperature_celsius)
self._temperature_coefficient = \
(self._highest_temperature_calibration_point.temperature_celsius - self._lowest_temperature_calibration_point.temperature_celsius) / \
(self._highest_temperature_calibration_point.temperature_adc - self._lowest_temperature_calibration_point.temperature_adc)
self._vdd_volts = calibration_points[0].vdd_volts
@staticmethod
def _point_to_xy(point):
return SimpleNamespace(
x=VddSpecificCalibrationResults._mean_temperature_adc(point.samples),
y=point.clock_frequency_hz)
@staticmethod
def _mean_temperature_adc(samples):
sum = 0
for i in range(0, len(samples)):
sum += samples[i].temperature_adc_mean
return sum / len(samples)
@property
def calibration_points(self): return self._calibration_points.copy()
@property
def crystal_parabola(self): return self._crystal_parabola
@property
def highest_temperature_calibration_point(self): return self._highest_temperature_calibration_point
@property
def lowest_temperature_calibration_point(self): return self._lowest_temperature_calibration_point
@property
def temperature_coefficient(self): return self._temperature_coefficient
@property
def vdd_volts(self): return self._vdd_volts
<file_sep>/src/firmware/src/Platform/Lcd/LcdWrite.c
#include <xc.h>
#include <stdint.h>
#include "Lcd.h"
void lcdWriteCommand(uint8_t byte)
{
lcdWriteNybble(LCD_NYBBLE_CMD | ((byte >> 4) & 0b00001111));
lcdWriteNybble(LCD_NYBBLE_CMD | ((byte >> 0) & 0b00001111));
}
void lcdWriteNybble(uint8_t nybble)
{
if (lcdState.enableCount == 0)
return;
LATAbits.LATA4 = 1;
LATAbits.LATA3 = (nybble & 0b10000000) ? 1 : 0;
LATCbits.LATC4 = (nybble & 0b00001000) ? 1 : 0;
LATAbits.LATA6 = (nybble & 0b00000100) ? 1 : 0;
LATAbits.LATA7 = (nybble & 0b00000010) ? 1 : 0;
LATAbits.LATA5 = (nybble & 0b00000001) ? 1 : 0;
LATAbits.LATA4 = 0;
}
void lcdWriteData(uint8_t byte)
{
lcdWriteNybble(LCD_NYBBLE_DATA | ((byte >> 4) & 0b00001111));
lcdWriteNybble(LCD_NYBBLE_DATA | ((byte >> 0) & 0b00001111));
}
<file_sep>/src/firmware/src/SunEvents/SunEvents.h
#ifndef __CLUCK2SESAME_SRC_SUNEVENTS_SUNEVENTS_H
#define __CLUCK2SESAME_SRC_SUNEVENTS_SUNEVENTS_H
#include "../Platform/Clock.h"
#include "../SunEvents.h"
#include "../Location.h"
#define LOOKUP_STEP 6
#define LOOKUP_LENGTH (366 / LOOKUP_STEP)
#define LOOKUP_LATITUDE (55 * LONGLAT_ONE_DEGREE)
#define LOOKUP_LATITUDE_NORTH (LOOKUP_LATITUDE + 5 * LONGLAT_ONE_DEGREE)
#define LOOKUP_LATITUDE_SOUTH (LOOKUP_LATITUDE - 5 * LONGLAT_ONE_DEGREE)
#define LOOKUP_LONGITUDE (0 * LONGLAT_ONE_DEGREE)
struct SunEventsCalculationContext
{
struct
{
uint16_t dayOfYear;
int8_t latitudeOffset;
int8_t longitudeOffset;
} inputs;
struct
{
uint16_t lookupPtr;
struct Time *destination;
} working;
};
struct SunEventsLookupEntry
{
uint16_t minuteOfDay;
int8_t offsetMinutesNorth;
int8_t offsetMinutesSouth;
};
extern struct SunEventsCalculationContext sunEventsCalculationContext;
extern const uint8_t sunriseLookupTable;
extern const uint8_t sunsetLookupTable;
extern void sunEventsCalculate(void);
#endif
<file_sep>/src/firmware/src/Ui/UiCalibrationModeScreen.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "Ui.h"
void uiCalibrationModeScreen(void)
{
memcpy(
uiState.screen,
"CALIBRATION MODE\0"
" (HEADLESS) ",
sizeof(uiState.screen));
uiState.flags.bits.isButtonPressPreventedFromTurningOnScreen = 1;
uiState.input.buttons = &uiInputIsUninitialised;
uiScreenBlit();
uiScreenStartTimeout();
}
<file_sep>/src/firmware/tests/Platform/PowerManagement/TestPowerManagement.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Platform/PowerManagement.h"
#include "TestPowerManagement.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Poll.c")
static volatile uint8_t sleepExecuted;
static volatile uint8_t pie0BeforeSleep;
static volatile uint8_t vregconBeforeSleep;
static volatile uint8_t cpudozeBeforeSleep;
static struct Event onAllEventsDispatchedEvent;
static const struct EventSubscription *onAllEventsDispatched;
static uint8_t numberOfEventPublishesForWokenFromSleep;
const struct Event eventEmptyArgs = { };
void onBeforeTest(void)
{
sleepExecuted = 0;
onAllEventsDispatched = (const struct EventSubscription *) 0;
numberOfEventPublishesForWokenFromSleep = 0;
}
void onAfterTest(void)
{
}
void test_powerManagementInitialise_called_expectPeripheralInterruptsAllowWakeFromSleep(void)
{
INTCON = anyByteWithMaskClear(_INTCON_PEIE_MASK);
uint8_t originalIntcon = INTCON;
powerManagementInitialise();
TEST_ASSERT_EQUAL_UINT8(originalIntcon | _INTCON_PEIE_MASK, INTCON);
}
void test_powerManagementInitialise_called_expectAllModulesExceptSystemClockAndNvmAreDisabled(void)
{
PMD0 = _PMD0_SYSCMD_MASK | _PMD0_NVMMD_MASK;
PMD1 = 0;
PMD2 = 0;
PMD3 = 0;
PMD4 = 0;
PMD5 = 0;
powerManagementInitialise();
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b01000011, PMD0, "PMD0");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b10000111, PMD1, "PMD1");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b01100111, PMD2, "PMD2");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b00111111, PMD3, "PMD3");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b11110001, PMD4, "PMD4");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0b00011110, PMD5, "PMD5");
}
void test_powerManagementInitialise_called_expectSubscriptionToAllEventsDispatched(void)
{
powerManagementInitialise();
TEST_ASSERT_NOT_NULL(onAllEventsDispatched);
}
void test_onAllEventsDispatched_event_expectDeviceSleepsWhenTimer2IsDisabled(void)
{
powerManagementInitialise();
PMD1bits.TMR2MD = 0;
PIE4bits.TMR2IE = 0;
T2CONbits.ON = 0;
CPUDOZE = anyByteWithMaskSet(_CPUDOZE_IDLEN_MASK | _CPUDOZE_DOZEN_MASK);
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_NOT_EQUAL_MESSAGE(0, sleepExecuted, "SLEEP");
TEST_ASSERT_BITS_LOW_MESSAGE(
_CPUDOZE_IDLEN_MASK | _CPUDOZE_DOZEN_MASK,
cpudozeBeforeSleep,
"IDLEN / DOZEN");
}
void test_onAllEventsDispatched_event_expectDeviceIdlesWhenTimer2IsEnabled(void)
{
powerManagementInitialise();
PMD1bits.TMR2MD = 0;
PIE4bits.TMR2IE = 0;
T2CONbits.ON = 1;
CPUDOZE = anyByte();
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_NOT_EQUAL_MESSAGE(0, sleepExecuted, "SLEEP");
TEST_ASSERT_BITS_LOW_MESSAGE(
_CPUDOZE_DOZEN_MASK,
cpudozeBeforeSleep,
"DOZEN");
TEST_ASSERT_BITS_HIGH_MESSAGE(
_CPUDOZE_IDLEN_MASK,
cpudozeBeforeSleep,
"IDLEN");
}
void test_onAllEventsDispatched_event_expectDeviceSleepsWhenUart1IsDisabled(void)
{
powerManagementInitialise();
PMD4bits.UART1MD = 0;
T2CONbits.ON = 0;
PIE3bits.RC1IE = 0;
CPUDOZE = anyByteWithMaskSet(_CPUDOZE_IDLEN_MASK | _CPUDOZE_DOZEN_MASK);
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_NOT_EQUAL_MESSAGE(0, sleepExecuted, "SLEEP");
TEST_ASSERT_BITS_LOW_MESSAGE(
_CPUDOZE_IDLEN_MASK | _CPUDOZE_DOZEN_MASK,
cpudozeBeforeSleep,
"IDLEN / DOZEN");
}
void test_onAllEventsDispatched_event_expectDeviceIdlesWhenUart1ReceiveIsEnabled(void)
{
powerManagementInitialise();
PMD4bits.UART1MD = 0;
T2CONbits.ON = 0;
PIE3bits.RC1IE = 1;
CPUDOZE = anyByte();
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_NOT_EQUAL_MESSAGE(0, sleepExecuted, "SLEEP");
TEST_ASSERT_BITS_LOW_MESSAGE(
_CPUDOZE_DOZEN_MASK,
cpudozeBeforeSleep,
"DOZEN");
TEST_ASSERT_BITS_HIGH_MESSAGE(
_CPUDOZE_IDLEN_MASK,
cpudozeBeforeSleep,
"IDLEN");
}
void test_onAllEventsDispatched_event_expectDeviceEntersLowPowerSleep(void)
{
powerManagementInitialise();
VREGCON = anyByteWithMaskClear(_VREGCON_VREGPM_MASK);
vregconBeforeSleep = VREGCON;
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_BIT_HIGH(_VREGCON_VREGPM_POSITION, vregconBeforeSleep);
}
void test_onAllEventsDispatched_event_expectWokenFromSleepIsPublished(void)
{
powerManagementInitialise();
onAllEventsDispatched->handler(&onAllEventsDispatchedEvent);
TEST_ASSERT_EQUAL_UINT8(1, numberOfEventPublishesForWokenFromSleep);
}
void eventSubscribe(const struct EventSubscription *subscription)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == ALL_EVENTS_DISPATCHED)
{
onAllEventsDispatched = subscription;
onAllEventsDispatchedEvent.type = subscription->type;
onAllEventsDispatchedEvent.state = subscription->state;
onAllEventsDispatchedEvent.args = (void *) 0;
}
else
{
TEST_FAIL_MESSAGE("Unknown subscription type");
}
}
void eventPublish(EventType type, const void *args)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(WOKEN_FROM_SLEEP, type, "Type");
TEST_ASSERT_NOT_NULL_MESSAGE(args, "Args");
numberOfEventPublishesForWokenFromSleep++;
}
<file_sep>/src/firmware/tests/Platform/PeriodicMonitor/PeriodicMonitorFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "Platform/Adc.h"
#include "PeriodicMonitorFixture.h"
#include "../../NonDeterminism.h"
static void onMonitoredParametersSampled(const struct Event *event);
static void onTimeChanged(const struct Event *event);
static void stubAdcSample(struct AdcSample *sample);
static uint8_t stubCallSequence;
const struct TimeChanged *timeChanged;
uint8_t timeChangedCalls;
uint8_t timeChangedSequence;
const struct MonitoredParametersSampled *monitoredParametersSampled;
uint8_t monitoredParametersSampledCalls;
uint8_t monitoredParametersSampledSequence;
static struct AdcSample *expectedAdcSampleArg;
uint8_t adcSampleCalls;
uint8_t adcSampleSequence;
AdcSampleCallback onAdcSample;
static void buggyCompilerWorkaround(void)
{
onAdcSample = _OMNITARGET;
}
void periodicMonitorFixtureSetUp(void)
{
eventInitialise();
periodicMonitorInitialise();
stubCallSequence = 1;
timeChanged = (const struct TimeChanged *) 0;
timeChangedCalls = 0;
timeChangedSequence = 0;
monitoredParametersSampled = (const struct MonitoredParametersSampled *) 0;
monitoredParametersSampledCalls = 0;
monitoredParametersSampledSequence = 0;
expectedAdcSampleArg = (struct AdcSample *) 0;
adcSampleCalls = 0;
adcSampleSequence = 0;
onAdcSample = &stubAdcSample;
}
void periodicMonitorFixtureTearDown(void)
{
}
void mockOnMonitoredParametersSampled(void)
{
static const struct EventSubscription onMonitoredParametersSampledSubscription =
{
.type = MONITORED_PARAMETERS_SAMPLED,
.handler = &onMonitoredParametersSampled
};
eventSubscribe(&onMonitoredParametersSampledSubscription);
}
static void onMonitoredParametersSampled(const struct Event *event)
{
monitoredParametersSampled = (const struct MonitoredParametersSampled *) event->args;
monitoredParametersSampledCalls++;
monitoredParametersSampledSequence = stubCallSequence++;
}
void publishTimeChanged(const struct Time *now)
{
static struct TimeChanged eventArgs;
eventArgs.now = now;
eventPublish(TIME_CHANGED, &eventArgs);
}
void stubAdcSampleFor(struct AdcSample *sample)
{
expectedAdcSampleArg = sample;
}
void adcSample(struct AdcSample *sample)
{
if (onAdcSample)
onAdcSample(sample);
}
static void stubAdcSample(struct AdcSample *sample)
{
adcSampleCalls++;
adcSampleSequence = stubCallSequence++;
if (!expectedAdcSampleArg || !sample)
return;
if (sample->channel != expectedAdcSampleArg->channel)
return;
if (sample->count != expectedAdcSampleArg->count)
return;
if (sample->flags.all != expectedAdcSampleArg->flags.all)
return;
sample->result = expectedAdcSampleArg->result;
}
<file_sep>/src/firmware/tests/Platform/Event/TestEventDispatch1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Platform/Event.h"
#include "Mock_EventHandler.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
static struct EventSubscription subscription;
static uint8_t eventState;
static struct EventSubscription anotherSubscription;
static uint8_t anotherEventState;
static int eventHandlerCallCount;
static void eventHandlerThatIncrementsCounter(
const struct Event *event,
int numCalls)
{
eventHandlerCallCount++;
}
void onBeforeTest(void)
{
eventHandlerCallCount = 0;
eventState = anyByte();
subscription.type = anyByte();
subscription.handler = &eventHandler;
subscription.state = &eventState;
anotherEventState = anyByte();
anotherSubscription.type = anyByteExcept(subscription.type);
anotherSubscription.handler = &anotherEventHandler;
anotherSubscription.state = &anotherEventState;
eventInitialise();
}
void onAfterTest(void)
{
}
void test_eventPublish_called_expectHandlerIsNotCalledBeforeEventDispatch(void)
{
uint8_t args = anyByte();
eventHandler_StubWithCallback(eventHandlerThatIncrementsCounter);
eventSubscribe(&subscription);
eventPublish(subscription.type, &args);
TEST_ASSERT_EQUAL_INT(0, eventHandlerCallCount);
}
void test_eventDispatchNext_calledWhenOneEventPublished_expectHandlerIsCalledWithOldestEvent(void)
{
struct Event event =
{
.type = subscription.type,
.args = (void *) (int) anyByte(),
.state = subscription.state
};
eventSubscribe(&subscription);
eventPublish(subscription.type, event.args);
eventHandler_Expect(&event);
eventDispatchNext();
}
void test_eventDispatchNext_calledWhenMoreThanOneEventPublished_expectHandlerIsCalledWithOldestEvent(void)
{
struct Event event =
{
.type = subscription.type,
.args = (void *) (int) anyByte(),
.state = subscription.state
};
struct Event anotherEvent =
{
.type = anotherSubscription.type,
.args = (void *) (int) anyByte(),
.state = anotherSubscription.state
};
eventSubscribe(&subscription);
eventPublish(event.type, event.args);
eventPublish(anotherEvent.type, anotherEvent.args);
eventHandler_Expect(&event);
anotherEventHandler_StubWithCallback(eventHandlerThatIncrementsCounter);
eventDispatchNext();
TEST_ASSERT_EQUAL_INT(0, eventHandlerCallCount);
}
void test_eventDispatchNext_calledTwiceWhenTwoEventsPublished_expectBothHandlersAreCalled(void)
{
struct Event event =
{
.type = subscription.type,
.args = (void *) (int) anyByte(),
.state = subscription.state
};
struct Event anotherEvent =
{
.type = anotherSubscription.type,
.args = (void *) (int) anyByte(),
.state = anotherSubscription.state
};
eventSubscribe(&subscription);
eventSubscribe(&anotherSubscription);
eventPublish(event.type, event.args);
eventPublish(anotherEvent.type, anotherEvent.args);
eventHandler_Expect(&event);
anotherEventHandler_Expect(&anotherEvent);
eventDispatchNext();
eventDispatchNext();
}
void test_eventDispatchNext_calledWhenMoreThanOneSubscriberForSameType_expectEachSubscriberHandlerIsCalled(void)
{
struct Event event =
{
.type = subscription.type,
.args = (void *) (int) anyByte(),
.state = subscription.state
};
struct Event anotherEvent =
{
.type = event.type,
.args = event.args,
.state = anotherSubscription.state
};
anotherSubscription.type = subscription.type;
eventSubscribe(&subscription);
eventSubscribe(&anotherSubscription);
eventPublish(subscription.type, event.args);
eventHandler_Expect(&event);
anotherEventHandler_Expect(&anotherEvent);
eventDispatchNext();
}
void test_eventDispatchNext_calledWhenNullHandlerAtSubscription_expectNothingHappens(void)
{
subscription.handler = (EventHandler) 0;
eventSubscribe(&subscription);
eventPublish(subscription.type, NULL);
eventDispatchNext();
}
void test_eventDispatchNext_calledWhenNullHandlerAfterSubscription_expectNothingHappens(void)
{
eventSubscribe(&subscription);
subscription.handler = (EventHandler) 0;
eventPublish(subscription.type, NULL);
eventDispatchNext();
}
<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdPuts.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Lcd.h"
#include "FakeLcd.h"
#include "LcdFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Poll.c")
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("Platform/PowerManagement.c")
TEST_FILE("Platform/PwmTimer.c")
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
TEST_FILE("Platform/Lcd/LcdConfigure.c")
TEST_FILE("Platform/Lcd/LcdTransaction.c")
TEST_FILE("Platform/Lcd/LcdWrite.c")
TEST_FILE("Platform/Lcd/LcdPuts.c")
extern void poll(void);
static void sendLineToLcdAndWaitUntilDone(void);
static void sendOffsetLineToLcdAndWaitUntilDone(uint8_t offset);
static void onLineDisplayed(void *state);
static char screen[sizeof(fakeLcdDram) + 1];
static const struct LcdPutsTransaction dummyTransaction = { .buffer = "\0" };
void onBeforeTest(void)
{
lcdFixtureInitialise();
for (uint8_t i = 0; i < sizeof(screen); i++)
screen[i] = (char) anyByteExcept('\0'); // TODO: CGPIC CORE DUMP !
screen[sizeof(screen) - 1] = '\0';
}
void onAfterTest(void)
{
lcdFixtureShutdown();
}
void test_lcdPuts_calledWithOneCharacterAfterLcdEnabled_expectCorrectDramBuffer(void)
{
enableLcdAndWaitUntilDone();
screen[1] = '\0';
sendLineToLcdAndWaitUntilDone();
TEST_ASSERT_EQUAL_UINT8(screen[0], fakeLcdDram[0]);
for (uint8_t i = 1; i < sizeof(fakeLcdDram); i++)
{
TEST_ASSERT_EQUAL_UINT8(' ', fakeLcdDram[i]);
}
}
static void sendLineToLcdAndWaitUntilDone(void)
{
sendOffsetLineToLcdAndWaitUntilDone(0);
}
static void sendOffsetLineToLcdAndWaitUntilDone(uint8_t offset)
{
static uint8_t lcdCallbackDone;
struct LcdPutsTransaction transaction =
{
.buffer = &screen[offset],
.callback = &onLineDisplayed,
.state = (void *) &lcdCallbackDone
};
lcdCallbackDone = 0;
lcdPuts(&transaction);
while (!lcdCallbackDone)
poll();
}
static void onLineDisplayed(void *state)
{
TEST_ASSERT_NOT_NULL(state);
*((uint8_t *) state) = 1;
}
void test_lcdPuts_calledWithTwoCharacterAfterLcdEnabled_expectCorrectDramBuffer(void)
{
enableLcdAndWaitUntilDone();
screen[2] = '\0';
sendLineToLcdAndWaitUntilDone();
TEST_ASSERT_EQUAL_UINT8(screen[0], fakeLcdDram[0]);
TEST_ASSERT_EQUAL_UINT8(screen[1], fakeLcdDram[1]);
for (uint8_t i = 2; i < sizeof(fakeLcdDram); i++)
{
TEST_ASSERT_EQUAL_UINT8(' ', fakeLcdDram[i]);
}
}
void test_lcdPuts_calledWithEntireLineOfCharactersAfterLcdEnabled_expectCorrectDramBuffer(void)
{
enableLcdAndWaitUntilDone();
screen[sizeof(fakeLcdDram) / 2] = '\0';
sendLineToLcdAndWaitUntilDone();
for (uint8_t i = 0; i < sizeof(fakeLcdDram) / 2; i++)
{
TEST_ASSERT_EQUAL_UINT8(screen[i], fakeLcdDram[i]);
}
for (uint8_t i = sizeof(fakeLcdDram) / 2; i < sizeof(fakeLcdDram); i++)
{
TEST_ASSERT_EQUAL_UINT8(' ', fakeLcdDram[i]);
}
}
void test_lcdPuts_calledTwiceAfterLcdEnabled_expectConcatenatedCharactersInDramBuffer(void)
{
enableLcdAndWaitUntilDone();
screen[5] = '\0';
sendOffsetLineToLcdAndWaitUntilDone(0);
screen[9] = '\0';
sendOffsetLineToLcdAndWaitUntilDone(6);
for (uint8_t i = 0; i < 5; i++)
{
TEST_ASSERT_EQUAL_UINT8(screen[i], fakeLcdDram[i]);
}
for (uint8_t i = 6; i < 9; i++)
{
TEST_ASSERT_EQUAL_UINT8(screen[i], fakeLcdDram[i - 1]);
}
for (uint8_t i = 8; i < sizeof(fakeLcdDram); i++)
{
TEST_ASSERT_EQUAL_UINT8(' ', fakeLcdDram[i]);
}
}
void test_lcdPuts_calledWithNullTransaction_expectLcdIsNotSentCommand(void)
{
enableLcdAndWaitUntilDone();
lcdPuts((const struct LcdPutsTransaction *) 0);
fakeLcdAssertNotBusy();
}
void test_lcdPuts_calledWithNullTransaction_expectNearSchedulerIsIdle(void)
{
enableLcdAndWaitUntilDone();
lcdPuts((const struct LcdPutsTransaction *) 0);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdPuts_calledWithNullBuffer_expectLcdIsNotSentCommand(void)
{
enableLcdAndWaitUntilDone();
static const struct LcdPutsTransaction withNullBuffer =
{
.buffer = (const char *) 0
};
lcdPuts(&withNullBuffer);
fakeLcdAssertNotBusy();
}
void test_lcdPuts_calledWithNullBuffer_expectNearSchedulerIsIdle(void)
{
enableLcdAndWaitUntilDone();
static const struct LcdPutsTransaction withNullBuffer =
{
.buffer = (const char *) 0
};
lcdPuts(&withNullBuffer);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdPuts_calledWithNullBuffer_expectCallbackIsStillCalled(void)
{
enableLcdAndWaitUntilDone();
static uint8_t callbackWasCalled = 0;
static const struct LcdPutsTransaction withNullBuffer =
{
.buffer = (const char *) 0,
.callback = &onLineDisplayed,
.state = &callbackWasCalled
};
lcdPuts(&withNullBuffer);
TEST_ASSERT_TRUE(callbackWasCalled);
}
void test_lcdPuts_calledBeforeLcdEnabled_expectLcdIsNotSentCommand(void)
{
lcdPuts(&dummyTransaction);
fakeLcdAssertNotBusy();
}
void test_lcdPuts_calledBeforeLcdEnabled_expectNearSchedulerIsIdle(void)
{
lcdPuts(&dummyTransaction);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_lcdPuts_calledBeforeLcdConfigured_expectLcdIsNotSentCommand(void)
{
lcdEnable();
lcdPuts(&dummyTransaction);
fakeLcdAssertStateIsValid();
}
void test_lcdPuts_calledWhileBusy_expectLcdIsNotSentCommand(void)
{
lcdEnable();
lcdPuts(&dummyTransaction);
lcdPuts(&dummyTransaction);
fakeLcdAssertStateIsValid();
}
void test_lcdPuts_calledAfterLcdDisabled_expectLcdIsNotSentCommand(void)
{
enableLcdAndWaitUntilDone();
lcdDisable();
lcdPuts(&dummyTransaction);
fakeLcdAssertNotBusy();
}
void test_lcdPuts_calledAfterLcdDisabled_expectNearSchedulerIsIdle(void)
{
enableLcdAndWaitUntilDone();
lcdDisable();
lcdPuts(&dummyTransaction);
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
<file_sep>/src/firmware/tests/Door/TestDoorClosingOnMotorStopped4.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsClose_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorIsTurnedOnAfterCurrentLimitIsSet(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_TRUE_MESSAGE(motorOnSequence > motorLimitIsMaximumLoadSequence, "Seq");
TEST_ASSERT_EQUAL_INT16_MESSAGE(nvmSettings.application.door.height, motorOnArgs[0], "Arg");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsClose_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsOpen_expectStateIsOpeningWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closing,
.transition = DoorTransition_Open
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opening, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsOpen_expectStateIsFaultWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closing,
.transition = DoorTransition_Open
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
<file_sep>/src/utilities/calibrator/pic16f15356_device_information_area.py
class Pic16f15356DeviceInformationArea:
def __init__(self, address, dia):
if len(dia) != 32:
raise ValueError('dia', f'PIC16F15356 DIA is 32 words but received {len(dia)} words')
self._address = address
self._raw = dia.copy()
self._device_id = ''.join(['{:04x}'.format(id_byte) for id_byte in dia[0x00:0x09]])
self._fvra2x = dia[0x19]
@property
def address(self): return self._address
@property
def raw(self): return self._raw.copy()
@property
def device_id(self): return self._device_id
@property
def fvra2x(self): return self._fvra2x
<file_sep>/src/firmware/tests/SunEvents/TestSunEventsScenarios.h
#ifndef __CLUCK2SESAME_TESTS_SUNEVENTS_TESTSUNEVENTSSCENARIOS_H
#define __CLUCK2SESAME_TESTS_SUNEVENTS_TESTSUNEVENTSSCENARIOS_H
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "Location.h"
#endif
<file_sep>/src/utilities/calibrator/parabola.py
class Parabola:
def __init__(self, points):
if len(points) != 3:
raise Exception('Expected three points')
x = [points[0].x, points[1].x, points[2].x]
y = [points[0].y, points[1].y, points[2].y]
denominator = (x[0] - x[1]) * (x[0] - x[2]) * (x[1] - x[2])
self._coefficients = [
(x[2] * (y[1] - y[0]) +
x[1] * (y[0] - y[2]) +
x[0] * (y[2] - y[1])) /
denominator,
(x[2] * x[2] * (y[0] - y[1]) +
x[1] * x[1] * (y[2] - y[0]) +
x[0] * x[0] * (y[1] - y[2])) /
denominator,
(x[1] * x[2] * (x[1] - x[2]) * y[0] +
x[2] * x[0] * (x[2] - x[0]) * y[1] +
x[0] * x[1] * (x[0] - x[1]) * y[2]) /
denominator]
@property
def coefficients(self): return self._coefficients
<file_sep>/src/firmware/tests/Door/TestDoorGetFaultState.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_doorGetState_calledWhenInNonFaultState_expectNoFaultFlagsSet(void)
{
struct DoorStateWithContext state =
{
.current = (enum DoorState) anyByteExcept(DoorState_Fault),
.transition = (enum DoorTransition) anyByte(),
.fault =
{
.all = anyByteExcept(0)
}
};
stubDoorWithState(state.current, state.transition);
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, state.fault.all);
}
void test_doorGetState_calledWhenInFaultState_expectFaultFlagsSet(void)
{
struct DoorStateWithContext state =
{
.current = (enum DoorState) anyByte(),
.transition = (enum DoorTransition) anyByte(),
.fault =
{
.all = 0
}
};
uint8_t faults = anyByteExcept(0);
stubDoorWithFault(faults);
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(faults, state.fault.all);
}
void test_doorGetState_calledWhenFaultStateCleared_expectNoFaultFlagsSet(void)
{
struct DoorStateWithContext state =
{
.current = (enum DoorState) anyByteExcept(DoorState_Fault),
.transition = (enum DoorTransition) anyByte(),
.fault =
{
.all = anyByteExcept(0)
}
};
uint8_t faults = anyByteExcept(0);
stubDoorWithFault(faults);
stubDoorWithState(state.current, state.transition);
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, state.fault.all);
}
<file_sep>/src/firmware/src/Platform/Lcd/LcdTransaction.c
#include <xc.h>
#include "Lcd.h"
void __reentrant lcdTransactionCompleted(void *unused)
{
lcdState.flags.isBusy = 0;
if (lcdState.transaction.callback)
lcdState.transaction.callback(lcdState.transaction.state);
}
<file_sep>/src/firmware/src/Platform/Clock/Clock.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_CLOCK_CLOCK_H
#define __CLUCK2SESAME_SRC_PLATFORM_CLOCK_CLOCK_H
#include "../Clock.h"
extern void clockTicked(void);
#endif
<file_sep>/src/firmware/tests/Platform/PwmTimer/TestPwmTimerEnableDisable.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/PwmTimer.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/PwmTimer.c")
void onBeforeTest(void)
{
pwmTimerInitialise();
}
void onAfterTest(void)
{
}
void test_pwmTimerEnable_calledOnce_expectTimer2IsEnabled(void)
{
uint8_t originalT2con = T2CON;
pwmTimerEnable();
TEST_ASSERT_EQUAL_UINT8(T2CON | _T2CON_ON_MASK, T2CON);
}
void test_pwmTimerEnable_calledOnce_expectTimerInterruptFlagIsCleared(void)
{
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerEnable();
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR2IF_MASK, PIR4);
}
void test_pwmTimerEnable_calledMoreThanOnceWhenInterruptFlagIsSet_expectTimerInterruptFlagIsNotCleared(void)
{
pwmTimerEnable();
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerEnable();
TEST_ASSERT_EQUAL_UINT8(originalPir4 | _PIR4_TMR2IF_MASK, PIR4);
}
void test_pwmTimerDisable_calledWhenNotEnabled_expectTimer2IsDisabled(void)
{
T2CON = anyByteWithMaskSet(_T2CON_ON_MASK);
uint8_t originalT2con = T2CON;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(T2CON & ~_T2CON_ON_MASK, T2CON);
}
void test_pwmTimerDisable_calledWhenNotEnabled_expectTimerInterruptFlagIsCleared(void)
{
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR2IF_MASK, PIR4);
}
void test_pwmTimerDisable_calledWhenEnabledOnce_expectTimer2IsDisabled(void)
{
pwmTimerEnable();
T2CON = anyByteWithMaskSet(_T2CON_ON_MASK);
uint8_t originalT2con = T2CON;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(T2CON & ~_T2CON_ON_MASK, T2CON);
}
void test_pwmTimerDisable_calledWhenEnabledOnce_expectTimerInterruptFlagIsCleared(void)
{
pwmTimerEnable();
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR2IF_MASK, PIR4);
}
void test_pwmTimerDisable_calledLessTimesThanEnabled_expectTimerIsNotDisabled(void)
{
pwmTimerEnable();
pwmTimerEnable();
uint8_t originalT2con = T2CON;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(originalT2con, T2CON);
}
void test_pwmTimerDisable_calledLessTimesThanEnabled_expectTimerInterruptFlagNotCleared(void)
{
pwmTimerEnable();
pwmTimerEnable();
PIR4 = anyByteWithMaskSet(_PIR4_TMR2IF_MASK);
uint8_t originalPir4 = PIR4;
pwmTimerDisable();
TEST_ASSERT_EQUAL_UINT8(originalPir4, PIR4);
}
void test_pwmTimerDisable_calledMoreTimesThanEnabled_expectTimerCounterDoesNotGetOutOfSync(void)
{
pwmTimerEnable();
pwmTimerDisable();
pwmTimerDisable();
pwmTimerEnable();
TEST_ASSERT_TRUE(T2CONbits.ON);
}
<file_sep>/src/schematics/Plots/seeed/Cluck2Sesame/README.TXT
Customer:
---------
<NAME> (Parity Computer Consultancy Limited) - <EMAIL>
Any problems / questions, please do not hesitate to get in touch.
Design Tools Used:
------------------
DesignSpark 8.1.2
Gerbv 2.6.2
Track and Spacing:
------------------
Minimum 6mil.
Layers:
-------
All viewed from above, no mirroring. Solder Resist and Solder Paste Stencil
layers are negatives, all others are positives.
Board Outline:
--------------
All layers contain a zero-width board outline. Outline size is
4.24016in x 4.20000in and >= 20mil from any feature, copper or otherwise.
Vias and Silkscreen:
--------------------
Some vias are partially covered with silkscreen; this is not anticipated to
be an issue since they should be tented.
Pads and Silkscreen:
--------------------
Some silkscreen map overlap, but this is not an issue. The silkscreen can be
clipped where necessary, but please advise if this is going to be an issue.
Drill Holes:
------------
All are through-plated and are finished sizes; no adjustments have been made
for plating thickness. All are >= 20mil from the edge of the board.
Bit sizes can be rounded to the nearest 0.1mm. Please advise if any drill
sizes are found to be incompatible with your processes.
Annular rings >= 6mil. Holes >= 0.4mm.
Data Formats:
-------------
More detailed information can be found in "DesignSpark Plot Report.TXT", but
in summary:
Gerber Settings
===============
Leading zero suppression.
G01 assumed throughout.
Line termination <*> <CR> <LF>.
3.5 format absolute inches.
Format commands defined in Gerber file.
Aperture table defined in Gerber file.
Hardware arcs allowed.
Drill Settings
==============
Excellon Format 1
Format 3.5 absolute in inches.
Zero suppression Leading
<file_sep>/src/firmware/tests/Platform/NearScheduler/NearSchedulerFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/NearScheduler.h"
#include "NearSchedulerFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
const struct NearSchedule dummySchedule =
{
.ticks = 0,
.handler = &dummyHandler,
.state = (void *) 0
};
const struct NearSchedule dummySchedule2 =
{
.ticks = 0,
.handler = &dummyHandler2,
.state = (void *) 0
};
static const struct EventSubscription *onWokenFromSleep;
static struct Event wokenFromSleepEvent;
static uint8_t numberOfHandlerCalls;
static const void *handlerSchedules[16];
static const void **handlerStateWrptr;
static const void **handlerStateRdptr;
void onBeforeTest(void)
{
onWokenFromSleep = (struct EventSubscription *) 0;
nearSchedulerInitialise();
numberOfHandlerCalls = 0;
handlerStateWrptr = &handlerSchedules[0];
handlerStateRdptr = handlerStateWrptr;
// HACK: Simulator does not respect NCO clock source, so NCO1ACC*
// manipulation does not produce the correct values if there is an
// increment.
NCO1INCU = 0;
NCO1INCH = 0;
NCO1INCL = 0;
}
void onAfterTest(void)
{
}
void tick(void)
{
PIR7bits.NCO1IF = 1;
wokenFromSleep();
}
void wokenFromSleep(void)
{
if (onWokenFromSleep && onWokenFromSleep->handler)
{
onWokenFromSleep->handler(&wokenFromSleepEvent);
}
else
{
TEST_FAIL_MESSAGE("No WokenFromSleep handler");
}
}
void assertNoHandlersCalled(void)
{
TEST_ASSERT_EQUAL_UINT8(0, numberOfHandlerCalls);
}
void assertHandlerCalledOnceWith(const void *state)
{
assertHandlerCalledTimes(1);
assertHandlerCalledWith(state);
}
void assertHandlerCalledTimes(uint8_t times)
{
TEST_ASSERT_EQUAL_UINT8(times, numberOfHandlerCalls);
}
void assertHandlerCalledWith(const void *state)
{
if (handlerStateRdptr == handlerStateWrptr)
{
TEST_FAIL_MESSAGE("Not enough calls");
}
const void *actual = *(handlerStateRdptr++);
TEST_ASSERT_EQUAL_PTR(state, actual);
}
void eventSubscribe(const struct EventSubscription *subscription)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Handler");
TEST_ASSERT_EQUAL_MESSAGE(
WOKEN_FROM_SLEEP,
subscription->type,
"Unexpected type");
static const struct WokenFromSleep emptyEventArgs = { };
onWokenFromSleep = subscription;
wokenFromSleepEvent.type = subscription->type;
wokenFromSleepEvent.state = subscription->state;
wokenFromSleepEvent.args = &emptyEventArgs;
}
void spyHandler(void *state)
{
numberOfHandlerCalls++;
*(handlerStateWrptr++) = state;
}
void spyHandler2(void *state)
{
numberOfHandlerCalls++;
*(handlerStateWrptr++) = state;
}
void dummyHandler(void *state)
{
}
void dummyHandler2(void *state)
{
}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorIsEnabled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
TEST_FILE("Platform/VoltageRegulatorFixture.c")
const struct Event eventEmptyArgs = { };
void test_voltageRegulatorIsEnabled_calledBeforeEnabled_expectFalse(void)
{
voltageRegulatorInitialise();
TEST_ASSERT_FALSE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledImmediatelyAfterEnable_expectFalse(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
TEST_ASSERT_FALSE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledWhenVoltageRailHasStabilised_expectFalse(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledWhenFullyEnabled_expectTrue(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
TEST_ASSERT_TRUE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledWhenFullyEnabledMoreTimesThanDisabled_expectTrue(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
fullyEnableVoltageRegulatorWithoutAssertions();
voltageRegulatorDisable();
TEST_ASSERT_TRUE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledWhenDisabledAfterBeingFullyEnabled_expectFalse(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
voltageRegulatorDisable();
TEST_ASSERT_FALSE(voltageRegulatorIsEnabled());
}
void test_voltageRegulatorIsEnabled_calledWhenDisabledBeforeBeingFullyEnabled_expectFalse(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
voltageRegulatorDisable();
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE(voltageRegulatorIsEnabled());
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorEnable.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorEnable_called_expectPwmTimerIsEnabled(void)
{
motorEnable();
TEST_ASSERT_EQUAL_UINT8(1, pwmTimerEnableCalls);
}
void test_motorEnable_calledMoreThanOnce_expectPwmTimerIsOnlyEnabledOnce(void)
{
uint8_t numberOfCalls = 2 + anyByteLessThan(10);
for (uint8_t i = 0; i < numberOfCalls; i++)
motorEnable();
TEST_ASSERT_EQUAL_UINT8(1, pwmTimerEnableCalls);
}
void test_motorEnable_calledWhenVoltageRegulatorIsDisabled_expectVoltageRegulatorIsEnabled(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
TEST_ASSERT_EQUAL_UINT8(1, voltageRegulatorEnableCalls);
}
void test_motorEnable_calledWhenVoltageRegulatorIsEnabled_expectVoltageRegulatorIsNotEnabledAgain(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
TEST_ASSERT_EQUAL_UINT8(1, voltageRegulatorEnableCalls);
}
void test_motorEnable_calledMoreThanOnce_expectVoltageRegulatorIsOnlyEnabledOnce(void)
{
uint8_t numberOfCalls = 2 + anyByteLessThan(10);
for (uint8_t i = 0; i < numberOfCalls; i++)
motorEnable();
TEST_ASSERT_EQUAL_UINT8(1, voltageRegulatorEnableCalls);
}
void test_motorEnable_calledForFirstTimeWhenVoltageRegulatorIsAlreadyEnabled_expectMotorEnabledEventIsPublished(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, onMotorEnabledCalls);
}
void test_motorEnable_calledForFirstTimeWhenVoltageRegulatorIsNotEnabled_expectMotorEnabledEventIsNotPublished(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorEnabledCalls);
}
void test_motorEnable_calledForSecondTimeWhenVoltageRegulatorIsAlreadyEnabled_expectMotorEnabledEventIsNotPublished(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
dispatchAllEvents();
motorEnable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, onMotorEnabledCalls);
}
void test_motorEnable_calledForSecondTimeWhenVoltageRegulatorIsNotEnabled_expectMotorEnabledEventIsNotPublished(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
motorEnable();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorEnabledCalls);
}
void test_motorEnable_calledForFirstTimeWhenVoltageRegulatorIsNotEnabled_expectMotorEnabledEventIsPublishedWhenVoltageRegulatorIsEnabled(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, onMotorEnabledCalls);
}
void test_motorEnable_calledTwiceWhenVoltageRegulatorIsNotEnabled_expectOneMotorEnabledEventIsPublishedWhenVoltageRegulatorIsEnabled(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
motorEnable();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, onMotorEnabledCalls);
}
void test_voltageRegulatorEnabled_onPublishedBeforeFirstMotorEnabledCall_expectMotorEnabledEventIsNotPublished(void)
{
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorEnabledCalls);
}
void test_motorIsEnabled_calledBeforeEnabled_expectFalse(void)
{
TEST_ASSERT_FALSE(motorIsEnabled());
}
void test_motorIsEnabled_calledBeforeMotorEnabledEvent_expectFalse(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
TEST_ASSERT_FALSE(motorIsEnabled());
}
void test_motorIsEnabled_calledAfterMotorEnabledEvent_expectTrue(void)
{
stubVoltageRegulatorIsEnabled(0);
motorEnable();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(motorIsEnabled());
}
void test_motorIsEnabled_calledWhenVoltageRegulatorEnabledButMotorEnabledEventHasNotBeenPublished_expectFalse(void)
{
stubVoltageRegulatorIsEnabled(1);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(motorIsEnabled());
}
void test_motorIsEnabled_calledWhenVoltageRegulatorEnabledAndMotorEnableHasBeenCalled_expectTrue(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
TEST_ASSERT_TRUE(motorIsEnabled());
}
void test_motorIsEnabled_calledAfterDisabled_expectFalse(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
dispatchAllEvents();
motorDisable();
TEST_ASSERT_FALSE(motorIsEnabled());
}
void test_motorIsEnabled_calledAfterDisableButStillEnabled_expectTrue(void)
{
stubVoltageRegulatorIsEnabled(1);
motorEnable();
motorEnable();
dispatchAllEvents();
motorDisable();
TEST_ASSERT_TRUE(motorIsEnabled());
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorModulesEnabled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectCurrentSenseComparatorAndDacAreEnabled(void)
{
static const uint8_t modules = _PMD2_CMP1MD_MASK | _PMD2_DAC1MD_MASK;
PMD2 = anyByteWithMaskSet(modules);
uint8_t originalPmd2 = PMD2;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd2 & ~modules, PMD2);
}
void test_voltageRegulatorEnabled_onPublished_expectEncoderCcpAndMotorPwmModulesAreEnabled(void)
{
static const uint8_t modules = _PMD3_CCP1MD_MASK | _PMD3_PWM4MD_MASK;
PMD3 = anyByteWithMaskSet(modules);
uint8_t originalPmd3 = PMD3;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd3 & ~modules, PMD3);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1ModuleIsEnabled(void)
{
PMD1 = anyByteWithMaskSet(_PMD1_TMR1MD_MASK);
uint8_t originalPmd1 = PMD1;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd1 & ~_PMD1_TMR1MD_MASK, PMD1);
}
void test_voltageRegulatorEnabled_onPublished_expectCwgModuleIsEnabled(void)
{
PMD4 = anyByteWithMaskSet(_PMD4_CWG1MD_MASK);
uint8_t originalPmd4 = PMD4;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd4 & ~_PMD4_CWG1MD_MASK, PMD4);
}
void test_voltageRegulatorEnabled_onPublished_expectClc2ModuleIsEnabled(void)
{
PMD5 = anyByteWithMaskSet(_PMD5_CLC2MD_MASK);
uint8_t originalPmd5 = PMD5;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd5 & ~_PMD5_CLC2MD_MASK, PMD5);
}
<file_sep>/src/utilities/calibrator/cluck2sesame_nvm_settings.py
from types import SimpleNamespace
_RETLW = 0b11_0100_0000_0000
_TEMPERATURE_ADC_HIGH_OFFSET = 4
_TEMPERATURE_CELSIUS_HIGH_OFFSET = 6
_TEMPERATURE_COEFFICIENT_OFFSET = 7
_FLAGS_OFFSET = 12
_CRC8_OFFSET = 31
class Cluck2SesameNvmSettings:
def __init__(self, address, nvm):
if len(nvm) != 32:
raise ValueError('nvm', f'NVM Settings is 32 words but received {len(nvm)} words')
self._address = address
self._raw = nvm.copy()
self._lcd_contrast = self._uint8_at(0)
self._temperature_adc_high = self._uint16_at(_TEMPERATURE_ADC_HIGH_OFFSET)
self._flags = self._uint8_at(_FLAGS_OFFSET)
@property
def address(self): return self._address
@property
def raw(self): return self._raw.copy()
@property
def lcd_contrast(self): return self._lcd_contrast
@property
def temperature_adc_high(self): return self._temperature_adc_high
@property
def flags(self): return Cluck2SesameNvmSettings._decode_flags(self._flags)
def _uint8_at(self, offset):
word = self._raw[offset]
if (word & _RETLW) != _RETLW:
raise Exception(f'NVM Settings at offset {offset} is not a retlw instruction')
return word & 0xff
def _uint16_at(self, offset):
return self._uint8_at(offset) | (self._uint8_at(offset + 1) << 8)
@staticmethod
def _decode_flags(flags):
as_obj = SimpleNamespace(raw=flags)
if flags & 0b0000_0001:
as_obj.is_calibration_required = True
return as_obj
def with_temperature_adc_high(self, value):
adc_value = int(value + 0.5)
if adc_value < 0 or adc_value > 1023:
raise Exception(f'ADC value must be an unsigned 10-bit integer; value={value}')
nvm = self._raw.copy()
nvm[_TEMPERATURE_ADC_HIGH_OFFSET + 0] = _RETLW | ((adc_value >> 0) & 0xff)
nvm[_TEMPERATURE_ADC_HIGH_OFFSET + 1] = _RETLW | ((adc_value >> 8) & 0xff)
return Cluck2SesameNvmSettings(self._address, nvm)
def with_temperature_celsius_high(self, value):
scaled_value = int((value - 25) * 10 + 0.5)
if scaled_value < 0 or scaled_value > 255:
raise Exception(f'Highest Calibration Temperature is higher than the maximum allowed; celsius={value}')
nvm = self._raw.copy()
nvm[_TEMPERATURE_CELSIUS_HIGH_OFFSET] = _RETLW | (scaled_value & 0xff)
return Cluck2SesameNvmSettings(self._address, nvm)
def with_temperature_coefficient(self, value):
scaled_value = int(65536 * -value + 0.5)
if scaled_value <= 0 or scaled_value > 65535:
raise Exception(f'Temperature coefficient must be negative and in the closed range (-1, 0); coefficient={value}')
nvm = self._raw.copy()
nvm[_TEMPERATURE_COEFFICIENT_OFFSET + 0] = _RETLW | ((scaled_value >> 0) & 0xff)
nvm[_TEMPERATURE_COEFFICIENT_OFFSET + 1] = _RETLW | ((scaled_value >> 8) & 0xff)
return Cluck2SesameNvmSettings(self._address, nvm)
def without_calibration_required_flag(self):
nvm = self._raw.copy()
nvm[_FLAGS_OFFSET] = _RETLW | (self._flags & 0xfe)
return Cluck2SesameNvmSettings(self._address, nvm)
def with_recalculated_crc8(self):
nvm = self._raw.copy()
crc8 = 0
for input in nvm[0:31]:
crc8 = Cluck2SesameNvmSettings._crc8Next(crc8, (input >> 8) & 0xff)
crc8 = Cluck2SesameNvmSettings._crc8Next(crc8, (input >> 0) & 0xff)
crc8 = Cluck2SesameNvmSettings._crc8Next(crc8, (_RETLW >> 8) & 0xff)
nvm[_CRC8_OFFSET] = _RETLW | crc8
return Cluck2SesameNvmSettings(self._address, nvm)
@staticmethod
def _crc8Next(crc8, input):
input ^= crc8
for _ in range(0, 8):
msb = input & 0x80
input <<= 1
if msb != 0:
input ^= 0x07
return input
<file_sep>/src/firmware/src/SunEvents/SunEventsCalculate.c
#include <xc.h>
#include <stdint.h>
#include <stdlib.h>
#include "../Platform/Event.h"
#include "../Platform/Nvm.h"
#include "../Platform/Clock.h"
#include "../Location.h"
#include "SunEvents.h"
#define MINUTES_PER_DEGREE_LONGITUDE 4
static void calculateSunEvent(void);
static void readLookupEntryInto(struct SunEventsLookupEntry *entry, uint8_t lookupIndex);
struct SunEventsCalculationContext sunEventsCalculationContext;
static struct SunEventsLookupEntry lookupEntries[2];
void sunEventsCalculate(void)
{
static struct SunEventsChanged eventArgs;
sunEventsCalculationContext.working.lookupPtr = (uint16_t) &sunriseLookupTable;
sunEventsCalculationContext.working.destination = &eventArgs.sunrise;
calculateSunEvent();
sunEventsCalculationContext.working.lookupPtr = (uint16_t) &sunsetLookupTable;
sunEventsCalculationContext.working.destination = &eventArgs.sunset;
calculateSunEvent();
eventPublish(SUN_EVENTS_CHANGED, &eventArgs);
}
static void calculateSunEvent(void)
{
// TODO: REFACTOR THIS WHEN IT'S ALL KNOWN TO BE WORKING
div_t lookupIndex = div(
(int) sunEventsCalculationContext.inputs.dayOfYear,
LOOKUP_STEP);
uint8_t lookupIndexUint8 = (uint8_t) lookupIndex.quot;
readLookupEntryInto(&lookupEntries[0], lookupIndexUint8);
if (++lookupIndexUint8 >= LOOKUP_LENGTH)
lookupIndexUint8 = 0;
readLookupEntryInto(&lookupEntries[1], lookupIndexUint8);
int dayDelta =
lookupIndex.rem * (int)
(lookupEntries[1].minuteOfDay - lookupEntries[0].minuteOfDay);
div_t interpolatedMinuteOfDay = div(dayDelta, LOOKUP_STEP);
if (interpolatedMinuteOfDay.rem >= LOOKUP_STEP / 2)
interpolatedMinuteOfDay.quot++;
interpolatedMinuteOfDay.quot += lookupEntries[0].minuteOfDay;
div_t latitudeAdjustmentMinutes;
if (sunEventsCalculationContext.inputs.latitudeOffset >= 0)
{
int offsetMinutes =
lookupEntries[0].offsetMinutesNorth +
(lookupEntries[1].offsetMinutesNorth - lookupEntries[0].offsetMinutesNorth) /
LOOKUP_STEP;
int interpolatedMinutes =
offsetMinutes * sunEventsCalculationContext.inputs.latitudeOffset;
latitudeAdjustmentMinutes = div(
interpolatedMinutes,
LOOKUP_LATITUDE_NORTH - LOOKUP_LATITUDE);
}
else
{
int offsetMinutes =
lookupEntries[0].offsetMinutesSouth +
(lookupEntries[1].offsetMinutesSouth - lookupEntries[0].offsetMinutesSouth) /
LOOKUP_STEP;
int interpolatedMinutes =
offsetMinutes * -sunEventsCalculationContext.inputs.latitudeOffset;
latitudeAdjustmentMinutes = div(
interpolatedMinutes,
LOOKUP_LATITUDE - LOOKUP_LATITUDE_SOUTH);
}
latitudeAdjustmentMinutes.quot +=
latitudeAdjustmentMinutes.rem >= LONGLAT_HALF_DEGREE
? 1
: latitudeAdjustmentMinutes.rem <= -LONGLAT_HALF_DEGREE
? -1
: 0;
int longitudeDelta =
sunEventsCalculationContext.inputs.longitudeOffset *
-MINUTES_PER_DEGREE_LONGITUDE;
div_t longitudeAdjustmentMinutes = div(longitudeDelta, LONGLAT_ONE_DEGREE);
longitudeAdjustmentMinutes.quot +=
longitudeAdjustmentMinutes.rem >= LONGLAT_HALF_DEGREE
? 1
: longitudeAdjustmentMinutes.rem <= -LONGLAT_HALF_DEGREE
? -1
: 0;
int minuteOfDay =
interpolatedMinuteOfDay.quot +
latitudeAdjustmentMinutes.quot +
longitudeAdjustmentMinutes.quot;
div_t hours = div(minuteOfDay, 60);
sunEventsCalculationContext.working.destination->hour = (uint8_t) hours.quot;
sunEventsCalculationContext.working.destination->minute = (uint8_t) hours.rem;
}
static void readLookupEntryInto(struct SunEventsLookupEntry *entry, uint8_t lookupIndex)
{
uint16_t lookupPtr = (sunEventsCalculationContext.working.lookupPtr + (((uint16_t) lookupIndex) << 1)) & 0x7fff;
uint16_t word0 = nvmWordAt(lookupPtr);
uint16_t word1 = nvmWordAt(lookupPtr + 1);
entry->minuteOfDay = (uint16_t) (((word0 >> 2) & 0b11111000000) | ((word1 >> 8) & 0b111111));
entry->offsetMinutesNorth = (int8_t) (word0 & 0xff);
entry->offsetMinutesSouth = (int8_t) (word1 & 0xff);
}
<file_sep>/src/firmware/tests/Fixture.c
#include <xc.h>
#include <stdint.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Fixture.h"
const struct Event eventEmptyArgs __attribute__((weak)) = { };
volatile uint8_t sclDataOverlay[31] __section("sclDataOverlay");
void setUp(void)
{
onBeforeTest();
}
void tearDown(void)
{
onAfterTest();
}
void dispatchAllEvents(void)
{
while (eventDispatchNext())
;;
}
void publishWokenFromSleep(void)
{
eventPublish(WOKEN_FROM_SLEEP, &eventEmptyArgs);
}
<file_sep>/src/firmware/src/ApplicationInitialise.c
#include <xc.h>
#include "Location.h"
#include "SunEvents.h"
#include "Door.h"
#include "Ui.h"
void applicationInitialise(void)
{
locationInitialise();
sunEventsInitialise();
doorInitialise();
uiInitialise();
}
<file_sep>/src/firmware/tests/SunEvents/TestSunEventsInitialise1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/Nvm.h"
#include "Mock_Location.h"
#include "SunEvents.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
TEST_FILE("SunEvents/SunEventsInitialise.c")
TEST_FILE("SunEvents/SunEventsCalculate.c")
static void ensureEventHandlerDoesNotGetOmittedByTheCompiler(void);
static struct Event onLocationChangedEvent;
static const struct EventSubscription *onLocationChanged;
static void eventSubscribeStub(
const struct EventSubscription *subscription,
int numCalls)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == LOCATION_CHANGED)
{
onLocationChanged = subscription;
onLocationChangedEvent.type = subscription->type;
onLocationChangedEvent.state = subscription->state;
onLocationChangedEvent.args = (void *) 0;
}
}
void onBeforeTest(void)
{
eventSubscribe_StubWithCallback(&eventSubscribeStub);
onLocationChanged = (const struct EventSubscription *) 0;
}
void onAfterTest(void)
{
}
void test_sunEventsInitialise_called_expectSubscriptionToLocationChanged(void)
{
sunEventsInitialise();
ensureEventHandlerDoesNotGetOmittedByTheCompiler();
TEST_ASSERT_NOT_NULL(onLocationChanged);
}
static void ensureEventHandlerDoesNotGetOmittedByTheCompiler(void)
{
static volatile uint8_t dummy = 0;
if (onLocationChanged && dummy)
onLocationChanged->handler(&onLocationChangedEvent);
}
<file_sep>/src/firmware/tests/Platform/NearScheduler/TestNearSchedulerInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/NearScheduler.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/NearScheduler.c")
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_MS_TO_TICKS_calledWithUpToFourMilliseconds_ExpectOneTick(void)
{
for (uint8_t ms = 1; ms <= 4; ms++)
{
TEST_ASSERT_EQUAL_UINT8(1, MS_TO_TICKS(ms));
}
}
void test_MS_TO_TICKS_calledWithExactMultiplesOfFourMilliseconds_ExpectNoRoundingIsPerformed(void)
{
uint16_t ms;
uint8_t ticks;
for (ms = 0, ticks = 0; ms <= 255 * 4; ms += 4, ticks++)
{
TEST_ASSERT_EQUAL_UINT8(ticks, MS_TO_TICKS(ms));
}
}
void test_MS_TO_TICKS_calledWithRemainderOfFourMillisecondMultiples_ExpectTicksRoundedUp(void)
{
uint8_t ms = anyByte();
uint8_t roundedUpTicks = ms / 4 + 1;
uint8_t msMultipleOfFour = (ms / 4) * 4;
for (uint8_t remainder = 1; remainder <= 3; remainder++)
{
TEST_ASSERT_EQUAL_UINT8(
roundedUpTicks,
MS_TO_TICKS(msMultipleOfFour + remainder));
}
}
void test_nearSchedulerInitialise_called_expectNcoModuleIsEnabled(void)
{
PMD1 = anyByteWithMaskSet(_PMD1_NCO1MD_MASK);
uint8_t originalPmd1 = PMD1;
nearSchedulerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd1 & ~_PMD1_NCO1MD_MASK, PMD1);
}
void test_nearSchedulerInitialise_called_expectNcoIsDisabled(void)
{
NCO1CON = anyByteWithMaskSet(_NCO1CON_N1EN_MASK);
nearSchedulerInitialise();
TEST_ASSERT_FALSE(NCO1CONbits.N1EN);
}
void test_nearSchedulerInitialise_called_expectNcoPolarityIsNotInverted(void)
{
NCO1CON = anyByteWithMaskSet(_NCO1CON_N1POL_MASK);
nearSchedulerInitialise();
TEST_ASSERT_FALSE(NCO1CONbits.N1POL);
}
void test_nearSchedulerInitialise_called_expectNcoModeIsFixedDutyCycle(void)
{
NCO1CON = anyByteWithMaskSet(_NCO1CON_N1PFM_MASK);
nearSchedulerInitialise();
TEST_ASSERT_FALSE(NCO1CONbits.N1PFM);
}
void test_nearSchedulerInitialise_called_expectNcoPulseWidthBitsAreClear(void)
{
NCO1CLK = anyByte();
nearSchedulerInitialise();
TEST_ASSERT_BITS_LOW(_NCO1CLK_N1PWS_MASK, NCO1CLK);
}
void test_nearSchedulerInitialise_called_expectNcoClockSourceIsSecondaryOscillator(void)
{
NCO1CLK = anyByte();
nearSchedulerInitialise();
TEST_ASSERT_EQUAL_INT(0b0101, (NCO1CLK >> _NCO1CLK_N1CKS_POSITION) & 0b1111);
}
void test_nearSchedulerInitialise_called_expectNcoIncrementGivesOverflowPeriodOfFourMillisecondsWhenUsedWith32768HzCrystal(void)
{
const uint16_t ncoIncrement = 8000;
NCO1INCU = anyByte();
NCO1INCH = anyByte();
NCO1INCL = anyByte();
nearSchedulerInitialise();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, NCO1INCU, "NCO1INCU");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
(ncoIncrement >> 8) & 0xff,
NCO1INCH,
"NCO1INCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
ncoIncrement & 0xff,
NCO1INCL,
"NCO1INCL");
}
void test_nearSchedulerInitialise_called_expectNcoCanWakeFromSleep(void)
{
PIE7 = anyByteWithMaskClear(_PIE7_NCO1IE_MASK);
uint8_t originalPie7 = PIE7;
nearSchedulerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie7 | _PIE7_NCO1IE_MASK, PIE7);
}
void test_nearSchedulerInitialise_called_expectNcoInterruptFlagIsClear(void)
{
PIR7 = anyByteWithMaskSet(_PIR7_NCO1IF_MASK);
uint8_t originalPir7 = PIR7;
nearSchedulerInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPir7 & ~_PIR7_NCO1IF_MASK, PIR7);
}
<file_sep>/src/firmware/tests/Location/TestLocation.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Location.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Location.c")
const struct Event eventEmptyArgs = { };
static void onLocationChanged(const struct Event *event);
static const struct LocationChanged *locationChangedEventArgs;
static union ApplicationNvmSettings appNvmSettings;
void onBeforeTest(void)
{
eventInitialise();
static const struct EventSubscription onLocationChangedSubscription =
{
.type = LOCATION_CHANGED,
.handler = &onLocationChanged,
.state = (void *) 0
};
eventSubscribe(&onLocationChangedSubscription);
locationChangedEventArgs = (const struct LocationChanged *) 0;
appNvmSettings.location.longitudeOffset = (int8_t) anyByte();
appNvmSettings.location.latitudeOffset = (int8_t) anyByte();
stubNvmApplicationSettings(&appNvmSettings);
}
static void onLocationChanged(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Null event !");
locationChangedEventArgs = (const struct LocationChanged *) event->args;
TEST_ASSERT_NOT_NULL_MESSAGE(locationChangedEventArgs, "Null event args !");
TEST_ASSERT_NOT_NULL_MESSAGE(locationChangedEventArgs->location, "Null location !");
}
void onAfterTest(void)
{
}
void test_locationInitialise_expectNoLocationChangedEventIsPublished(void)
{
locationInitialise();
dispatchAllEvents();
TEST_ASSERT_NULL(locationChangedEventArgs);
}
void test_onNvmSettingsChanged_eventPublishedWithSameLongitudeAndLatitude_expectNoLocationChangedEventIsPublished(void)
{
locationInitialise();
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NULL(locationChangedEventArgs);
}
void test_onNvmSettingsChanged_eventPublishedWithDifferentLongitudeAndSameLatitude_expectLocationChangedEventIsPublishedWithUpdatedLongitude(void)
{
locationInitialise();
appNvmSettings.location.longitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.longitudeOffset);
stubNvmApplicationSettings(&appNvmSettings);
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(locationChangedEventArgs);
TEST_ASSERT_EQUAL_INT8(appNvmSettings.location.longitudeOffset, locationChangedEventArgs->location->longitudeOffset);
}
void test_onNvmSettingsChanged_eventPublishedWithDifferentLongitudeAndSameLatitude_expectLocationChangedEventIsPublishedWithPreviousLatitude(void)
{
locationInitialise();
appNvmSettings.location.longitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.longitudeOffset);
stubNvmApplicationSettings(&appNvmSettings);
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(locationChangedEventArgs);
TEST_ASSERT_EQUAL_INT8(appNvmSettings.location.latitudeOffset, locationChangedEventArgs->location->latitudeOffset);
}
void test_onNvmSettingsChanged_eventPublishedWithSameLongitudeAndDifferentLatitude_expectLocationChangedEventIsPublishedWithUpdatedLatitude(void)
{
locationInitialise();
appNvmSettings.location.latitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.latitudeOffset);
stubNvmApplicationSettings(&appNvmSettings);
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(locationChangedEventArgs);
TEST_ASSERT_EQUAL_INT8(appNvmSettings.location.latitudeOffset, locationChangedEventArgs->location->latitudeOffset);
}
void test_onNvmSettingsChanged_eventPublishedWithSameLongitudeAndDifferentLatitude_expectLocationChangedEventIsPublishedWithPreviousLongitude(void)
{
locationInitialise();
appNvmSettings.location.latitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.latitudeOffset);
stubNvmApplicationSettings(&appNvmSettings);
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(locationChangedEventArgs);
TEST_ASSERT_EQUAL_INT8(appNvmSettings.location.longitudeOffset, locationChangedEventArgs->location->longitudeOffset);
}
void test_onNvmSettingsChanged_eventPublishedWithDifferentLongitudeAndLatitude_expectLocationChangedEventIsPublishedWithUpdatedValues(void)
{
locationInitialise();
appNvmSettings.location.longitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.longitudeOffset);
appNvmSettings.location.latitudeOffset = (int8_t) anyByteExcept((uint8_t) appNvmSettings.location.latitudeOffset);
stubNvmApplicationSettings(&appNvmSettings);
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(locationChangedEventArgs);
TEST_ASSERT_EQUAL_INT8_MESSAGE(appNvmSettings.location.longitudeOffset, locationChangedEventArgs->location->longitudeOffset, "LONG");
TEST_ASSERT_EQUAL_INT8_MESSAGE(appNvmSettings.location.latitudeOffset, locationChangedEventArgs->location->latitudeOffset, "LAT");
}
<file_sep>/src/utilities/calibrator/calibration_results_loader.py
import jsonpickle
from intelhex import IntelHex
from pathlib import Path
from struct import unpack
from calibration_results import CalibrationResults
from cluck2sesame_device import Cluck2SesameDevice
from cluck2sesame_nvm_settings import Cluck2SesameNvmSettings
class CalibrationResultsLoader:
def __init__(self, results_path):
if results_path is None:
raise TypeError('results_path')
if not isinstance(results_path, Path):
results_path = Path(results_path)
if not results_path.is_dir():
raise ValueError('results_path', 'Calibration path needs to be a directory')
self._results_path = results_path
def load(self):
calibration_points = []
for point_file in self._results_path.glob('point.*.json'):
calibration_points.append(jsonpickle.decode(point_file.read_text()))
nvm_settings_hex = IntelHex(str(Path(self._results_path, 'nvm-settings.pre.hex')))
nvm_settings = Cluck2SesameNvmSettings(
Cluck2SesameDevice.NVM_SETTINGS_ADDRESS,
CalibrationResultsLoader._bytes_to_words(nvm_settings_hex.tobinarray()))
return CalibrationResults(nvm_settings, calibration_points)
@staticmethod
def _bytes_to_words(bytes):
return [word for word in unpack('<' + 'H' * (len(bytes) // 2), bytes)]
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/VoltageRegulatorFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_VOLTAGEREGULATOR_VOLTAGEREGULATORFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_VOLTAGEREGULATOR_VOLTAGEREGULATORFIXTURE_H
#include "Platform/NearScheduler.h"
extern void assertEventPublishNotCalled(
EventType type,
const void *args,
int numCalls);
extern void assertScheduleAddedWithHandler(void);
extern void fullyEnableVoltageRegulator(void);
extern void callScheduleHandlerAndForget(void);
extern void callScheduleHandlerIfPresentAndForget(void);
extern void fullyEnableVoltageRegulatorWithoutAssertions(void);
extern const struct NearSchedule *requestedSchedule;
#endif
<file_sep>/src/firmware/tests/Platform/Battery/TestBatteryVoltageSampled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/Battery.h"
#include "BatteryFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Battery.c")
static void onBatteryVoltageSampled(const struct Event *event);
static uint16_t anyValidFvrSample(void);
static const struct BatteryVoltageSampled *batteryVoltageSampledEventArgs;
void onBeforeTest(void)
{
batteryFixtureSetUp();
static const struct EventSubscription onBatteryVoltageSampledSubscription =
{
.type = BATTERY_VOLTAGE_SAMPLED,
.handler = &onBatteryVoltageSampled,
.state = (void *) 0
};
eventSubscribe(&onBatteryVoltageSampledSubscription);
batteryVoltageSampledEventArgs = (const struct BatteryVoltageSampled *) 0;
}
static void onBatteryVoltageSampled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Null event !");
batteryVoltageSampledEventArgs = (const struct BatteryVoltageSampled *) event->args;
TEST_ASSERT_NOT_NULL_MESSAGE(batteryVoltageSampledEventArgs, "Null event args !");
}
void onAfterTest(void)
{
batteryFixtureTearDown();
}
void test_batteryInitialise_expectNoBatteryVoltageSampledEventIsPublished(void)
{
batteryInitialise();
dispatchAllEvents();
TEST_ASSERT_NULL(batteryVoltageSampledEventArgs);
}
void test_onMonitoredParametersSampled_eventPublishedWithIdVddRegulatedFlagSet_expectNoBatteryVoltageSampledEventIsPublished(void)
{
batteryInitialise();
struct MonitoredParametersSampled eventArgs =
{
.fvr = anyValidFvrSample(),
.flags = { .isVddRegulated = 1 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NULL(batteryVoltageSampledEventArgs);
}
static uint16_t anyValidFvrSample(void)
{
return FVR_MINIMUM_VALID_SAMPLE + anyWordLessThan(FVR_MAXIMUM_VALID_SAMPLE - FVR_MINIMUM_VALID_SAMPLE + 1);
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClearAndLessThanMinimumFvrSample_expectNoBatteryVoltageSampledEventIsPublished(void)
{
uint16_t fvrMillivolts = stubAnyDiaFvra2xMillivolts();
stubDiaFvra2xMillivolts(fvrMillivolts);
batteryInitialise();
for (uint16_t i = 1; i < 10; i++)
{
struct MonitoredParametersSampled eventArgs =
{
.fvr = FVR_MINIMUM_VALID_SAMPLE - i,
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NULL(batteryVoltageSampledEventArgs);
}
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClearAndMoreThanMaximumFvrSample_expectNoBatteryVoltageSampledEventIsPublished(void)
{
uint16_t fvrMillivolts = stubAnyDiaFvra2xMillivolts();
stubDiaFvra2xMillivolts(fvrMillivolts);
batteryInitialise();
for (uint16_t i = 1; i < 10; i++)
{
struct MonitoredParametersSampled eventArgs =
{
.fvr = FVR_MAXIMUM_VALID_SAMPLE + i,
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NULL(batteryVoltageSampledEventArgs);
}
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClear_expectPublishedEventHasFvrSample(void)
{
stubAnyDiaFvra2xMillivolts();
batteryInitialise();
struct MonitoredParametersSampled eventArgs =
{
.fvr = anyValidFvrSample(),
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryVoltageSampledEventArgs);
TEST_ASSERT_EQUAL_UINT16(eventArgs.fvr, batteryVoltageSampledEventArgs->sample);
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClearAndMinimumFvrSample_expectPublishedEventHasCalculatedVddMillivolts(void)
{
uint16_t fvrMillivolts = stubAnyDiaFvra2xMillivolts();
uint32_t vddMillivolts = (uint32_t) fvrMillivolts * 8192 / FVR_MINIMUM_VALID_SAMPLE;
stubDiaFvra2xMillivolts(fvrMillivolts);
batteryInitialise();
struct MonitoredParametersSampled eventArgs =
{
.fvr = FVR_MINIMUM_VALID_SAMPLE,
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryVoltageSampledEventArgs);
TEST_ASSERT_EQUAL_UINT16(vddMillivolts, batteryVoltageSampledEventArgs->millivolts);
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClearAndMaximumFvrSample_expectPublishedEventHasCalculatedVddMillivolts(void)
{
uint16_t fvrMillivolts = stubAnyDiaFvra2xMillivolts();
uint32_t vddMillivolts = (uint32_t) fvrMillivolts * 8192 / FVR_MAXIMUM_VALID_SAMPLE;
stubDiaFvra2xMillivolts(fvrMillivolts);
batteryInitialise();
struct MonitoredParametersSampled eventArgs =
{
.fvr = FVR_MAXIMUM_VALID_SAMPLE,
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryVoltageSampledEventArgs);
TEST_ASSERT_EQUAL_UINT16(vddMillivolts, batteryVoltageSampledEventArgs->millivolts);
}
void test_onMonitoredParametersSampled_eventPublishedWithIsVddRegulatedFlagClearAndValidFvrSample_expectPublishedEventHasCalculatedVddMillivolts(void)
{
uint16_t fvrMillivolts = stubAnyDiaFvra2xMillivolts();
stubDiaFvra2xMillivolts(fvrMillivolts);
batteryInitialise();
struct MonitoredParametersSampled eventArgs =
{
.fvr = anyValidFvrSample(),
.flags = { .isVddRegulated = 0 }
};
eventPublish(MONITORED_PARAMETERS_SAMPLED, &eventArgs);
dispatchAllEvents();
uint32_t vddMillivolts = (uint32_t) fvrMillivolts * 8192 / eventArgs.fvr;
TEST_ASSERT_NOT_NULL(batteryVoltageSampledEventArgs);
TEST_ASSERT_EQUAL_UINT16(vddMillivolts, batteryVoltageSampledEventArgs->millivolts);
}
<file_sep>/src/firmware/tests/Platform/PeriodicMonitor/PeriodicMonitorFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_PERIODICMONITOR_PERIODICMONITORFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_PERIODICMONITOR_PERIODICMONITORFIXTURE_H
#include <stdint.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "Platform/Adc.h"
#include "Platform/PeriodicMonitor.h"
typedef void (*AdcSampleCallback)(struct AdcSample *);
extern void periodicMonitorFixtureSetUp(void);
extern void periodicMonitorFixtureTearDown(void);
extern void mockOnMonitoredParametersSampled(void);
extern void publishTimeChanged(const struct Time *now);
extern void stubAdcSampleFor(struct AdcSample *sample);
extern const struct MonitoredParametersSampled *monitoredParametersSampled;
extern uint8_t monitoredParametersSampledCalls;
extern uint8_t monitoredParametersSampledSequence;
extern uint8_t adcSampleCalls;
extern uint8_t adcSampleSequence;
extern AdcSampleCallback onAdcSample;
#endif
<file_sep>/src/firmware/src/Door/DoorOnOpenScheduleActioned.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/NvmSettings.h"
#include "../Platform/Motor.h"
#include "../ApplicationNvmSettings.h"
#include "Door.h"
void doorOnOpenScheduleActioned(const struct Event *event)
{
switch (doorState.current)
{
case DoorState_Opened:
doorState.transition = DoorTransition_Unchanged;
break;
case DoorState_Closed:
motorEnable();
doorStartOpening(
DoorState_Opening,
DoorState_Opening_WaitingForEnabledMotor);
doorState.transition = DoorTransition_Open;
break;
case DoorState_Unknown:
motorEnable();
doorStartFindingBottom(
DoorState_FindBottom,
DoorState_FindBottom_WaitingForEnabledMotor);
default:
doorState.transition = DoorTransition_Open;
};
}
void doorStartOpening(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState)
{
if (motorIsEnabled())
{
motorLimitIsMaximumLoad();
motorOn((motorEnabledState == DoorState_ManualOpening)
? (int16_t) MANUAL_MOVEMENT_LIMIT
: (int16_t) nvmSettings.application.door.height);
doorState.current = motorEnabledState;
}
else
doorState.current = motorDisabledState;
}
<file_sep>/src/firmware/tests/Platform/Clock/TestClockGetSetNow1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "ClockGetSetNowFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
void onBeforeTest(void)
{
clockFixtureSetUp();
clockGetSetNowFixtureSetUp();
}
void onAfterTest(void)
{
clockGetSetNowFixtureTearDown();
clockFixtureTearDown();
}
void test_clockGetNowGmt_called_expectSecondsIsTmr0l(void)
{
stubAnyDateTime();
TMR0L = anyByte();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8(TMR0L, now.time.second);
}
void test_clockGetNowGmt_calledWhenClockLessThan59MinutesTicks_expectNewMinute(void)
{
TMR0L = anyByte();
stubAnyDateTimeWithHourAndMinute(anyByteLessThan(23), anyByteLessThan(59));
struct DateAndTimeGet before;
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(TMR0L, now.time.second, "SS");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.time.minute + 1, now.time.minute, "MM");
assertEqualDateTimeExceptMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOf59MinutesTicks_expectNewHourAndZeroMinutes(void)
{
TMR0L = anyByte();
stubAnyDateTimeWithHourAndMinute(anyByteLessThan(23), 59);
struct DateAndTimeGet before;
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.time.hour + 1, now.time.hour, "HH");
assertEqualDateTimeExceptHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOf23HoursAnd59MinutesTicks_expectNewDayAndZeroHoursAndMinutes(void)
{
TMR0L = anyByte();
stubAnyDateTimeWithDayAndHourAndMinute(
1 + anyByteLessThan(28),
23,
59);
struct DateAndTimeGet before;
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.day + 1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.dayOfYear + 1, now.date.dayOfYear, "DoY");
assertEqualDateTimeExceptDayAndHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfNonLeapYearMonthTicks_expectNewMonthAndFirstDayAndZeroHoursAndMinutes(void)
{
static const uint8_t daysInMonth[] =
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30
};
for (uint8_t month = 0; month < 11; month++)
{
struct DateAndTimeGet before =
{
.date =
{
.year = anyNonLeapYearLessThan(99),
.month = 1 + month,
.day = daysInMonth[month]
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.dayOfYear + 1, now.date.dayOfYear, "DoY");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.month + 1, now.date.month, "M");
assertEqualDateTimeExceptMonthAndDayAndHourAndMinute(&before, &now);
}
}
void test_clockGetNowGmt_calledWhenClockOf28FebruaryInLeapYearTicks_expectLastDayOfFebruaryAndZeroHoursAndMinutes(void)
{
struct DateAndTimeGet before =
{
.date =
{
.year = anyLeapYear(),
.month = 2,
.day = 28
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(29, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.dayOfYear + 1, now.date.dayOfYear, "DoY");
assertEqualDateTimeExceptDayAndHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfFebruaryInLeapYearMonthTicks_expectNewMonthAndFirstDayAndZeroHoursAndMinutes(void)
{
struct DateAndTimeGet before =
{
.date =
{
.year = anyLeapYear(),
.month = 2,
.day = 29
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.dayOfYear + 1, now.date.dayOfYear, "DoY");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.month + 1, now.date.month, "M");
assertEqualDateTimeExceptMonthAndDayAndHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfNonLeapYearDecemberTicks_expectNewYearAndAndFirstMonthAndDayAndZeroHoursAndMinutes(void)
{
struct DateAndTimeGet before =
{
.date =
{
.year = anyNonLeapYearLessThan(99),
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.date.dayOfYear, "DoY");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.month, "M");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.year + 1, now.date.year, "Y");
assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(&before, &now);
}
<file_sep>/src/utilities/calibrator/calibration_log.py
import jsonpickle
from pathlib import Path
from intelhex import IntelHex
class CalibrationLog:
def __init__(self, path):
if path is None:
raise TypeError('path')
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
raise ValueError('path', 'Calibration path needs to be a directory')
self._path = path
def for_device(self, device_id):
path = Path(self._path, device_id)
return DeviceCalibrationLog(path)
class DeviceCalibrationLog:
def __init__(self, path):
if path is None:
raise TypeError('path')
if not isinstance(path, Path):
path = Path(path)
path.mkdir(exist_ok=True)
if not path.is_dir():
raise ValueError('path', 'Calibration path needs to be a directory')
self._path = path
def add_device_information_area(self, dia):
self._write_raw_words_as_hex('dia.hex', dia)
return self
def _write_raw_words_as_hex(self, filename, section, high_mask=0x3f):
hex_file = IntelHex()
addr = section.address * 2
for word in section.raw:
hex_file[addr + 0] = (word >> 0) & 0xff
hex_file[addr + 1] = (word >> 8) & high_mask
addr += 2
hex_file.write_hex_file(self._file_path_for(filename))
def _file_path_for(self, filename):
return Path(self._path, filename)
def add_initial_nvm_settings(self, nvm_settings):
self._write_raw_words_as_hex('nvm-settings.pre.hex', nvm_settings)
return self
def add_calibrated_nvm_settings(self, nvm_settings):
self._write_raw_words_as_hex('nvm-settings.post.hex', nvm_settings)
return self
def add_calibration_points(self, calibration_points):
for i in range(0, len(calibration_points)):
self._add_calibration_point(self._file_path_for(f'point.{i}.json'), calibration_points[i])
return self
def _add_calibration_point(self, file, calibration_point):
file.write_text(jsonpickle.encode(calibration_point, indent=4))
def add_calibration_results(self, results):
file = self._file_path_for('results.json')
file.write_text(jsonpickle.encode(results, indent=4))
return self._add_crystal_parabolas(results)
def _add_crystal_parabolas(self, results):
template = Path('crystal-template.m').read_text()
DeviceCalibrationLog._write_crystal_parabola_octave(template, results.low_vdd, self._file_path_for('crystal-low-vdd.m'))
DeviceCalibrationLog._write_crystal_parabola_octave(template, results.high_vdd, self._file_path_for('crystal-high-vdd.m'))
DeviceCalibrationLog._write_crystal_parabola_octave(template, results.mean_vdd, self._file_path_for('crystal-mean-vdd.m'))
return self
@staticmethod
def _write_crystal_parabola_octave(template, results, filename):
(temperatures_adc, temperatures_celsius) = DeviceCalibrationLog._temperatures_from(results.calibration_points)
coefficients = ', '.join([str(c) for c in results.crystal_parabola.coefficients])
filename.write_text(template
.replace('{crystal_coefficients}', coefficients)
.replace('{temperatures_adc}', temperatures_adc)
.replace('{temperatures_celsius}', temperatures_celsius)
.replace('{temperature_high_adc}', str(results.highest_temperature_calibration_point.temperature_adc))
.replace('{temperature_high_celsius}', str(results.highest_temperature_calibration_point.temperature_celsius))
.replace('{temperature_coefficient}', str(results.temperature_coefficient))
.replace('{vdd_volts}', str(results.vdd_volts)))
@staticmethod
def _temperatures_from(calibration_points):
return (
', '.join([str(point.temperature_adc) for point in calibration_points]),
', '.join([str(point.temperature_celsius) for point in calibration_points]))
<file_sep>/src/firmware/src/Platform/Nvm.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_NVM_H
#define __CLUCK2SESAME_SRC_PLATFORM_NVM_H
#include <stdint.h>
extern uint16_t nvmWordAt(uint16_t address);
#endif
<file_sep>/src/firmware/src/Platform/Temperature.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include "Event.h"
#include "NvmSettings.h"
#include "PeriodicMonitor.h"
#include "Temperature.h"
static void onMonitoredParametersSampled(const struct Event *event);
static bool hasPreviousSample;
static uint8_t previousSampleTimestamp;
static int16_t previousSampleCelsius;
static int32_t scaledTemperatureCoefficient;
void temperatureInitialise(void)
{
static const struct EventSubscription onMonitoredParametersSampledSubscription =
{
.type = MONITORED_PARAMETERS_SAMPLED,
.handler = &onMonitoredParametersSampled,
.state = (void *) 0
};
eventSubscribe(&onMonitoredParametersSampledSubscription);
hasPreviousSample = false;
scaledTemperatureCoefficient = nvmSettings.platform.temperature.temperatureCoefficient;
scaledTemperatureCoefficient *= -10;
}
static void onMonitoredParametersSampled(const struct Event *event)
{
const struct MonitoredParametersSampled *args = (const struct MonitoredParametersSampled *) event->args;
static struct TemperatureSampled eventArgs;
eventArgs.sample = args->temperature;
int32_t celsius = scaledTemperatureCoefficient;
celsius *= (int16_t) (((eventArgs.sample + 4) >> 3) - nvmSettings.platform.temperature.temperatureHighAdc);
celsius += (((int32_t) nvmSettings.platform.temperature.temperatureHighCelsius + 25 * 10) << 16) + 32768;
eventArgs.currentCelsius = (int16_t) (celsius >> 16);
if (!hasPreviousSample)
{
eventArgs.deltaSeconds = 0;
eventArgs.deltaCelsius = 0;
hasPreviousSample = true;
}
else
{
eventArgs.deltaSeconds = args->timestamp - previousSampleTimestamp;
eventArgs.deltaCelsius = eventArgs.currentCelsius - previousSampleCelsius;
}
previousSampleTimestamp = args->timestamp;
previousSampleCelsius = eventArgs.currentCelsius;
eventPublish(TEMPERATURE_SAMPLED, &eventArgs);
}
<file_sep>/src/firmware/src/Platform/Poll.c
#include <xc.h>
#include "Main.h"
#include "Event.h"
void poll(void)
{
if (!eventDispatchNext())
eventPublish(ALL_EVENTS_DISPATCHED, &eventEmptyArgs);
}
<file_sep>/src/firmware/src/Platform/Nvm.c
#include <xc.h>
#include <stdint.h>
uint16_t nvmWordAt(uint16_t address)
{
NVMCON1bits.NVMREGS = (address & 0x8000) ? 1 : 0;
NVMADR = address;
NVMCON1bits.RD = 1;
asm("nop");
return NVMDAT;
}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorDisable2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
TEST_FILE("Platform/VoltageRegulatorFixture.c")
const struct Event eventEmptyArgs = { };
void test_voltageRegulatorDisable_calledMoreTimesThanEnable_expectEnableCountDoesNotGetOutOfSync(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
voltageRegulatorDisable();
voltageRegulatorDisable();
voltageRegulatorDisable();
voltageRegulatorEnable();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB2, "EN");
voltageRegulatorDisable();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB2, "DIS");
}
void test_voltageRegulatorDisable_calledWhenAlreadyDisabled_expectNoEventIsPublished(void)
{
voltageRegulatorInitialise();
eventPublish_StubWithCallback(assertEventPublishNotCalled);
voltageRegulatorDisable();
}
void test_voltageRegulatorDisable_calledWhenStillEnabled_expectNoEventIsPublished(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
voltageRegulatorEnable();
eventPublish_StubWithCallback(assertEventPublishNotCalled);
voltageRegulatorDisable();
}
void test_voltageRegulatorDisable_calledWhenNotEnabled_expectVoltageRegulatorDisabledEventIsNotPublished(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
const struct VoltageRegulatorDisabled emptyArgs = { };
eventPublish_StubWithCallback(assertEventPublishNotCalled);
voltageRegulatorDisable();
}
void test_voltageRegulatorDisable_calledWhenVoltageRailHasStabilised_expectVoltageRegulatorDisabledEventIsNotPublished(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
const struct VoltageRegulatorDisabled emptyArgs = { };
eventPublish_StubWithCallback(assertEventPublishNotCalled);
voltageRegulatorDisable();
}
void test_voltageRegulatorDisable_calledWhenDisabled_expectVoltageRegulatorDisabledEventIsPublished(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
const struct VoltageRegulatorDisabled emptyArgs = { };
eventPublish_Expect(VOLTAGE_REGULATOR_DISABLED, &emptyArgs);
voltageRegulatorDisable();
}
void test_voltageRegulatorDisable_calledBeforeBeingFullyEnabled_expectNoEventPublished(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
voltageRegulatorDisable();
eventPublish_StubWithCallback(assertEventPublishNotCalled);
callScheduleHandlerAndForget();
}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/VoltageRegulatorFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
static void ensureScheduleHandlerIsNotOmittedByTheCompiler(void);
const struct NearSchedule *requestedSchedule;
const struct Event eventEmptyArgs = { };
void onBeforeTest(void)
{
requestedSchedule = (const struct NearSchedule *) 0;
}
void onAfterTest(void)
{
ensureScheduleHandlerIsNotOmittedByTheCompiler();
}
static void ensureScheduleHandlerIsNotOmittedByTheCompiler(void)
{
static volatile uint8_t neverTrue = 0;
if (neverTrue)
requestedSchedule->handler((void *) 0);
}
void assertEventPublishNotCalled(
EventType type,
const void *args,
int numCalls)
{
TEST_FAIL_MESSAGE("Expected eventPublish() not to be called");
}
void assertScheduleAddedWithHandler(void)
{
TEST_ASSERT_NOT_NULL_MESSAGE(requestedSchedule, "Schedule");
TEST_ASSERT_NOT_NULL_MESSAGE(requestedSchedule->handler, "Handler");
}
void nearSchedulerAdd(const struct NearSchedule *schedule)
{
requestedSchedule = schedule;
}
void fullyEnableVoltageRegulator(void)
{
voltageRegulatorEnable();
callScheduleHandlerAndForget();
callScheduleHandlerAndForget();
}
void callScheduleHandlerAndForget(void)
{
assertScheduleAddedWithHandler();
callScheduleHandlerIfPresentAndForget();
}
void callScheduleHandlerIfPresentAndForget(void)
{
if (!requestedSchedule || !requestedSchedule->handler)
return;
void *state = requestedSchedule->state;
NearScheduleHandler handler = requestedSchedule->handler;
requestedSchedule = (const struct NearSchedule *) 0;
handler(state);
}
void fullyEnableVoltageRegulatorWithoutAssertions(void)
{
voltageRegulatorEnable();
callScheduleHandlerIfPresentAndForget();
callScheduleHandlerIfPresentAndForget();
}
<file_sep>/src/firmware/tests/Platform/HexDigits/TestHexDigits.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <unity.h>
#include "Platform/HexDigits.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/HexDigits.c")
static uint8_t hexDigitForHighNybbleOf(uint8_t byte);
static uint8_t hexDigitForLowNybbleOf(uint8_t byte);
static uint16_t anyCasedFourHexDigitsInto(uint8_t *outFourDigits);
static uint8_t anyNonHexDigit(void);
static const uint8_t *hexDigits = (const uint8_t *) "0123456789abcdef";
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_hexDigitsForByte_called_expectExpectTwoCorrectHexDigits(void)
{
for (uint16_t i = 0; i < 256; i++)
{
uint8_t digits[2];
uint8_t byte = (uint8_t) i;
hexDigitsForByte(digits, byte);
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForHighNybbleOf(byte), digits[0], "0");
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForLowNybbleOf(byte), digits[1], "1");
}
}
static uint8_t hexDigitForHighNybbleOf(uint8_t byte)
{
return hexDigits[(byte >> 4) & 0x0f];
}
static uint8_t hexDigitForLowNybbleOf(uint8_t byte)
{
return hexDigits[byte & 0x0f];
}
void test_hexDigitsForWord_called_expectExpectFourCorrectHexDigits(void)
{
for (uint32_t i = 0; i < 65536l; i++)
{
uint8_t digits[4];
uint16_t word = (uint16_t) i;
hexDigitsForWord(digits, word);
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForHighNybbleOf((uint8_t) (word >> 8)), digits[0], "0");
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForLowNybbleOf((uint8_t) (word >> 8)), digits[1], "1");
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForHighNybbleOf((uint8_t) word), digits[2], "2");
TEST_ASSERT_EQUAL_MESSAGE(hexDigitForLowNybbleOf((uint8_t) word), digits[3], "3");
}
}
void test_hexDigitsToWord_calledWithNullOutWord_expectFalseIsReturned(void)
{
uint8_t inFourDigits[4];
anyCasedFourHexDigitsInto(inFourDigits);
bool wasSuccessful = hexDigitsToWord((uint16_t *) 0, inFourDigits);
TEST_ASSERT_FALSE(wasSuccessful);
}
static uint16_t anyCasedFourHexDigitsInto(uint8_t *outFourDigits)
{
if (!outFourDigits)
return 0;
uint16_t equivalentWord = 0;
for (uint8_t i = 0; i < 4; i++, outFourDigits++)
{
uint16_t anyNybble = anyByteLessThan(16);
equivalentWord <<= 4;
equivalentWord |= anyNybble;
*outFourDigits = hexDigits[anyNybble];
if (*outFourDigits >= 'a' && anyBoolean())
*outFourDigits = *outFourDigits - 'a' + 'A';
}
return equivalentWord;
}
void test_hexDigitsToWord_calledWithNullInFourDigits_expectFalseIsReturned(void)
{
uint16_t outWord;
bool wasSuccessful = hexDigitsToWord(&outWord, (uint8_t *) 0);
TEST_ASSERT_FALSE(wasSuccessful);
}
void test_hexDigitsToWord_calledWithNullInFourDigits_expectOutWordIsNotModified(void)
{
uint16_t outWord = anyWord();
uint16_t originalOutWord = outWord;
hexDigitsToWord(&outWord, (uint8_t *) 0);
TEST_ASSERT_EQUAL_UINT16(originalOutWord, outWord);
}
void test_hexDigitsToWord_calledWithInvalidFirstHexDigit_expectFalseIsReturned(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[0] = anyNonHexDigit();
uint16_t outWord;
bool wasSuccessful = hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_FALSE(wasSuccessful);
}
static uint8_t anyNonHexDigit(void)
{
while (true)
{
uint8_t nonHexDigit = anyByte();
if (nonHexDigit < '0' || nonHexDigit > 'f')
return nonHexDigit;
if (nonHexDigit > '9' && nonHexDigit < 'A')
return nonHexDigit;
if (nonHexDigit > 'F' && nonHexDigit < 'a')
return nonHexDigit;
}
}
void test_hexDigitsToWord_calledWithInvalidFirstHexDigit_expectOutWordIsNotModified(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[0] = anyNonHexDigit();
uint16_t outWord = anyWord();
uint16_t originalOutWord = outWord;
hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_EQUAL_UINT16(originalOutWord, outWord);
}
void test_hexDigitsToWord_calledWithInvalidSecondHexDigit_expectFalseIsReturned(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[1] = anyNonHexDigit();
uint16_t outWord;
bool wasSuccessful = hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_FALSE(wasSuccessful);
}
void test_hexDigitsToWord_calledWithInvalidSecondHexDigit_expectOutWordIsNotModified(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[1] = anyNonHexDigit();
uint16_t outWord = anyWord();
uint16_t originalOutWord = outWord;
hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_EQUAL_UINT16(originalOutWord, outWord);
}
void test_hexDigitsToWord_calledWithInvalidThirdHexDigit_expectFalseIsReturned(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[2] = anyNonHexDigit();
uint16_t outWord;
bool wasSuccessful = hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_FALSE(wasSuccessful);
}
void test_hexDigitsToWord_calledWithInvalidThirdHexDigit_expectOutWordIsNotModified(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[2] = anyNonHexDigit();
uint16_t outWord = anyWord();
uint16_t originalOutWord = outWord;
hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_EQUAL_UINT16(originalOutWord, outWord);
}
void test_hexDigitsToWord_calledWithInvalidFourthHexDigit_expectFalseIsReturned(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[3] = anyNonHexDigit();
uint16_t outWord;
bool wasSuccessful = hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_FALSE(wasSuccessful);
}
void test_hexDigitsToWord_calledWithInvalidFourthHexDigit_expectOutWordIsNotModified(void)
{
uint8_t invalidInFourDigits[4];
anyCasedFourHexDigitsInto(invalidInFourDigits);
invalidInFourDigits[3] = anyNonHexDigit();
uint16_t outWord = anyWord();
uint16_t originalOutWord = outWord;
hexDigitsToWord(&outWord, invalidInFourDigits);
TEST_ASSERT_EQUAL_UINT16(originalOutWord, outWord);
}
void test_hexDigitsToWord_calledWithValidHexDigits_expectTrueIsReturned(void)
{
uint16_t outWord;
uint8_t inFourDigits[5] = {0};
anyCasedFourHexDigitsInto(inFourDigits);
bool wasSuccessful = hexDigitsToWord(&outWord, inFourDigits);
TEST_ASSERT_TRUE_MESSAGE(wasSuccessful, (char *) inFourDigits);
}
void test_hexDigitsToWord_calledWithValidHexDigits_expectCorrectWordIsReturned(void)
{
for (uint8_t i = 0; i < 10; i++)
{
uint16_t outWord;
uint8_t inFourDigits[5] = {0};
uint16_t correctWord = anyCasedFourHexDigitsInto(inFourDigits);
hexDigitsToWord(&outWord, inFourDigits);
TEST_ASSERT_EQUAL_UINT16_MESSAGE(correctWord, outWord, (char *) inFourDigits);
}
}
<file_sep>/src/firmware/src/Platform/PeriodicMonitor.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_PERIODICMONITOR_H
#define __CLUCK2SESAME_SRC_PLATFORM_PERIODICMONITOR_H
#include "Event.h"
#define MONITORED_PARAMETERS_SAMPLED ((EventType) 0x38)
struct MonitoredParametersSampled
{
uint8_t timestamp;
union
{
uint8_t all;
struct
{
unsigned int isVddRegulated : 1;
};
} flags;
uint16_t fvr;
uint16_t temperature;
};
extern void periodicMonitorInitialise(void);
#ifdef __PERIODICMONITOR_EXPOSE_INTERNALS
extern void periodicMonitorSampleNow(struct MonitoredParametersSampled *eventArgs);
#endif
#endif
<file_sep>/src/firmware/src/Platform/Lcd/LcdInitialise.c
#include <xc.h>
#include <stdint.h>
#include "../Event.h"
#include "../NvmSettings.h"
#include "../VoltageRegulator.h"
#include "Lcd.h"
#define PORTA_PIN_MASK 0b00000011
#define PORTC_PIN_MASK 0b11001111
#define PPS_OUT_PWM3 0x0b
#define PPS_OUT_PWM5 0x0d
struct LcdState lcdState;
static void buggyCompilerWorkaround(void)
{
static const struct LcdPutsTransaction dummy =
{
.buffer = _OMNITARGET,
.state = _OMNITARGET
};
lcdState.transaction.state = _OMNITARGET;
}
void lcdInitialise(void)
{
// TODO: THE NVM_SETTINGS_CHANGED EVENT SHOULD BE HANDLED
PMD3bits.PWM3MD = 0;
PMD3bits.PWM5MD = 0;
ANSELA &= PORTA_PIN_MASK;
LATA &= PORTA_PIN_MASK;
ANSELC &= PORTC_PIN_MASK;
LATC &= PORTC_PIN_MASK;
TRISA &= PORTA_PIN_MASK;
TRISC &= PORTC_PIN_MASK;
PWM5CON = 0;
PWM5DCH = (nvmSettings.platform.lcd.contrast >> 2) & 0b00111111;
PWM5DCL = (uint8_t) (nvmSettings.platform.lcd.contrast << 6);
RA2PPS = PPS_OUT_PWM5;
ANSELAbits.ANSA2 = 1;
TRISAbits.TRISA2 = 1;
PWM3CON = 0;
PWM3DCH = (nvmSettings.platform.lcd.backlightBrightness >> 2) & 0b00111111;
PWM3DCL = (uint8_t) (nvmSettings.platform.lcd.backlightBrightness << 6);
RC5PPS = PPS_OUT_PWM3;
lcdState.enableCount = 0;
lcdState.flags.all = 0;
lcdState.flags.isBusy = 1;
static const struct EventSubscription onVoltageRegulatorEnabledSubscription =
{
.type = VOLTAGE_REGULATOR_ENABLED,
.handler = &lcdOnVoltageRegulatorEnabled,
.state = (void *) 0
};
eventSubscribe(&onVoltageRegulatorEnabledSubscription);
static const struct EventSubscription onVoltageRegulatorDisabledSubscription =
{
.type = VOLTAGE_REGULATOR_DISABLED,
.handler = &lcdOnVoltageRegulatorDisabled,
.state = (void *) 0
};
eventSubscribe(&onVoltageRegulatorDisabledSubscription);
}
<file_sep>/src/firmware/tests/Platform/Clock/TestClockTick.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "ClockGetSetNowFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
static void tickWithoutSettingInterruptFlag(void);
void onBeforeTest(void)
{
clockFixtureSetUp();
clockGetSetNowFixtureSetUp();
}
void onAfterTest(void)
{
clockFixtureTearDown();
}
void test_tick_onWokenFromSleepWhenTimerInterruptFlagIsClear_expectTimeIsNotIncremented(void)
{
stubAnyDateTime();
struct DateAndTimeGet before;
clockGetNowGmt(&before);
dispatchAllEvents();
PIR0bits.TMR0IF = 0;
tickWithoutSettingInterruptFlag();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
assertEqualDateTime(&before, &now);
}
static void tickWithoutSettingInterruptFlag(void)
{
publishWokenFromSleep();
dispatchAllEvents();
}
void test_tick_onWokenFromSleepWhenTimerInterruptFlagIsSet_expectTimeIsIncremented(void)
{
stubAnyDateTimeWithHourAndMinute(anyByteLessThan(23), anyByteLessThan(59));
struct DateAndTimeGet before;
clockGetNowGmt(&before);
dispatchAllEvents();
PIR0bits.TMR0IF = 1;
tickWithoutSettingInterruptFlag();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
assertEqualDateTimeExceptMinute(&before, &now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.time.minute + 1, now.time.minute, "MM");
}
void test_tick_onWokenFromSleepWhenTimerInterruptFlagIsSet_expectTimerInterruptFlagIsCleared(void)
{
PIR0 = anyByteWithMaskSet(_PIR0_TMR0IF_MASK);
uint8_t originalPir0 = PIR0;
tickWithoutSettingInterruptFlag();
TEST_ASSERT_EQUAL_UINT8(originalPir0 & ~_PIR0_TMR0IF_MASK, PIR0);
}
void test_tick_happensWhenTmr0hIsNotOneMinute_expectTmr0hIsResetToOneMinute(void)
{
TMR0H = anyByteExcept(59);
tick();
TEST_ASSERT_EQUAL_UINT8(59, TMR0H);
}
void test_tick_happens_expectTimeChangedEventIsPublished(void)
{
stubAnyDateTime();
dispatchAllEvents();
mockOnTimeChanged();
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, timeChangedCalls, "Num Events");
TEST_ASSERT_NOT_NULL_MESSAGE(timeChanged, "Event");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
&now.time,
timeChanged->now,
sizeof(struct Time),
"Time");
}
void test_tick_happensWhenTicksToNextDay_expectDateChangedEventIsPublished(void)
{
stubAnyDateTimeWithHourAndMinute(23, 59);
dispatchAllEvents();
mockOnDateChanged();
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, dateChangedCalls, "Num Events");
TEST_ASSERT_NOT_NULL_MESSAGE(dateChanged, "Event");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
&now.date,
dateChanged->today,
sizeof(struct DateWithFlags),
"Date");
}
void test_tick_happensWhenDoesNotTickToNextDay_expectNoDateChangedEventIsPublished(void)
{
stubAnyDateTimeWithHourAndMinute(23, anyByteLessThan(59));
dispatchAllEvents();
mockOnDateChanged();
tick();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, dateChangedCalls, "Num Events");
}
void test_tick_happensWhenTicksToNextDay_expectDateChangedEventIsPublishedBeforeTimeChanged(void)
{
stubAnyDateTimeWithHourAndMinute(23, 59);
dispatchAllEvents();
mockOnDateChanged();
mockOnTimeChanged();
tick();
TEST_ASSERT_TRUE(dateChangedSequence < timeChangedSequence);
}
void test_tick_happensWhenLeapYearTicksToNextYear_expectIsLeapYearFlagIsClear(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyLeapYear(),
.month = 12,
.day = 31
},
.time =
{
.hour = 23,
.minute = 59
}
};
clockSetNowGmt(&now);
dispatchAllEvents();
mockOnDateChanged();
tick();
TEST_ASSERT_NOT_NULL(dateChanged);
TEST_ASSERT_FALSE(dateChanged->today->flags.isLeapYear);
}
void test_tick_happensWhenNonLeapYearTicksToNextYear_expectIsLeapYearFlagIsSet(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyLeapYear() + 3,
.month = 12,
.day = 31
},
.time =
{
.hour = 23,
.minute = 59
}
};
clockSetNowGmt(&now);
dispatchAllEvents();
mockOnDateChanged();
tick();
TEST_ASSERT_NOT_NULL(dateChanged);
TEST_ASSERT_TRUE(dateChanged->today->flags.isLeapYear);
}
<file_sep>/src/utilities/calibrator/calibration_point.py
from statistics import mean
class CalibrationPoint:
def __init__(self, samples, vdd_volts, temperature_celsius, clock_frequency_hz):
if samples is None:
raise TypeError('samples')
if vdd_volts is None:
raise TypeError('vdd_volts')
if temperature_celsius is None:
raise TypeError('temperature_celsius')
if clock_frequency_hz is None:
raise TypeError('clock_frequency_hz')
self._samples = samples.copy()
self._vdd_volts = vdd_volts
self._temperature_adc = int(mean([sample.temperature_adc_mean for sample in self._samples]) + 0.5)
self._temperature_celsius = temperature_celsius
self._clock_frequency_hz = clock_frequency_hz
@property
def samples(self): return self._samples.copy()
@property
def vdd_volts(self): return self._vdd_volts
@property
def temperature_adc(self): return self._temperature_adc
@property
def temperature_celsius(self): return self._temperature_celsius
@property
def clock_frequency_hz(self): return self._clock_frequency_hz
<file_sep>/src/firmware/tests/Platform/NearScheduler/NearSchedulerFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_NEARSCHEDULER_NEARSCHEDULERFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_NEARSCHEDULER_NEARSCHEDULERFIXTURE_H
#include <stdint.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/NearScheduler.h"
extern void tick(void);
extern void wokenFromSleep(void);
extern void assertNoHandlersCalled(void);
extern void assertHandlerCalledOnceWith(const void *state);
extern void assertHandlerCalledTimes(uint8_t times);
extern void assertHandlerCalledWith(const void *state);
extern void spyHandler(void *state);
extern void spyHandler2(void *state);
extern void dummyHandler(void *state);
extern void dummyHandler2(void *state);
extern const struct NearSchedule dummySchedule;
extern const struct NearSchedule dummySchedule2;
#endif
<file_sep>/src/firmware/tests/Door/DoorFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Platform/Motor.h"
#include "ApplicationNvmSettings.h"
#include "SunEvents.h"
#include "Door/Door.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
static void onDoorAborted(const struct Event *event);
static void onDoorOpened(const struct Event *event);
static void onDoorClosed(const struct Event *event);
static uint8_t callSequence;
uint8_t farSchedulerAddCalls;
uint8_t farSchedulerAddSequence[8];
const struct FarSchedule *farSchedulerAddArgs[8];
uint8_t farSchedulerRemoveCalls;
uint8_t farSchedulerRemoveSequence[8];
const struct FarSchedule *farSchedulerRemoveArgs[8];
uint8_t onDoorAbortedCalls;
const struct DoorAborted *onDoorAbortedArgs[8];
uint8_t onDoorOpenedCalls;
const struct DoorOpened *onDoorOpenedArgs[8];
uint8_t onDoorClosedCalls;
const struct DoorClosed *onDoorClosedArgs[8];
uint8_t motorEnableCalls;
uint8_t motorEnableSequence;
uint8_t motorDisableCalls;
uint8_t motorDisableSequence;
uint8_t motorOnCalls;
uint8_t motorOnSequence;
int16_t motorOnArgs[8];
uint8_t motorOffCalls;
uint8_t motorOffSequence;
uint8_t motorLimitIsNoLoadCalls;
uint8_t motorLimitIsNoLoadSequence;
uint8_t motorLimitIsMaximumLoadCalls;
uint8_t motorLimitIsMaximumLoadSequence;
static uint8_t motorIsEnabledReturns;
void doorFixtureInitialise(void)
{
callSequence = 0;
farSchedulerAddCalls = 0;
farSchedulerRemoveCalls = 0;
onDoorAbortedCalls = 0;
onDoorOpenedCalls = 0;
onDoorClosedCalls = 0;
motorIsEnabledReturns = 0;
motorEnableCalls = 0;
motorEnableSequence = 0;
motorDisableCalls = 0;
motorDisableSequence = 0;
motorOnCalls = 0;
motorOnSequence = 0;
motorOffCalls = 0;
motorOffSequence = 0;
motorLimitIsNoLoadCalls = 0;
motorLimitIsNoLoadSequence = 0;
motorLimitIsMaximumLoadCalls = 0;
motorLimitIsMaximumLoadSequence = 0;
eventInitialise();
doorInitialise();
}
void doorFixtureShutdown(void)
{
}
void stubNvmSettingsForTimeDrivenMode(void)
{
union ApplicationNvmSettings settings =
{
.door =
{
.mode =
{
.isTimeDriven = 1,
.isManuallyOverridden = 0,
.isSunEventDriven = 0
},
.autoOpenTime =
{
.hour = anyByteLessThan(24),
.minute = anyByteLessThan(60)
},
.autoCloseTime =
{
.hour = anyByteLessThan(24),
.minute = anyByteLessThan(60)
}
}
};
stubNvmApplicationSettings(&settings);
}
void stubNvmSettingsForManuallyDrivenMode(void)
{
union ApplicationNvmSettings settings =
{
.door =
{
.mode =
{
.isTimeDriven = 0,
.isManuallyOverridden = 1,
.isSunEventDriven = 0
}
}
};
stubNvmApplicationSettings(&settings);
}
void stubNvmSettingsForSunEventDrivenMode(void)
{
stubNvmSettingsForSunEventDrivenModeWithOffsets(
(int8_t) anyByte(),
(int8_t) anyByte());
}
void stubNvmSettingsForSunEventDrivenModeWithOffsets(
int8_t sunriseMinutes,
int8_t sunsetMinutes)
{
union ApplicationNvmSettings settings =
{
.door =
{
.mode =
{
.isTimeDriven = 0,
.isManuallyOverridden = 0,
.isSunEventDriven = 1
},
.sunEvents =
{
.sunriseOffsetMinutes = sunriseMinutes,
.sunsetOffsetMinutes = sunsetMinutes
}
}
};
stubNvmApplicationSettings(&settings);
}
void stubNvmSettingsForUnspecifiedMode(void)
{
union ApplicationNvmSettings settings =
{
.door =
{
.mode =
{
.isTimeDriven = 0,
.isManuallyOverridden = 0,
.isSunEventDriven = 0
}
}
};
stubNvmApplicationSettings(&settings);
}
void stubAnySunEvents(struct SunEventsChanged *eventArgs)
{
eventArgs->sunrise.hour = anyByteLessThan(24);
eventArgs->sunrise.minute = anyByteLessThan(60);
eventArgs->sunset.hour = anyByteLessThan(24);
eventArgs->sunset.minute = anyByteLessThan(60);
}
void stubDoorWithFault(uint8_t flags)
{
stubDoorWithState(DoorState_Fault, (enum DoorTransition) anyByte());
extern struct DoorStateInternal doorState;
doorState.aborted.fault.all = flags;
}
void stubDoorWithState(
enum DoorState state,
enum DoorTransition transition)
{
extern struct DoorStateInternal doorState;
doorState.current = state;
doorState.transition = transition;
}
void stubMotorIsEnabled(void)
{
motorIsEnabledReturns = 1;
}
void stubMotorIsDisabled(void)
{
motorIsEnabledReturns = 0;
}
uint8_t motorIsEnabled(void)
{
return motorIsEnabledReturns;
}
void motorEnable(void)
{
motorEnableCalls++;
motorEnableSequence = ++callSequence;
}
void motorDisable(void)
{
motorDisableCalls++;
motorDisableSequence = ++callSequence;
}
void motorOn(int16_t count)
{
motorOnSequence = ++callSequence;
motorOnArgs[motorOnCalls & 7] = count;
motorOnCalls++;
}
void motorOff(void)
{
motorOffCalls++;
motorOffSequence = ++callSequence;
}
void motorLimitIsNoLoad(void)
{
motorLimitIsNoLoadCalls++;
motorLimitIsNoLoadSequence = ++callSequence;
}
void motorLimitIsMaximumLoad(void)
{
motorLimitIsMaximumLoadCalls++;
motorLimitIsMaximumLoadSequence = ++callSequence;
}
void publishDoorAbortedWithAnyFault(void)
{
static const struct DoorAborted eventArgs = { };
eventPublish(DOOR_ABORTED, &eventArgs);
}
void publishDateChanged(void)
{
static const struct DateWithFlags today = { };
static const struct DateChanged dateChangedEventArgs = { .today = &today };
eventPublish(DATE_CHANGED, &dateChangedEventArgs);
}
void publishNvmSettingsChanged(void)
{
static const struct NvmSettingsChanged nvmSettingsChangedEventArgs = { };
eventPublish(NVM_SETTINGS_CHANGED, &nvmSettingsChangedEventArgs);
}
void publishSunEventsChanged(const struct SunEventsChanged *eventArgs)
{
eventPublish(SUN_EVENTS_CHANGED, eventArgs);
}
void publishDoorOpenScheduleActioned(void)
{
static const struct DoorOpenScheduleActioned eventArgs = { };
eventPublish(DOOR_OPEN_SCHEDULE_ACTIONED, &eventArgs);
}
void publishDoorCloseScheduleActioned(void)
{
static const struct DoorCloseScheduleActioned eventArgs = { };
eventPublish(DOOR_CLOSE_SCHEDULE_ACTIONED, &eventArgs);
}
void publishMotorStopped(const struct MotorStopped *eventArgs)
{
eventPublish(MOTOR_STOPPED, eventArgs);
}
void publishMotorStoppedWithNoFaults(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = 123,
.requestedCount = 456,
.fault = 0
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithNoFaultsOnRaising(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = 123,
.requestedCount = 456,
.fault = 0
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithNoFaultsOnLowering(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = -123,
.requestedCount = -456,
.fault = 0
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithFaults(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = 123,
.requestedCount = 456,
.fault = 0xff
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithFaultsOnRaising(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = 123,
.requestedCount = 456,
.fault = 0xff
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithFaultsOnLowering(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = -123,
.requestedCount = -456,
.fault = 0xff
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorStoppedWithNonCurrentLimitFaultOnRaising(void)
{
static const struct MotorStopped eventArgs =
{
.actualCount = 123,
.requestedCount = 456,
.fault = { .all = 0xfe }
};
eventPublish(MOTOR_STOPPED, &eventArgs);
}
void publishMotorEnabled(void)
{
static const struct MotorEnabled eventArgs = { };
eventPublish(MOTOR_ENABLED, &eventArgs);
}
void assertFarSchedulesAreEqualWithAnyNonNullArgs(
const struct FarSchedule *expected,
const struct FarSchedule *actual)
{
TEST_ASSERT_NOT_NULL_MESSAGE(expected, "NULL1");
TEST_ASSERT_NOT_NULL_MESSAGE(actual, "NULL2");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->time.hour,
actual->time.hour,
"Hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->time.minute,
actual->time.minute,
"Minute");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->eventType,
actual->eventType,
"Event");
}
void farSchedulerAdd(const struct FarSchedule *schedule)
{
farSchedulerAddSequence[farSchedulerAddCalls & 7] = ++callSequence;
farSchedulerAddArgs[farSchedulerAddCalls & 7] = schedule;
farSchedulerAddCalls++;
}
void farSchedulerRemove(const struct FarSchedule *schedule)
{
farSchedulerRemoveSequence[farSchedulerRemoveCalls & 7] = ++callSequence;
farSchedulerRemoveArgs[farSchedulerRemoveCalls & 7] = schedule;
farSchedulerRemoveCalls++;
}
void mockOnDoorAborted(void)
{
static const struct EventSubscription onDoorAbortedSubscription =
{
.type = DOOR_ABORTED,
.handler = &onDoorAborted,
.state = (void *) 0
};
eventSubscribe(&onDoorAbortedSubscription);
onDoorAbortedCalls = 0;
}
static void onDoorAborted(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Event");
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "Event Args");
onDoorAbortedArgs[onDoorAbortedCalls & 7] =
(const struct DoorAborted *) event->args;
onDoorAbortedCalls++;
}
void mockOnDoorOpened(void)
{
static const struct EventSubscription onDoorOpenedSubscription =
{
.type = DOOR_OPENED,
.handler = &onDoorOpened,
.state = (void *) 0
};
eventSubscribe(&onDoorOpenedSubscription);
onDoorOpenedCalls = 0;
}
static void onDoorOpened(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Event");
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "Event Args");
onDoorOpenedArgs[onDoorOpenedCalls & 7] =
(const struct DoorOpened *) event->args;
onDoorOpenedCalls++;
}
void mockOnDoorClosed(void)
{
static const struct EventSubscription onDoorClosedSubscription =
{
.type = DOOR_CLOSED,
.handler = &onDoorClosed,
.state = (void *) 0
};
eventSubscribe(&onDoorClosedSubscription);
onDoorClosedCalls = 0;
}
static void onDoorClosed(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event, "Event");
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "Event Args");
onDoorClosedArgs[onDoorClosedCalls & 7] =
(const struct DoorClosed *) event->args;
onDoorClosedCalls++;
}
void enterFindBottomState(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Unknown, anyTransition);
stubMotorIsEnabled();
publishDoorCloseScheduleActioned();
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(DoorState_FindBottom, state.current);
}
uint8_t anyUnknownMotorFault(void)
{
while (1)
{
uint8_t fault = anyByteWithMaskClear(0b00000111);
if (fault != 0)
return fault;
}
}
<file_sep>/src/firmware/tests/Platform/Battery/TestBatteryTemperatureSampled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Battery.h"
#include "Platform/Temperature.h"
#include "BatteryFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Battery.c")
void onBeforeTest(void)
{
batteryFixtureSetUp();
}
void onAfterTest(void)
{
batteryFixtureTearDown();
}
void test_batteryChargerEnabled_eventWhenTemperatureIsOver30CelsiusWhenOtherParametersAllowCharging_expectNoBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
for (int16_t tooHot = CELSIUS(30.1); tooHot <= CELSIUS(50); tooHot++)
{
stubTemperatureOf(tooHot);
dispatchAllEvents();
TEST_ASSERT_NULL(batteryChargerEnabledEventArgs);
}
}
void test_chargerEnablePin_getWhenTemperatureIsOver30CelsiusWhenOtherParametersAllowCharging_expectChargerEnablePinIsLow(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
for (int16_t tooHot = CELSIUS(30.1); tooHot <= CELSIUS(50); tooHot++)
{
stubTemperatureOf(tooHot);
LATBbits.LATB3 = 1;
dispatchAllEvents();
TEST_ASSERT_FALSE(LATBbits.LATB3);
}
}
void test_batteryChargerEnabled_eventWhenTemperatureIsBelow5CelsiusWhenOtherParametersAllowCharging_expectNoBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
for (int16_t tooCold = CELSIUS(4.9); tooCold >= CELSIUS(-25); tooCold--)
{
stubTemperatureOf(tooCold);
dispatchAllEvents();
TEST_ASSERT_NULL(batteryChargerEnabledEventArgs);
}
}
void test_chargerEnablePin_getWhenTemperatureIsBelow5CelsiusWhenOtherParametersAllowCharging_expectChargerEnablePinIsLow(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
for (int16_t tooCold = CELSIUS(4.9); tooCold >= CELSIUS(-25); tooCold--)
{
stubTemperatureOf(tooCold);
LATBbits.LATB3 = 1;
dispatchAllEvents();
TEST_ASSERT_FALSE(LATBbits.LATB3);
}
}
void test_batteryChargerEnabled_eventWhenTemperatureIsBetween5And30CelsiusWhenOtherParametersAllowCharging_expectBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
for (int16_t justRight = CELSIUS(5); justRight <= CELSIUS(30); justRight++)
{
stubTemperatureOf(CELSIUS(-10));
dispatchAllEvents();
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
stubTemperatureOf(justRight);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerEnabledEventArgs);
}
}
void test_chargerEnablePin_getWhenTemperatureIsBetween5And30CelsiusWhenOtherParametersAllowCharging_expectChargerEnablePinIsHigh(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
for (int16_t justRight = CELSIUS(5); justRight <= CELSIUS(30); justRight++)
{
stubTemperatureOf(justRight);
LATBbits.LATB3 = 0;
dispatchAllEvents();
TEST_ASSERT_TRUE(LATBbits.LATB3);
}
}
void test_batteryChargerDisabled_eventWhenTemperatureTransitionsBelow5CelsiusWhenOtherParametersAllowCharging_expectBatteryChargerDisabledEventIsPublished(void)
{
batteryInitialise();
for (int16_t tooCold = CELSIUS(4.9); tooCold >= CELSIUS(-25); tooCold--)
{
stubAllParametersThatWillEnableCharging();
dispatchAllEvents();
stubTemperatureOf(tooCold);
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) 0;
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerDisabledEventArgs);
}
}
void test_batteryChargerDisabled_eventWhenTemperatureTransitionsAbove30CelsiusWhenOtherParametersAllowCharging_expectBatteryChargerDisabledEventIsPublished(void)
{
batteryInitialise();
for (int16_t tooHot = CELSIUS(30.1); tooHot <= CELSIUS(50); tooHot++)
{
stubAllParametersThatWillEnableCharging();
dispatchAllEvents();
stubTemperatureOf(tooHot);
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) 0;
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerDisabledEventArgs);
}
}
<file_sep>/src/firmware/src/Platform/Event.c
#include <xc.h>
#include <stdint.h>
#include "Event.h"
#define MAX_SUBSCRIPTIONS 48
#define MAX_EVENTS 16
const struct Event eventEmptyArgs = { };
static const struct EventSubscription *subscriptions[MAX_SUBSCRIPTIONS];
static struct EventQueueEntry
{
EventType type;
const void *args;
} events[MAX_EVENTS];
static uint8_t eventsReadIndex, eventsWriteIndex;
static void buggyCompilerWorkaround(void)
{
static const struct Event dummy1 =
{
.state = _OMNITARGET,
.args = _OMNITARGET
};
static const struct EventSubscription dummy2 =
{
.state = _OMNITARGET
};
static const struct EventQueueEntry dummy3 =
{
.args = _OMNITARGET
};
}
void eventInitialise(void)
{
uint8_t i;
for (i = 0; i < MAX_SUBSCRIPTIONS; i++)
subscriptions[i] = (struct EventSubscription *) 0;
eventsReadIndex = 0;
eventsWriteIndex = 0;
}
void eventSubscribe(const struct EventSubscription *subscription)
{
int8_t freeIndex = -1;
int8_t i;
for (i = 0; i < MAX_SUBSCRIPTIONS; i++)
{
if (
(freeIndex < 0 && !subscriptions[i]) ||
subscriptions[i] == subscription)
freeIndex = i;
}
if (freeIndex >= 0)
subscriptions[freeIndex] = subscription;
// else
// TODO: THIS SHOULD REGISTER A FAULT
}
void eventUnsubscribe(const struct EventSubscription *subscription)
{
uint8_t i;
for (i = 0; i < MAX_SUBSCRIPTIONS; i++)
{
if (subscriptions[i] == subscription)
{
subscriptions[i] = (const struct EventSubscription *) 0;
return;
}
}
}
void eventPublish(EventType type, const void *args)
{
events[eventsWriteIndex].type = type;
events[eventsWriteIndex].args = args;
if (++eventsWriteIndex >= MAX_EVENTS)
eventsWriteIndex = 0;
}
int8_t eventDispatchNext(void)
{
if (eventsReadIndex == eventsWriteIndex)
return 0;
static struct Event event;
event.type = events[eventsReadIndex].type;
event.args = events[eventsReadIndex].args;
uint8_t i;
for (i = 0; i < MAX_SUBSCRIPTIONS; i++)
{
if (
!subscriptions[i] ||
subscriptions[i]->type != event.type ||
!subscriptions[i]->handler)
continue;
event.state = subscriptions[i]->state;
subscriptions[i]->handler(&event);
}
if (++eventsReadIndex >= MAX_EVENTS)
eventsReadIndex = 0;
return 1;
}
<file_sep>/src/firmware/tests/Platform/Lcd/LcdFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_LCD_LCDFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_LCD_LCDFIXTURE_H
extern void lcdFixtureInitialise(void);
extern void lcdFixtureShutdown(void);
extern void enableLcdAndWaitUntilDone(void);
#endif
<file_sep>/src/firmware/tests/Door/TestDoorOnNvmSettingsChanged.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsTimeDriven_expectScheduleIsAddedForOpeningTimeStoredInNvm(void)
{
stubNvmSettingsForTimeDrivenMode();
struct FarSchedule expectedOpeningSchedule =
{
.time =
{
.hour = nvmSettings.application.door.autoOpenTime.hour,
.minute = nvmSettings.application.door.autoOpenTime.minute
},
.eventType = DOOR_OPEN_SCHEDULE_ACTIONED
};
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 1);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedOpeningSchedule,
farSchedulerAddArgs[0]);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsTimeDriven_expectPreviousScheduleIsRemovedBeforeAddingNewDoorOpeningTime(void)
{
stubNvmSettingsForTimeDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 1, "Calls");
TEST_ASSERT_EQUAL(farSchedulerAddArgs[0], farSchedulerRemoveArgs[0]);
TEST_ASSERT_TRUE(farSchedulerRemoveSequence[0] < farSchedulerAddSequence[0]);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsTimeDriven_expectScheduleIsAddedForClosingTimeStoredInNvm(void)
{
stubNvmSettingsForTimeDrivenMode();
struct FarSchedule expectedClosingSchedule =
{
.time =
{
.hour = nvmSettings.application.door.autoCloseTime.hour,
.minute = nvmSettings.application.door.autoCloseTime.minute
},
.eventType = DOOR_CLOSE_SCHEDULE_ACTIONED
};
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 2);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedClosingSchedule,
farSchedulerAddArgs[1]);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsTimeDriven_expectPreviousScheduleIsRemovedBeforeAddingNewDoorClosingTime(void)
{
stubNvmSettingsForTimeDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 2, "Calls");
TEST_ASSERT_EQUAL(farSchedulerAddArgs[1], farSchedulerRemoveArgs[1]);
TEST_ASSERT_TRUE(farSchedulerRemoveSequence[1] < farSchedulerAddSequence[1]);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsManuallyDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForManuallyDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsManuallyDriven_expectSchedulesAreRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForManuallyDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(2, farSchedulerRemoveCalls);
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[0], "Open");
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[1], "Close");
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsSunEventDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForSunEventDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsSunEventDriven_expectSchedulesAreRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForSunEventDrivenMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(2, farSchedulerRemoveCalls);
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[0], "Open");
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[1], "Close");
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsUnspecifiedMode_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForUnspecifiedMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_nvmSettingsChanged_onPublishedWhenDoorIsUnspecifiedMode_expectSchedulesAreRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForUnspecifiedMode();
publishNvmSettingsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(2, farSchedulerRemoveCalls);
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[0], "Open");
TEST_ASSERT_NOT_NULL_MESSAGE(farSchedulerAddArgs[1], "Close");
}
<file_sep>/src/firmware/tests/Door/TestDoorFindBottom1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void test_findBottom_expectDoorIsFirstLoweredAbout10cm(void)
{
enterFindBottomState();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(motorOnArgs[0], -PULSES_PER_10CM, "Arg");
}
void test_findBottomAfterLoweringStop_expectMotorIsNotDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorDisableCalls);
}
void test_findBottomWhenLoweringStopHasFaults_expectFaultStateWithUnmodifiedTransition(void)
{
enterFindBottomState();
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom, anyTransition);
publishMotorStoppedWithFaultsOnLowering();
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(anyTransition, state.transition, "T");
}
void test_findBottomWhenLoweringStopHasFaults_expectMotorIsDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithFaultsOnLowering();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_findBottomWhenLoweringStopCurrentLimitFault_expectDoorAbortedIsPublishedWithReversedFlag(void)
{
enterFindBottomState();
static const struct MotorStopped reversed =
{
.actualCount = -123,
.requestedCount = -456,
.fault = { .currentLimited = 1 }
};
publishMotorStopped(&reversed);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_findBottomWhenLoweringStopEncoderOverflowFault_expectDoorAbortedIsPublishedWithLineTooLongFlag(void)
{
enterFindBottomState();
static const struct MotorStopped tooLong =
{
.actualCount = -123,
.requestedCount = -456,
.fault = { .encoderOverflow = 1 }
};
publishMotorStopped(&tooLong);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_findBottomWhenLoweringStopEncoderTimeoutFault_expectDoorAbortedIsPublishedWithEncoderBrokenFlag(void)
{
enterFindBottomState();
static const struct MotorStopped timeout =
{
.actualCount = -123,
.requestedCount = -456,
.fault = { .encoderTimeout = 1 }
};
publishMotorStopped(&timeout);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
void test_findBottomWhenLoweringStopUnknownFault_expectDoorAbortedIsPublishedWithNoFaultFlags(void)
{
enterFindBottomState();
struct MotorStopped unknown =
{
.actualCount = -123,
.requestedCount = -456,
.fault = { .all = anyUnknownMotorFault() }
};
publishMotorStopped(&unknown);
mockOnDoorAborted();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedArgs[0]->fault.all, "F");
}
<file_sep>/src/firmware/tests/Platform/Clock/TestClockGetSetNow3.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "ClockGetSetNowFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
void onBeforeTest(void)
{
clockFixtureSetUp();
clockGetSetNowFixtureSetUp();
dispatchAllEvents();
}
void onAfterTest(void)
{
clockGetSetNowFixtureTearDown();
clockFixtureTearDown();
}
void test_clockGetNowGmt_calledWhenTimerInterruptFlagIsSet_expectTimeIsSameAsWouldBeAfterTick(void)
{
struct DateAndTimeGet before, after;
stubAnyDateTime();
clockGetNowGmt(&before);
tick();
clockGetNowGmt(&after);
clockSetNowGmt((const struct DateAndTimeSet *) &before);
PIR0bits.TMR0IF = 1;
struct DateAndTimeGet now;
clockGetNowGmt(&now);
assertEqualDateTime(&after, &now);
}
void test_clockGetNowGmt_calledWhenTimerInterruptFlagIsSet_expectTimerInterruptFlagIsCleared(void)
{
struct DateAndTimeGet before, after;
stubAnyDateTime();
clockGetNowGmt(&before);
tick();
clockGetNowGmt(&after);
clockSetNowGmt((const struct DateAndTimeSet *) &before);
PIR0 = anyByteWithMaskSet(_PIR0_TMR0IF_MASK);
uint8_t expectedPir0 = PIR0 & ~_PIR0_TMR0IF_MASK;
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8(expectedPir0, PIR0);
}
void test_clockSetNowGmt_calledWhenTimerInterruptFlagIsSet_expectTimerInterruptFlagIsCleared(void)
{
struct DateAndTimeGet now;
stubAnyDateTime();
clockGetNowGmt(&now);
PIR0 = anyByteWithMaskSet(_PIR0_TMR0IF_MASK);
uint8_t expectedPir0 = PIR0 & ~_PIR0_TMR0IF_MASK;
clockSetNowGmt((const struct DateAndTimeSet *) &now);
TEST_ASSERT_EQUAL_UINT8(expectedPir0, PIR0);
}
void test_clockSetNowGmt_calledWhenTmr0hIsNotOneMinute_expectTmr0hIsResetToOneMinute(void)
{
struct DateAndTimeGet now;
stubAnyDateTime();
clockGetNowGmt(&now);
TMR0H = anyByteExcept(59);
clockSetNowGmt((const struct DateAndTimeSet *) &now);
TEST_ASSERT_EQUAL_UINT8(59, TMR0H);
}
void test_clockSetNowGmt_calledWhenLeapYear_expectIsLeapYearFlagIsSet(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyLeapYear(),
.month = 1 + anyByteLessThan(12),
.day = 1 + anyByteLessThan(29)
}
};
mockOnDateChanged();
clockSetNowGmt(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, dateChangedCalls, "Calls");
TEST_ASSERT_NOT_NULL_MESSAGE(dateChanged, "Args");
TEST_ASSERT_TRUE_MESSAGE(dateChanged->today->flags.isLeapYear, "Flag");
}
void test_clockSetNowGmt_calledWhenNotLeapYear_expectIsLeapYearFlagIsClear(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyNonLeapYear(),
.month = 1 + anyByteLessThan(12),
.day = 1 + anyByteLessThan(28)
}
};
mockOnDateChanged();
clockSetNowGmt(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, dateChangedCalls, "Calls");
TEST_ASSERT_NOT_NULL_MESSAGE(dateChanged, "Args");
TEST_ASSERT_FALSE_MESSAGE(dateChanged->today->flags.isLeapYear, "Flag");
}
void test_clockSetNowGmt_called_expectDateChangedIsPublishedWithCorrectDate(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyByteLessThan(100),
.month = 1 + anyByteLessThan(12),
.day = 1 + anyByteLessThan(28)
}
};
mockOnDateChanged();
clockSetNowGmt(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, dateChangedCalls, "Calls");
TEST_ASSERT_NOT_NULL_MESSAGE(dateChanged, "Args");
assertEqualDate(&now.date, (const struct Date *) dateChanged->today);
}
void test_clockSetNowGmt_called_expectTimeChangedIsPublishedAfterDateChanged(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyNonLeapYear(),
.month = 1 + anyByteLessThan(12),
.day = 1 + anyByteLessThan(28)
},
.time =
{
.hour = anyByteLessThan(24),
.minute = anyByteLessThan(60),
.second = anyByteLessThan(60)
}
};
mockOnDateChanged();
mockOnTimeChanged();
clockSetNowGmt(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, dateChangedCalls, "Calls (D)");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, timeChangedCalls, "Calls (T)");
TEST_ASSERT_TRUE_MESSAGE(dateChangedSequence < timeChangedSequence, "Sequence");
}
void test_clockSetNowGmt_called_expectTimeChangedIsPublishedWithCorrectTime(void)
{
struct DateAndTimeSet now =
{
.time =
{
.hour = anyByteLessThan(24),
.minute = anyByteLessThan(60),
.second = anyByteLessThan(60)
}
};
mockOnDateChanged();
mockOnTimeChanged();
clockSetNowGmt(&now);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(timeChanged);
assertEqualTime(&now.time, timeChanged->now);
}
// TODO: TEST SETNOW TO MAKE SURE DATE_CHANGED HAS DST FLAG SET / CLEAR
// TODO: TEST GETNOW TO MAKE SURE DATE_CHANGED HAS DST FLAG SET / CLEAR
<file_sep>/src/firmware/tests/Platform/Event/TestEventSubscribe.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Platform/Event.h"
#include "Mock_EventHandler.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
#define MAX_SUBSCRIPTIONS 48
static void buggyCompilerWorkaround(void)
{
eventPublish(0, _OMNITARGET);
}
static struct EventSubscription subscription;
static uint8_t eventState;
static struct EventSubscription anotherSubscription;
static uint8_t anotherEventState;
static struct EventSubscription lotsOfSubscriptions[MAX_SUBSCRIPTIONS];
static uint8_t lotsOfEventStates[MAX_SUBSCRIPTIONS];
static int eventHandlerCallCount;
static void eventHandlerThatIncrementsCounter(const struct Event *event)
{
eventHandlerCallCount++;
}
void onBeforeTest(void)
{
eventHandlerCallCount = 0;
eventState = anyByte();
subscription.type = 1;
subscription.handler = &eventHandler;
subscription.state = &eventState;
anotherEventState = anyByte();
anotherSubscription.type = 2;
anotherSubscription.handler = &anotherEventHandler;
anotherSubscription.state = &anotherEventState;
for (uint8_t i = 0; i < MAX_SUBSCRIPTIONS; i++)
{
lotsOfEventStates[i] = anyByte();
lotsOfSubscriptions[i].type = 3;
lotsOfSubscriptions[i].handler = &eventHandlerThatIncrementsCounter;
lotsOfSubscriptions[i].state = &lotsOfEventStates[i];
}
eventInitialise();
}
void onAfterTest(void)
{
}
void test_eventSubscribe_calledWithExistingSubscription_expectOnlyOneDispatch(void)
{
eventSubscribe(&subscription);
eventSubscribe(&subscription);
eventPublish(subscription.type, NULL);
eventHandler_ExpectAnyArgs();
eventDispatchNext();
}
void test_eventSubscribe_calledMoreTimesThanBufferSize_expectExistingSubscriptionsAreNotOverwritten(void)
{
subscription.type = lotsOfSubscriptions[0].type;
eventSubscribe(&subscription);
eventHandler_ExpectAnyArgs();
for (uint8_t i = 0; i < MAX_SUBSCRIPTIONS; i++)
eventSubscribe(&lotsOfSubscriptions[i]);
eventPublish(subscription.type, NULL);
eventDispatchNext();
TEST_ASSERT_EQUAL_UINT8(MAX_SUBSCRIPTIONS - 1, eventHandlerCallCount);
}
void test_eventUnsubscribe_called_expectEventsAreNotDispatchedAnymore(void)
{
eventSubscribe(&subscription);
eventPublish(subscription.type, NULL);
eventPublish(subscription.type, NULL);
eventHandler_ExpectAnyArgs();
eventDispatchNext();
eventUnsubscribe(&subscription);
eventDispatchNext();
}
void test_eventUnsubscribe_called_expectHoleInListCanBeRefilledByNewSubscription(void)
{
for (uint8_t i = 0; i < MAX_SUBSCRIPTIONS; i++)
eventSubscribe(&lotsOfSubscriptions[i]);
eventUnsubscribe(&lotsOfSubscriptions[7]);
subscription.type = lotsOfSubscriptions[0].type;
eventSubscribe(&subscription);
eventHandler_ExpectAnyArgs();
eventPublish(subscription.type, NULL);
eventDispatchNext();
TEST_ASSERT_EQUAL_UINT8(MAX_SUBSCRIPTIONS - 1, eventHandlerCallCount);
}
<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdEnable.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Mock_VoltageRegulator.h"
#include "Mock_PwmTimer.h"
#include "Mock_LcdInternals.h"
#include "Platform/Lcd.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
static void assertLcdConfigureNotCalled(int numCalls);
static void publishVoltageRegulatorEnabled(void);
void onBeforeTest(void)
{
eventInitialise();
lcdInitialise();
}
void onAfterTest(void)
{
}
void test_lcdEnable_calledWhenVoltageRegulatorIsNotEnabled_expectVoltageRegulatorIsEnabled(void)
{
voltageRegulatorEnable_Expect();
voltageRegulatorIsEnabled_ExpectAndReturn(0);
lcdEnable();
}
void test_lcdEnable_calledWhenVoltageRegulatorIsEnabled_expectVoltageRegulatorIsEnabled(void)
{
voltageRegulatorEnable_Expect();
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdEnable();
}
void test_lcdEnable_called_expectPwmTimerIsEnabled(void)
{
pwmTimerEnable_Expect();
lcdEnable();
}
void test_lcdEnable_calledOnceWhenVoltageRegulatorIsEnabled_expectLcdIsConfigured(void)
{
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdConfigure_Expect();
lcdEnable();
}
void test_lcdEnable_calledMoreThanOnceWhenVoltageRegulatorIsEnabled_expectLcdIsOnlyConfiguredOnce(void)
{
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdConfigure_Expect();
lcdEnable();
lcdEnable();
}
void test_lcdEnable_calledAfterDisabled_expectLcdIsConfigured(void)
{
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdConfigure_Expect();
lcdEnable();
lcdDisable();
voltageRegulatorIsEnabled_ExpectAndReturn(1);
lcdConfigure_Expect();
lcdEnable();
}
void test_lcdEnable_calledWhenVoltageRegulatorIsNotEnabled_expectLcdIsNotConfiguredUntilVoltageRegulatorEnabled(void)
{
voltageRegulatorIsEnabled_ExpectAndReturn(0);
lcdConfigure_StubWithCallback(assertLcdConfigureNotCalled);
lcdEnable();
}
static void assertLcdConfigureNotCalled(int numCalls)
{
TEST_FAIL_MESSAGE("Expected no calls to lcdConfigure()");
}
void test_lcdEnable_calledWhenVoltageRegulatorIsNotEnabledAndThenEventPublished_expectLcdIsConfigured(void)
{
voltageRegulatorIsEnabled_ExpectAndReturn(0);
lcdEnable();
lcdConfigure_Expect();
publishVoltageRegulatorEnabled();
while (eventDispatchNext())
;;
}
static void publishVoltageRegulatorEnabled(void)
{
static const struct VoltageRegulatorEnabled emptyArgs = { };
eventPublish(VOLTAGE_REGULATOR_ENABLED, &emptyArgs);
}
void test_lcdEnable_notCalled_expectVoltageRegulatorEnabledEventDoesNotConfigureLcd(void)
{
lcdConfigure_StubWithCallback(assertLcdConfigureNotCalled);
publishVoltageRegulatorEnabled();
while (eventDispatchNext())
;;
}
<file_sep>/src/firmware/src/Location.c
#include <xc.h>
#include "../Platform/Event.h"
#include "../Platform/NvmSettings.h"
#include "Location.h"
static void buggyCompilerWorkaround(void)
{
static const struct LocationChanged dummy =
{
.location = _OMNITARGET
};
}
static void onNvmSettingsChanged(const struct Event *event);
static struct Location location;
void locationInitialise(void)
{
static const struct EventSubscription onNvmSettingsChangedSubscription =
{
.type = NVM_SETTINGS_CHANGED,
.handler = &onNvmSettingsChanged,
.state = (void *) 0
};
eventSubscribe(&onNvmSettingsChangedSubscription);
location.latitudeOffset = nvmSettings.application.location.latitudeOffset;
location.longitudeOffset = nvmSettings.application.location.longitudeOffset;
}
static void onNvmSettingsChanged(const struct Event *event)
{
if (nvmSettings.application.location.latitudeOffset == location.latitudeOffset &&
nvmSettings.application.location.longitudeOffset == location.longitudeOffset)
return;
static const struct LocationChanged locationChangedEventArgs = { .location = &location };
location.latitudeOffset = nvmSettings.application.location.latitudeOffset;
location.longitudeOffset = nvmSettings.application.location.longitudeOffset;
eventPublish(LOCATION_CHANGED, &locationChangedEventArgs);
}
<file_sep>/src/firmware/tests/Platform/Clock/TestClockGetSetNow2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "ClockGetSetNowFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
static void clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
struct DateAndTimeSet *monthPrototype,
const uint16_t *expectedDayOfYear);
void onBeforeTest(void)
{
clockFixtureSetUp();
clockGetSetNowFixtureSetUp();
}
void onAfterTest(void)
{
clockGetSetNowFixtureTearDown();
clockFixtureTearDown();
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfLeapYearDecemberTicks_expectNewYearAndAndFirstMonthAndDayAndZeroHoursAndMinutes(void)
{
struct DateAndTimeGet before =
{
.date =
{
.year = anyLeapYear(),
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.date.dayOfYear, "DoY");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.month, "M");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(before.date.year + 1, now.date.year, "Y");
assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfCenturyTicks_expectZeroYearAndAndFirstMonthAndDayAndZeroHoursAndMinutes(void)
{
struct DateAndTimeGet before =
{
.date =
{
.year = 99,
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt((const struct DateAndTimeSet *) &before);
clockGetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "MM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "HH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "D");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.date.dayOfYear, "DoY");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.month, "M");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.date.year, "Y");
assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(&before, &now);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfLeapYearDecemberTicks_expectIsLeapYearFlagIsCleared(void)
{
struct DateAndTimeSet before =
{
.date =
{
.year = anyLeapYear(),
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_FALSE(now.date.flags.isLeapYear);
}
void test_clockGetNowGmt_calledWhenClockOfLastDayOfNonLeapYearDecemberTicksIntoLeapYear_expectIsLeapYearFlagIsSet(void)
{
struct DateAndTimeSet before =
{
.date =
{
.year = anyLeapYear() + 3,
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
clockSetNowGmt(&before);
tick();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_TRUE(now.date.flags.isLeapYear);
}
void test_clockGetNowGmt_calledWhenLeapYear_expectIsLeapYearFlagIsSet(void)
{
struct DateAndTimeSet before =
{
.date =
{
.year = 0,
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
for (uint8_t leapYear = 0; leapYear < 100; leapYear += 4)
{
before.date.year = leapYear;
clockSetNowGmt(&before);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_TRUE(now.date.flags.isLeapYear);
}
}
void test_clockGetNowGmt_calledWhen1JanuaryInAllYears_expectDayOfYearIs0(void)
{
struct DateAndTimeSet firstDayOfYear =
{
.date =
{
.year = 0,
.month = 1,
.day = 1
}
};
for (uint8_t year = 0; year < 100; year++)
{
firstDayOfYear.date.year = year;
clockSetNowGmt(&firstDayOfYear);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT16(0, now.date.dayOfYear);
}
}
void test_clockGetNowGmt_calledWhen31DecemberInLeapYear_expectDayOfYearIs365(void)
{
struct DateAndTimeSet lastDayOfYear =
{
.date =
{
.year = 0,
.month = 12,
.day = 31
}
};
for (uint8_t leapYear = 0; leapYear < 100; leapYear += 4)
{
lastDayOfYear.date.year = leapYear;
clockSetNowGmt(&lastDayOfYear);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT16(365, now.date.dayOfYear);
}
}
void test_clockGetNowGmt_calledWhen31DecemberInNonLeapYear_expectDayOfYearIs364(void)
{
struct DateAndTimeSet lastDayOfYear =
{
.date =
{
.year = 1,
.month = 12,
.day = 31
}
};
for (uint8_t nonLeapYear = 1; nonLeapYear < 100; nonLeapYear++)
{
if ((nonLeapYear & 3) == 0)
continue;
lastDayOfYear.date.year = nonLeapYear;
clockSetNowGmt(&lastDayOfYear);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT16(364, now.date.dayOfYear);
}
}
void test_clockGetNowGmt_calledWhenNotLeapYear_expectIsLeapYearFlagIsClear(void)
{
struct DateAndTimeSet before =
{
.date =
{
.year = 1,
.month = 12,
.day = 31
},
.time = { .hour = 23, .minute = 59, .second = anyByteLessThan(60) }
};
for (uint8_t nonLeapYear = 1; nonLeapYear < 100; nonLeapYear++)
{
if ((nonLeapYear & 3) == 0)
continue;
before.date.year = nonLeapYear;
clockSetNowGmt(&before);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_FALSE(now.date.flags.isLeapYear);
}
}
void test_clockGetNowGmt_calledWhenNotLeapYear_expectDayOfYearIsValidForEachMonthStart(void)
{
static const uint16_t expectedDayOfYear[] =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
struct DateAndTimeSet monthStart =
{
.date =
{
.year = anyNonLeapYear(),
.month = 1,
.day = 1
}
};
clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
&monthStart,
expectedDayOfYear);
}
static void clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
struct DateAndTimeSet *monthPrototype,
const uint16_t *expectedDayOfYear)
{
static const int8_t daysInMonth[] =
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int8_t prototypeDay = (int8_t) monthPrototype->date.day;
for (uint8_t month = 0; month < 12; month++)
{
monthPrototype->date.month = 1 + month;
if (prototypeDay < 1)
{
int8_t leapYearFebruaryAdjustment =
month == 1 && (monthPrototype->date.year & 3) == 0
? 1
: 0;
monthPrototype->date.day = (uint8_t)
prototypeDay +
daysInMonth[month] +
leapYearFebruaryAdjustment;
}
clockSetNowGmt(monthPrototype);
struct DateAndTimeGet now;
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT16(*(expectedDayOfYear++), now.date.dayOfYear);
}
}
void test_clockGetNowGmt_calledWhenLeapYear_expectDayOfYearIsValidForEachMonthStart(void)
{
static const uint16_t expectedDayOfYear[] =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
};
struct DateAndTimeSet monthStart =
{
.date =
{
.year = anyLeapYear(),
.month = 1,
.day = 1
}
};
clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
&monthStart,
expectedDayOfYear);
}
void test_clockGetNowGmt_calledWhenNotLeapYear_expectDayOfYearIsValidForEachMonthEnd(void)
{
static const uint16_t expectedDayOfYear[] =
{
30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364
};
struct DateAndTimeSet monthEnd =
{
.date =
{
.year = anyNonLeapYear(),
.month = 1,
.day = 0
}
};
clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
&monthEnd,
expectedDayOfYear);
}
void test_clockGetNowGmt_calledWhenLeapYear_expectDayOfYearIsValidForEachMonthEnd(void)
{
static const uint16_t expectedDayOfYear[] =
{
30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
struct DateAndTimeSet monthEnd =
{
.date =
{
.year = anyLeapYear(),
.month = 1,
.day = 0
}
};
clockGetNowGmt_called_expectDayOfYearIsValidForEachMonth(
&monthEnd,
expectedDayOfYear);
}
<file_sep>/src/firmware/src/Platform/Clock/ClockInitialise.c
#include <xc.h>
#include "../Event.h"
#include "../PowerManagement.h"
#include "Clock.h"
#define T0CON0_POSTSCALE_1SECOND_MASK (0 << _T0CON0_T0OUTPS_POSITION)
#define T0CON1_SOSC_SOURCE_MASK (0b110 << _T0CON1_T0CS_POSITION)
#define T0CON1_PRESCALE_1SECOND_MASK (0b1111 << _T0CON1_T0CKPS_POSITION)
static void onWokenFromSleep(const struct Event *event);
static void buggyCompilerWorkaround(void)
{
static const struct DateChanged dummy1 = { .today = _OMNITARGET };
static const struct TimeChanged dummy2 = { .now = _OMNITARGET };
}
void clockInitialise(void)
{
PMD1bits.TMR0MD = 0;
OSCENbits.SOSCEN = 1;
while (!OSCSTATbits.SOR)
;;
T0CON0 = T0CON0_POSTSCALE_1SECOND_MASK;
TMR0H = 59;
TMR0L = 0;
PIR0bits.TMR0IF = 0;
PIE0bits.TMR0IE = 1;
T0CON1 =
_T0CON1_T0ASYNC_MASK |
T0CON1_SOSC_SOURCE_MASK |
T0CON1_PRESCALE_1SECOND_MASK;
T0CON0bits.T0EN = 1;
static const struct DateAndTimeSet epoch =
{
.date =
{
.year = 0,
.month = 1,
.day = 1
}
};
clockSetNowGmt(&epoch);
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
}
static void onWokenFromSleep(const struct Event *event)
{
if (!PIR0bits.TMR0IF)
return;
PIR0bits.TMR0IF = 0;
clockTicked();
}
<file_sep>/src/firmware/src/Platform/Lcd.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_LCD_H
#define __CLUCK2SESAME_SRC_PLATFORM_LCD_H
#include <stdint.h>
#include "Event.h"
#define LCD_ENABLED ((EventType) 0x20)
struct LcdEnabled { EMPTY_EVENT_ARGS };
#define LCD_DISABLED ((EventType) 0x21)
struct LcdDisabled { EMPTY_EVENT_ARGS };
#define LCD_ADDRESS_LINE1 0x00
#define LCD_ADDRESS_LINE2 0x40
#define LCD_CMD_FUNCTION 0b00100000
#define LCD_CMD_FUNCTION_TWOLINES 0b00001000
#define LCD_CMD_FUNCTION_FONT5X8 0b00000000
#define LCD_CMD_DISPLAY 0b00001000
#define LCD_CMD_DISPLAY_OFF 0b00000000
#define LCD_CMD_DISPLAY_ON 0b00000100
#define LCD_CMD_DISPLAYCLEAR 0b00000001
#define LCD_CMD_ENTRYMODE 0b00000100
#define LCD_CMD_ENTRYMODE_INCREMENT 0b00000010
#define LCD_CMD_ENTRYMODE_NOSHIFT 0b00000000
#define LCD_CMD_SETDDRAMADDRESS 0b10000000
#define LCD_CMD_SETDDRAMADDRESS_LINE1 (LCD_CMD_SETDDRAMADDRESS | LCD_ADDRESS_LINE1)
#define LCD_CMD_SETDDRAMADDRESS_LINE2 (LCD_CMD_SETDDRAMADDRESS | LCD_ADDRESS_LINE2)
#define LCD_CMD_DONE 0
typedef void (*LcdTransactionCallback)(void *state);
struct LcdPutsTransaction
{
const char *buffer;
LcdTransactionCallback callback;
void *state;
};
struct LcdSetAddressTransaction
{
uint8_t address;
LcdTransactionCallback callback;
void *state;
};
struct LcdSetCursorTransaction
{
uint8_t on;
LcdTransactionCallback callback;
void *state;
};
extern void lcdInitialise(void);
extern void lcdEnable(void);
extern void lcdDisable(void);
extern void __reentrant lcdPuts(const struct LcdPutsTransaction *transaction);
extern void lcdSetDdramAddress(const struct LcdSetAddressTransaction *transaction);
extern void lcdSetCursor(const struct LcdSetCursorTransaction *transaction);
#endif
<file_sep>/src/firmware/tests/Platform/Lcd/FakeLcd.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_LCD_FAKELCD_H
#define __CLUCK2SESAME_TESTS_PLATFORM_LCD_FAKELCD_H
#include <stdint.h>
extern void fakeLcdInitialise(void);
extern void fakeLcdShutdown(void);
extern void fakeLcdAssertStateIsValid(void);
extern void fakeLcdAssertNotBusy(void);
extern void fakeLcdAssertFunctionRegister(uint8_t flags);
extern void fakeLcdAssertDisplayRegister(uint8_t flags);
extern void fakeLcdAssertEntryModeRegister(uint8_t flags);
extern void fakeLcdAssertDdramAddressRegisterIs(uint8_t address);
extern volatile uint8_t fakeLcdIsSessionInvalid;
extern volatile uint8_t fakeLcdRs;
extern volatile uint8_t fakeLcdData;
extern volatile uint8_t fakeLcdIsConfigured;
extern volatile uint8_t fakeLcdIsNybbleMode;
extern volatile uint8_t fakeLcdDram[16 * 2];
#endif
<file_sep>/src/firmware/src/ConfigurationWords.c
#include <xc.h>
#pragma config "FEXTOSC=OFF"
#pragma config "RSTOSC=HFINT32"
#pragma config "CLKOUTEN=OFF"
#pragma config "CSWEN=ON"
#pragma config "FCMEN=OFF"
#pragma config "MCLRE=ON"
#pragma config "PWRTE=ON"
#pragma config "LPBOREN=OFF"
#pragma config "BOREN=OFF"
#pragma config "ZCD=OFF"
#pragma config "PPS1WAY=OFF"
#pragma config "STVREN=ON"
#pragma config "WDTE=OFF"
#pragma config "BBEN=OFF"
#pragma config "SAFEN=OFF"
#pragma config "WRTAPP=OFF"
#pragma config "WRTB=OFF"
#pragma config "WRTC=ON"
#pragma config "WRTSAF=OFF"
#pragma config "LVP=ON"
#pragma config "CP=OFF"
<file_sep>/src/firmware/src/Ui/UiSystemInitialised.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Platform/Event.h"
#include "../Platform/NvmSettings.h"
#include "../Platform/NearScheduler.h"
#include "../Platform/NvmSettings.h"
#include "Ui.h"
static void uiOnSplashScreenTimeout(void *state);
static const struct NearSchedule uiScreenTimeoutSchedule =
{
.ticks = MS_TO_TICKS(1000),
.handler = &uiOnSplashScreenTimeout
};
void uiOnSystemInitialised(const struct Event *event)
{
memcpy(
uiState.screen,
"Cluck2Sesame by \0"
"lophtware.co.uk ",
sizeof(uiState.screen));
uiScreenOn();
uiState.flags.bits.isCalibrationMode = (nvmSettings.platform.flags.bits.isCalibrationRequired) ? 1 : 0;
uiState.flags.bits.isInitialSetupRequired = (nvmSettings.application.door.height < 128) ? 1 : 0;
uiState.flags.bits.isScreenTimeoutDisabled = 1;
nearSchedulerAdd(&uiScreenTimeoutSchedule);
uiScreenBlit();
}
static void uiOnSplashScreenTimeout(void *state)
{
static uint8_t secondsElapsed = 0;
if (++secondsElapsed == 5)
{
if (!uiState.flags.bits.isCalibrationMode)
{
uiDateAndTimeEntryScreen();
uiScreenStartTimeout();
}
else
uiCalibrationModeScreen();
return;
}
nearSchedulerAdd(&uiScreenTimeoutSchedule);
}
void uiOnSystemInitialSetupCompleted(void)
{
if (!nvmSettingsStore(&uiNvmSettings))
{
// TODO: THIS NEEDS TO BE A FAULT...
}
uiState.flags.bits.isInitialSetupRequired = 0;
uiDateAndTimeStatusScreen();
}
<file_sep>/src/firmware/src/Ui/UiDoorControlScreen.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Platform/Event.h"
#include "../Platform/NvmSettings.h"
#include "../Door.h"
#include "Ui.h"
#define MOVE_DOOR_MENU_LINE "Move door ? "
#define MOVE_DOOR_LINE "Move door... "
#define CALIBRATE_DOOR_MENU_LINE "Calibrate door ?"
#define CALIBRATE_DOOR_LINE "Move door to top"
#define DOOR_CONTROL_LINE ">UP DN DONE"
#define UP_POS UI_CURSOR_AT(0, 1)
#define DOWN_POS UI_CURSOR_AT(5, 1)
#define DONE_POS UI_CURSOR_AT(11, 1)
static void uiDoorControlScreen(void);
static void uiDoorControlScreenWireInputAndDisplay(void);
static void uiDoorControlScreenOptionSelected(void);
static void uiDoorControlScreenOptionAfterSelected(void);
static void uiDoorOnCalibrated(const struct Event *event);
static const struct EventSubscription onDoorCalibratedSubscription =
{
.type = DOOR_CALIBRATED,
.handler = &uiDoorOnCalibrated,
.state = (void *) 0
};
void uiDoorControlMenuScreen(void)
{
uiState.menu.itemText = MOVE_DOOR_MENU_LINE;
uiState.menu.onNext = &uiDoorCalibrationMenuScreen;
uiState.menu.onOk = &uiDoorControlScreen;
uiMenuScreen();
}
static void uiDoorControlScreen(void)
{
memcpy(
&uiState.screen[0],
MOVE_DOOR_LINE,
UI_SCREEN_WIDTH + 1);
memcpy(
&uiState.screen[UI_SCREEN_WIDTH + 1],
DOOR_CONTROL_LINE,
UI_SCREEN_WIDTH + 1);
uiState.flags.bits.isDoorBeingCalibrated = 0;
uiDoorControlScreenWireInputAndDisplay();
}
static void uiDoorControlScreenWireInputAndDisplay(void)
{
uiState.input.menu.options.cursorPositions[0] = UP_POS;
uiState.input.menu.options.cursorPositions[1] = DOWN_POS;
uiState.input.menu.options.cursorPositions[2] = DONE_POS;
uiState.input.cursorPosition = UP_POS;
uiState.input.selectedOptionIndex = 0;
uiState.input.buttons = &uiInputIsOptions;
uiState.input.onPreEnter = &uiDoorControlScreenOptionSelected;
uiState.input.onEnter = &uiDoorControlScreenOptionAfterSelected;
uiScreenBlit();
}
static void uiDoorControlScreenOptionSelected(void)
{
// TODO: COULD DO WITH CAPTURING DOOR_ABORTED AND THEN SHOWING AN ALERT SCREEN WITH A MESSAGE FOR A FAULT ('JAMMED/TOO HEAVY', 'SPOOL REVERSED', etc.) PROBABLY A BACKLIGHT FLASH AS WELL. ALERT SCREEN WILL BE GENERALLY USEFUL, SO MAKE A 'uiAlertScreen.c' MODULE FOR IT.
if (uiState.input.selectedOptionIndex == 0)
{
doorManualStartOpening();
uiState.flags.bits.isDoorBeingManuallyControlled = 1;
}
if (uiState.input.selectedOptionIndex == 1)
{
doorManualStartClosing();
uiState.flags.bits.isDoorBeingManuallyControlled = 1;
}
}
static void uiDoorControlScreenOptionAfterSelected(void)
{
if (uiState.flags.bits.isDoorBeingManuallyControlled)
{
doorManualStop();
uiState.flags.bits.isDoorBeingManuallyControlled = 0;
}
else if (uiState.input.selectedOptionIndex == 2)
{
if (uiState.flags.bits.isInitialSetupRequired)
{
uiNvmSettings.application.door.mode.isManuallyOverridden = 0;
uiNvmSettings.application.door.mode.isSunEventDriven = 1;
uiNvmSettings.application.door.mode.isTimeDriven = 0;
}
if (uiState.flags.bits.isDoorBeingCalibrated)
{
uiState.flags.bits.isDoorBeingCalibrated = 0;
eventSubscribe(&onDoorCalibratedSubscription);
// TODO: THIS NEEDS TO BE A FUNCTION INSTEAD
memcpy(
uiState.screen,
"! DO NOT TOUCH !\0"
"Calibrating... ",
sizeof(uiState.screen));
uiState.flags.bits.isScreenTimeoutDisabled = 1;
uiState.input.buttons = &uiInputIsUninitialised;
uiState.input.cursorPosition = UI_NO_CURSOR;
uiScreenBlit();
doorCalibrate();
}
else
uiDateAndTimeStatusScreen();
}
}
void uiDoorCalibrationMenuScreen(void)
{
uiState.menu.itemText = CALIBRATE_DOOR_MENU_LINE;
uiState.menu.onNext = &UI_LAST_SETTINGS_SCREEN;
uiState.menu.onOk = &uiDoorCalibrationScreen;
uiMenuScreen();
}
void uiDoorCalibrationScreen(void)
{
memcpy(
&uiState.screen[0],
CALIBRATE_DOOR_LINE,
UI_SCREEN_WIDTH + 1);
memcpy(
&uiState.screen[UI_SCREEN_WIDTH + 1],
DOOR_CONTROL_LINE,
UI_SCREEN_WIDTH + 1);
uiState.flags.bits.isDoorBeingCalibrated = 1;
uiDoorControlScreenWireInputAndDisplay();
}
static void uiDoorOnCalibrated(const struct Event *event)
{
uiScreenStartTimeout();
eventUnsubscribe(&onDoorCalibratedSubscription);
// TODO: IF FAULT THEN... (AND GO BACK TO THE CALIBRATION SCREEN...)
const struct DoorCalibrated *calibrated = (const struct DoorCalibrated *) event->args;
uiNvmSettings.application.door.height = calibrated->height;
if (uiState.flags.bits.isInitialSetupRequired)
{
uiOnSystemInitialSetupCompleted();
}
else
{
UI_DEFAULT_SCREEN();
}
}
<file_sep>/src/firmware/src/Location.h
#ifndef __CLUCK2SESAME_SRC_LOCATION_H
#define __CLUCK2SESAME_SRC_LOCATION_H
#include <stdint.h>
#include "Platform/Event.h"
#define LONGLAT_RESOLUTION 10
#define LONGLAT_ONE_DEGREE (1 * LONGLAT_RESOLUTION)
#define LONGLAT_HALF_DEGREE (1 * LONGLAT_RESOLUTION / 2)
struct Location;
#define LOCATION_CHANGED ((EventType) 0x48)
struct LocationChanged
{
const struct Location *location;
};
struct Location
{
int8_t latitudeOffset;
int8_t longitudeOffset;
};
extern void locationInitialise(void);
#endif
<file_sep>/src/firmware/src/Platform/VoltageRegulator.c
#include <xc.h>
#include <stdint.h>
#include "Event.h"
#include "NearScheduler.h"
#include "VoltageRegulator.h"
static void onRegulatedVoltageRailStabilised(void *state);
static void onMcuVoltageRailStabilised(void *state);
static uint8_t enableCount;
static uint8_t fullyEnabled;
void voltageRegulatorInitialise(void)
{
ANSELBbits.ANSB0 = 0;
ANSELBbits.ANSB2 = 0;
LATBbits.LATB0 = 0;
LATBbits.LATB2 = 0;
TRISBbits.TRISB0 = 0;
TRISBbits.TRISB2 = 0;
enableCount = 0;
fullyEnabled = 0;
}
void voltageRegulatorEnable(void)
{
LATBbits.LATB2 = 1;
if (++enableCount > 1)
return;
static const struct NearSchedule waitForRegulatedVoltageRailToStabilise =
{
.ticks = MS_TO_TICKS(64),
.handler = onRegulatedVoltageRailStabilised
};
nearSchedulerAdd(&waitForRegulatedVoltageRailToStabilise);
}
static void onRegulatedVoltageRailStabilised(void *state)
{
if (!enableCount)
return;
LATBbits.LATB0 = 1;
static const struct NearSchedule waitForMcuVoltageRailToStabilise =
{
.ticks = MS_TO_TICKS(4),
.handler = onMcuVoltageRailStabilised
};
nearSchedulerAdd(&waitForMcuVoltageRailToStabilise);
}
static void onMcuVoltageRailStabilised(void *state)
{
if (!enableCount)
return;
eventPublish(VOLTAGE_REGULATOR_ENABLED, &eventEmptyArgs);
fullyEnabled = 1;
}
void voltageRegulatorDisable(void)
{
if (enableCount > 1)
{
enableCount--;
return;
}
if (enableCount == 1 && fullyEnabled)
{
eventPublish(VOLTAGE_REGULATOR_DISABLED, &eventEmptyArgs);
fullyEnabled = 0;
}
LATBbits.LATB0 = 0;
LATBbits.LATB2 = 0;
enableCount = 0;
}
uint8_t voltageRegulatorIsEnabled(void)
{
return fullyEnabled;
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeSampleParametersCommand.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include <unity.h>
#include "Mock_Nvm.h"
#include "Platform/HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixtureWithUart.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
TEST_FILE("Platform/Event.c")
static void periodicMonitorSampleNowCallback(struct MonitoredParametersSampled *sample, int numCalls);
static void stubMonitoredParametersSampledFor(const struct MonitoredParametersSampled *sample);
static uint8_t hexDigitHigh(uint8_t value);
static uint8_t hexDigitLow(uint8_t value);
static uint8_t byteHigh(uint16_t value);
static uint8_t byteLow(uint16_t value);
static const struct MonitoredParametersSampled *stubbedMonitoredParametersSampled;
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
periodicMonitorSampleNow_StubWithCallback(&periodicMonitorSampleNowCallback);
}
static void periodicMonitorSampleNowCallback(struct MonitoredParametersSampled *sample, int numCalls)
{
TEST_ASSERT_NOT_NULL_MESSAGE(stubbedMonitoredParametersSampled, "A");
TEST_ASSERT_NOT_NULL_MESSAGE(sample, "B");
memcpy(sample, stubbedMonitoredParametersSampled, sizeof(struct MonitoredParametersSampled));
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_uart1_receivesSampleParametersCommand_expectSampledParametersAreTransmittedToHost(void)
{
struct MonitoredParametersSampled sample;
stubMonitoredParametersSampledFor(anyBytesInto(&sample, sizeof(struct MonitoredParametersSampled)));
uint8_t command[] = {CALIBRATIONMODE_CMD_SAMPLEPARAMETERS, CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(17, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_RESULT, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(sample.timestamp), deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(sample.timestamp), deviceToHostBytes[2], "2");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(',', deviceToHostBytes[3], "3");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(sample.flags.all), deviceToHostBytes[4], "4");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(sample.flags.all), deviceToHostBytes[5], "5");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(',', deviceToHostBytes[6], "6");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(byteHigh(sample.fvr)), deviceToHostBytes[7], "7");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(byteHigh(sample.fvr)), deviceToHostBytes[8], "8");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(byteLow(sample.fvr)), deviceToHostBytes[9], "9");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(byteLow(sample.fvr)), deviceToHostBytes[10], "10");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(',', deviceToHostBytes[11], "11");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(byteHigh(sample.temperature)), deviceToHostBytes[12], "12");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(byteHigh(sample.temperature)), deviceToHostBytes[13], "13");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitHigh(byteLow(sample.temperature)), deviceToHostBytes[14], "14");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(hexDigitLow(byteLow(sample.temperature)), deviceToHostBytes[15], "15");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[16], "EOL");
}
static void stubMonitoredParametersSampledFor(const struct MonitoredParametersSampled *sample)
{
stubbedMonitoredParametersSampled = sample;
}
static uint8_t hexDigitHigh(uint8_t value)
{
return hexDigitLow((value >> 4) & 0x0f);
}
static uint8_t hexDigitLow(uint8_t value)
{
value &= 0x0f;
if (value > 9)
return 'a' + (value - 10);
return '0' + value;
}
static uint8_t byteHigh(uint16_t value)
{
return (uint8_t) (value >> 8);
}
static uint8_t byteLow(uint16_t value)
{
return (uint8_t) (value & 0xff);
}
void test_uart1_receivesSampleParametersCommandWithAnArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_SAMPLEPARAMETERS, '1', CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
<file_sep>/src/firmware/src/Platform/FarScheduler.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "Event.h"
#include "Clock.h"
#include "FarScheduler.h"
#define MAX_SCHEDULES 32
struct FarScheduleWithFlags
{
uint8_t dateDiscriminator;
const struct FarSchedule *data;
};
static void buggyCompilerWorkaround(void)
{
static const struct FarSchedule dummy = { .eventArgs = _OMNITARGET };
static const struct FarScheduleWithFlags dummy2 = { .data = _OMNITARGET };
}
static void onDateChanged(const struct Event *event);
static void onTimeChanged(const struct Event *event);
static uint8_t dateDiscriminator;
static struct FarScheduleWithFlags schedules[MAX_SCHEDULES];
static struct FarScheduleWithFlags *noMoreSchedules = schedules + MAX_SCHEDULES;
void farSchedulerInitialise(void)
{
static const struct EventSubscription onDateChangedSubscription =
{
.type = DATE_CHANGED,
.handler = &onDateChanged,
.state = (void *) 0
};
eventSubscribe(&onDateChangedSubscription);
static const struct EventSubscription onTimeChangedSubscription =
{
.type = TIME_CHANGED,
.handler = &onTimeChanged,
.state = (void *) 0
};
eventSubscribe(&onTimeChangedSubscription);
dateDiscriminator = 1;
#ifdef TEST
memset(&schedules, 0, sizeof(schedules));
#endif
}
static void onDateChanged(const struct Event *event)
{
dateDiscriminator++;
}
static void onTimeChanged(const struct Event *event)
{
const struct TimeChanged *args = (const struct TimeChanged *) event->args;
for (struct FarScheduleWithFlags *schedule = schedules; schedule != noMoreSchedules; schedule++)
{
if (
schedule->dateDiscriminator == dateDiscriminator &&
schedule->data->time.hour == args->now->hour &&
schedule->data->time.minute == args->now->minute)
{
const struct Event *eventArgs = schedule->data->eventArgs;
if (!eventArgs)
eventArgs = &eventEmptyArgs;
eventPublish(schedule->data->eventType, eventArgs);
schedule->data = (const struct FarSchedule *) 0;
}
}
}
void farSchedulerAdd(const struct FarSchedule *schedule)
{
for (struct FarScheduleWithFlags *dest = schedules; dest != noMoreSchedules; dest++)
{
if (!dest->data)
{
dest->dateDiscriminator = dateDiscriminator;
dest->data = schedule;
return;
}
}
// TODO: THIS SHOULD REGISTER A FAULT
}
void farSchedulerRemove(const struct FarSchedule *schedule)
{
for (struct FarScheduleWithFlags *dest = schedules; dest != noMoreSchedules; dest++)
{
if (dest->data == schedule)
dest->data = (const struct FarSchedule *) 0;
}
}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorDisable1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
TEST_FILE("Platform/VoltageRegulatorFixture.c")
const struct Event eventEmptyArgs = { };
void test_voltageRegulatorDisable_calledAfterEnabledOnce_expectEnablePinIsLow(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
voltageRegulatorDisable();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB2, "A");
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB2, "B");
callScheduleHandlerIfPresentAndForget();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB2, "C");
}
void test_voltageRegulatorDisable_calledAfterVoltageRailStabilised_expectEnablePinIsLow(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
voltageRegulatorDisable();
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE(LATBbits.LATB2);
}
void test_voltageRegulatorDisable_calledAfterFullyEnabledOnce_expectEnablePinIsLow(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
voltageRegulatorDisable();
TEST_ASSERT_FALSE(LATBbits.LATB2);
}
void test_voltageRegulatorDisable_calledAfterEnabledOnce_expectVmcuSelPinIsLow(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
voltageRegulatorDisable();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB0, "A");
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB0, "B");
callScheduleHandlerIfPresentAndForget();
TEST_ASSERT_FALSE_MESSAGE(LATBbits.LATB0, "C");
}
void test_voltageRegulatorDisable_calledAfterVoltageRailStabilised_expectVmcuSelPinIsLow(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
callScheduleHandlerAndForget();
voltageRegulatorDisable();
callScheduleHandlerAndForget();
TEST_ASSERT_FALSE(LATBbits.LATB0);
}
void test_voltageRegulatorDisable_calledAfterFullyEnabledOnce_expectVmcuSelPinIsLow(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
voltageRegulatorDisable();
TEST_ASSERT_FALSE(LATBbits.LATB0);
}
void test_voltageRegulatorDisable_calledOnceAfterEnabledTwice_expectEnablePinIsHigh(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
voltageRegulatorEnable();
voltageRegulatorDisable();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB2, "A");
callScheduleHandlerAndForget();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB2, "B");
callScheduleHandlerAndForget();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB2, "C");
}
void test_voltageRegulatorDisable_calledOnceAfterEnabledTwice_expectVmcuSelPinIsHigh(void)
{
voltageRegulatorInitialise();
fullyEnableVoltageRegulator();
voltageRegulatorEnable();
voltageRegulatorDisable();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB0, "A");
callScheduleHandlerIfPresentAndForget();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB0, "B");
callScheduleHandlerIfPresentAndForget();
TEST_ASSERT_TRUE_MESSAGE(LATBbits.LATB0, "C");
}
<file_sep>/src/firmware/src/Platform/NearScheduler.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_NEARSCHEDULER_H
#define __CLUCK2SESAME_SRC_PLATFORM_NEARSCHEDULER_H
#include <stdint.h>
#define MS_TO_TICKS(x) ((uint8_t) (((x) + 3) / 4))
typedef void (*NearScheduleHandler)(void *state);
struct NearSchedule
{
uint8_t ticks;
NearScheduleHandler handler;
void *state;
};
extern void nearSchedulerInitialise(void);
extern void nearSchedulerAdd(const struct NearSchedule *schedule);
extern void nearSchedulerAddOrUpdate(const struct NearSchedule *schedule);
#endif
<file_sep>/src/firmware/tests/Platform/CalibrationMode/CalibrationModeFixtureWithUart.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "Platform/PowerManagement.h"
#include "Platform/PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "../../NonDeterminism.h"
#include "../../Fixture.h"
#include "../../NvmSettingsFixture.h"
#include "CalibrationModeFixtureWithUart.h"
#define HOST_TO_DEVICE_BYTE_ADDR(x) __at(0x23a0 + (x))
#define DEVICE_TO_HOST_BYTE_ADDR(x) __at(0x23a8 + (x))
static void fakeUart1Initialise(void);
static void uart1_receivesInvalidCommand_expectErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes, uint8_t errorHigh, uint8_t errorLow);
volatile uint8_t hostToDeviceBytes[8] HOST_TO_DEVICE_BYTE_ADDR(0);
volatile uint8_t hostToDeviceByte0 HOST_TO_DEVICE_BYTE_ADDR(0);
volatile uint8_t hostToDeviceByte1 HOST_TO_DEVICE_BYTE_ADDR(1);
volatile uint8_t hostToDeviceByte2 HOST_TO_DEVICE_BYTE_ADDR(2);
volatile uint8_t hostToDeviceByte3 HOST_TO_DEVICE_BYTE_ADDR(3);
volatile uint8_t hostToDeviceByte4 HOST_TO_DEVICE_BYTE_ADDR(4);
volatile uint8_t hostToDeviceByte5 HOST_TO_DEVICE_BYTE_ADDR(5);
volatile uint8_t hostToDeviceByte6 HOST_TO_DEVICE_BYTE_ADDR(6);
volatile uint8_t hostToDeviceByte7 HOST_TO_DEVICE_BYTE_ADDR(7);
volatile uint8_t hostToDeviceNumberOfBytes;
volatile uint8_t deviceToHostBytes[18] DEVICE_TO_HOST_BYTE_ADDR(0);
volatile uint8_t deviceToHostByte0 DEVICE_TO_HOST_BYTE_ADDR(0);
volatile uint8_t deviceToHostByte1 DEVICE_TO_HOST_BYTE_ADDR(1);
volatile uint8_t deviceToHostByte2 DEVICE_TO_HOST_BYTE_ADDR(2);
volatile uint8_t deviceToHostByte3 DEVICE_TO_HOST_BYTE_ADDR(3);
volatile uint8_t deviceToHostByte4 DEVICE_TO_HOST_BYTE_ADDR(4);
volatile uint8_t deviceToHostByte5 DEVICE_TO_HOST_BYTE_ADDR(5);
volatile uint8_t deviceToHostByte6 DEVICE_TO_HOST_BYTE_ADDR(6);
volatile uint8_t deviceToHostByte7 DEVICE_TO_HOST_BYTE_ADDR(7);
volatile uint8_t deviceToHostByte8 DEVICE_TO_HOST_BYTE_ADDR(8);
volatile uint8_t deviceToHostByte9 DEVICE_TO_HOST_BYTE_ADDR(9);
volatile uint8_t deviceToHostByte10 DEVICE_TO_HOST_BYTE_ADDR(10);
volatile uint8_t deviceToHostByte11 DEVICE_TO_HOST_BYTE_ADDR(11);
volatile uint8_t deviceToHostByte12 DEVICE_TO_HOST_BYTE_ADDR(12);
volatile uint8_t deviceToHostByte13 DEVICE_TO_HOST_BYTE_ADDR(13);
volatile uint8_t deviceToHostByte14 DEVICE_TO_HOST_BYTE_ADDR(14);
volatile uint8_t deviceToHostByte15 DEVICE_TO_HOST_BYTE_ADDR(15);
volatile uint8_t deviceToHostByte16 DEVICE_TO_HOST_BYTE_ADDR(16);
volatile uint8_t deviceToHostByte17 DEVICE_TO_HOST_BYTE_ADDR(17);
volatile uint8_t deviceToHostNumberOfBytes;
volatile uint8_t fakeUart1SessionIndex;
volatile uint8_t fakeUart1IsSessionInvalid;
void calibrationModeFixtureSetUp(void)
{
fakeUart1Initialise();
eventInitialise();
}
static void fakeUart1Initialise(void)
{
RC1STA = 0;
TX1STA = 0;
fakeUart1SessionIndex++;
for (uint16_t i = 0; i < 2084; i++)
asm("nop");
while (PIR3bits.RC1IF)
(void) RC1REG;
deviceToHostNumberOfBytes = 0;
hostToDeviceNumberOfBytes = 0;
fakeUart1IsSessionInvalid = 0;
}
void calibrationModeFixtureTearDown(void)
{
TEST_ASSERT_FALSE_MESSAGE(fakeUart1IsSessionInvalid, "UART1 violations !");
}
void stubNvmSettingsWithCalibrationRequired(void)
{
static const union NvmSettings withCalibrationRequired =
{
.platform =
{
.flags = { .bits = { .isCalibrationRequired = 1 } }
}
};
stubNvmSettings(&withCalibrationRequired);
}
void stubNvmSettingsWithoutCalibrationRequired(void)
{
static const union NvmSettings withoutCalibrationRequired =
{
.platform =
{
.flags = { .bits = { .isCalibrationRequired = 0 } }
}
};
stubNvmSettings(&withoutCalibrationRequired);
}
void fakeHostToDeviceSend(const uint8_t *bytes, size_t numberOfBytes)
{
if (numberOfBytes > sizeof(hostToDeviceBytes))
numberOfBytes = sizeof(hostToDeviceBytes);
memcpy((void *) hostToDeviceBytes, bytes, numberOfBytes);
hostToDeviceNumberOfBytes = (uint8_t) numberOfBytes;
}
void fakeHostWaitForDeviceResponse(void)
{
CPUDOZEbits.DOZEN = 0;
CPUDOZEbits.IDLEN = 1;
INTCONbits.PEIE = 1;
uint8_t byteIndex = 0;
while (true)
{
dispatchAllEvents();
eventPublish(WOKEN_FROM_SLEEP, &eventEmptyArgs);
while (byteIndex < deviceToHostNumberOfBytes)
{
TEST_ASSERT_LESS_THAN_MESSAGE(sizeof(deviceToHostBytes), byteIndex, "Receive overflow");
if (deviceToHostBytes[byteIndex] == CALIBRATIONMODE_CMD_EOL)
{
dispatchAllEvents();
return;
}
byteIndex++;
}
}
}
void uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes)
{
uart1_receivesInvalidCommand_expectErrorIsTransmittedToHost(command, numberOfBytes, '0', '1');
}
static void uart1_receivesInvalidCommand_expectErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes, uint8_t errorHigh, uint8_t errorLow)
{
fakeHostToDeviceSend(command, numberOfBytes);
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(4, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_ERROR, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(errorHigh, deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(errorLow, deviceToHostBytes[2], "2");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[3], "EOL");
}
void uart1_receivesInvalidCommand_expectInvalidArgumentErrorIsTransmittedToHost(const uint8_t *command, size_t numberOfBytes)
{
uart1_receivesInvalidCommand_expectErrorIsTransmittedToHost(command, numberOfBytes, '0', '2');
}
<file_sep>/src/firmware/src/Platform/Lcd/LcdConfigure.c
#include <xc.h>
#include <stdint.h>
#include "../Event.h"
#include "../NearScheduler.h"
#include "Lcd.h"
static void lcdConfigureStateMachine(void *state);
void lcdConfigure(void)
{
static const struct NearSchedule waitForLcdToStabilise =
{
.ticks = MS_TO_TICKS(48),
.handler = &lcdConfigureStateMachine
};
nearSchedulerAdd(&waitForLcdToStabilise);
PWM5CONbits.PWM5EN = 1;
TRISAbits.TRISA2 = 0;
ANSELAbits.ANSA2 = 0;
lcdState.flags.isBusy = 1;
}
static void lcdConfigureStateMachine(void *state)
{
struct NearSchedule waitForLcdCommand =
{
.ticks = MS_TO_TICKS(8),
.handler = &lcdConfigureStateMachine,
.state = (void *) (((int) state) + 1)
};
switch ((int) state)
{
case 0:
case 1:
case 2:
lcdWriteNybble(LCD_NYBBLE_CMD | 0b00000011);
break;
case 3:
lcdWriteNybble(LCD_NYBBLE_CMD | 0b00000010);
break;
case 4:
lcdWriteCommand(
LCD_CMD_FUNCTION |
LCD_CMD_FUNCTION_TWOLINES |
LCD_CMD_FUNCTION_FONT5X8);
break;
case 5:
lcdWriteCommand(LCD_CMD_DISPLAY | LCD_CMD_DISPLAY_OFF);
break;
case 6:
lcdWriteCommand(LCD_CMD_DISPLAYCLEAR);
break;
case 7:
lcdWriteCommand(
LCD_CMD_ENTRYMODE |
LCD_CMD_ENTRYMODE_INCREMENT |
LCD_CMD_ENTRYMODE_NOSHIFT);
break;
case 8:
lcdWriteCommand(LCD_CMD_DISPLAY | LCD_CMD_DISPLAY_ON);
break;
default:
lcdState.flags.isBusy = 0;
eventPublish(LCD_ENABLED, &eventEmptyArgs);
waitForLcdCommand.handler = (NearScheduleHandler) 0;
}
nearSchedulerAdd(&waitForLcdCommand);
}
<file_sep>/src/firmware/tests/Door/TestDoorClosedOnOpenScheduleActioned.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectOpeningStateWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByteExcept(DoorTransition_Open)
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opening, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectMotorIsEnabled(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(1, motorEnableCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectMotorIsTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(
nvmSettings.application.door.height,
motorOnArgs[0],
"Height");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectMotorCurrentLimitIsMaximumLoad(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorLimitIsMaximumLoadCalls, "M");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectMotorIsEnabledBeforeCurrentLimitIsChanged(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_TRUE(motorEnableSequence < motorLimitIsMaximumLoadSequence);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsEnabled_expectMotorCurrentLimitIsChangedBeforeMotorIsTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_TRUE(motorLimitIsMaximumLoadSequence < motorOnSequence);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsDisabled_expectOpeningWaitingForEnabledMotorStateWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByteExcept(DoorTransition_Open)
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opening_WaitingForEnabledMotor, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsDisabled_expectMotorIsEnabled(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(1, motorEnableCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsDisabled_expectMotorIsNotTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosedAndMotorIsDisabled_expectMotorCurrentLimitIsNotChanged(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Closed,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
<file_sep>/src/firmware/tests/Platform/Motor/MotorFixture.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/NearScheduler.h"
#include "Platform/VoltageRegulator.h"
#include "Platform/Motor.h"
#include "../../NonDeterminism.h"
#include "../../Fixture.h"
#include "MotorFixture.h"
static void onMotorEnabled(const struct Event *event);
static void onMotorDisabled(const struct Event *event);
static void onVoltageRegulatorDisabled(const struct Event *event);
static void onMotorStarted(const struct Event *event);
static void onMotorStopped(const struct Event *event);
static uint8_t callSequence;
static uint8_t voltageRegulatorDisableIsStubbedForEvent;
uint8_t pwmTimerEnableCalls;
uint8_t pwmTimerDisableCalls;
uint8_t voltageRegulatorIsEnabledValue;
uint8_t voltageRegulatorEnableCalls;
uint8_t voltageRegulatorEnableSequence;
uint8_t voltageRegulatorDisableCalls;
uint8_t voltageRegulatorDisableSequence;
uint8_t onVoltageRegulatorDisabledCalls;
uint8_t onVoltageRegulatorDisabledSequence;
uint8_t onMotorEnabledCalls;
uint8_t onMotorEnabledSequence;
uint8_t onMotorDisabledCalls;
uint8_t onMotorDisabledSequence;
uint8_t onMotorStartedCalls;
struct MotorStarted onMotorStartedArgs;
uint8_t onMotorStoppedCalls;
struct MotorStopped onMotorStoppedArgs;
uint16_t nearSchedulerAddOrUpdateCalls;
const struct NearSchedule *nearSchedulerAddOrUpdateArgs[8];
void motorFixtureSetUp(void)
{
eventInitialise();
callSequence = 1;
pwmTimerEnableCalls = 0;
pwmTimerDisableCalls = 0;
voltageRegulatorDisableIsStubbedForEvent = 0;
voltageRegulatorIsEnabledValue = 0;
voltageRegulatorEnableCalls = 0;
voltageRegulatorEnableSequence = 0;
voltageRegulatorDisableCalls = 0;
voltageRegulatorDisableSequence = 0;
onVoltageRegulatorDisabledCalls = 0;
onVoltageRegulatorDisabledSequence = 0;
onMotorEnabledCalls = 0;
onMotorEnabledSequence = 0;
onMotorDisabledCalls = 0;
onMotorDisabledSequence = 0;
onMotorStartedCalls = 0;
onMotorStoppedCalls = 0;
nearSchedulerAddOrUpdateCalls = 0;
static const struct EventSubscription onMotorEnabledSubscription =
{
.type = MOTOR_ENABLED,
.handler = &onMotorEnabled,
.state = (void *) 0
};
eventSubscribe(&onMotorEnabledSubscription);
static const struct EventSubscription onMotorDisabledSubscription =
{
.type = MOTOR_DISABLED,
.handler = &onMotorDisabled,
.state = (void *) 0
};
eventSubscribe(&onMotorDisabledSubscription);
static const struct EventSubscription onMotorStartedSubscription =
{
.type = MOTOR_STARTED,
.handler = &onMotorStarted,
.state = (void *) 0
};
eventSubscribe(&onMotorStartedSubscription);
static const struct EventSubscription onMotorStoppedSubscription =
{
.type = MOTOR_STOPPED,
.handler = &onMotorStopped,
.state = (void *) 0
};
eventSubscribe(&onMotorStoppedSubscription);
}
static void onMotorEnabled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "MTR EN");
onMotorEnabledCalls++;
onMotorEnabledSequence = callSequence++;
}
static void onMotorDisabled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "MTR DIS");
onMotorDisabledCalls++;
onMotorDisabledSequence = callSequence++;
}
void motorFixtureTearDown(void)
{
}
void pwmTimerEnable(void)
{
pwmTimerEnableCalls++;
}
void pwmTimerDisable(void)
{
pwmTimerDisableCalls++;
}
void ensureMotorFullyEnabled(void)
{
stubVoltageRegulatorIsEnabled(1);
publishVoltageRegulatorEnabled();
motorEnable();
dispatchAllEvents();
}
void stubVoltageRegulatorIsEnabled(uint8_t value)
{
voltageRegulatorIsEnabledValue = value;
}
void publishVoltageRegulatorEnabled(void)
{
static const struct VoltageRegulatorEnabled emptyEventArgs = { };
eventPublish(VOLTAGE_REGULATOR_ENABLED, &emptyEventArgs);
}
void publishVoltageRegulatorDisabled(void)
{
static const struct VoltageRegulatorDisabled emptyEventArgs = { };
eventPublish(VOLTAGE_REGULATOR_DISABLED, &emptyEventArgs);
}
uint8_t voltageRegulatorIsEnabled(void)
{
return voltageRegulatorIsEnabledValue;
}
void voltageRegulatorEnable(void)
{
voltageRegulatorEnableCalls++;
voltageRegulatorEnableSequence = callSequence++;
}
void voltageRegulatorDisable(void)
{
voltageRegulatorDisableCalls++;
voltageRegulatorDisableSequence = callSequence++;
if (voltageRegulatorDisableIsStubbedForEvent)
publishVoltageRegulatorDisabled();
}
void mockOnVoltageRegulatorDisabled(void)
{
static const struct EventSubscription onVoltageRegulatorDisabledSubscription =
{
.type = VOLTAGE_REGULATOR_DISABLED,
.handler = &onVoltageRegulatorDisabled,
.state = (void *) 0
};
eventSubscribe(&onVoltageRegulatorDisabledSubscription);
}
static void onVoltageRegulatorDisabled(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "VR DIS");
onVoltageRegulatorDisabledCalls++;
onVoltageRegulatorDisabledSequence = callSequence++;
}
void stubVoltageRegulatorDisableToPublishEvent(void)
{
voltageRegulatorDisableIsStubbedForEvent = 1;
}
static void onMotorStarted(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "MTR STD");
onMotorStartedCalls++;
memcpy(&onMotorStartedArgs, event->args, sizeof(struct MotorStarted));
}
static void onMotorStopped(const struct Event *event)
{
TEST_ASSERT_NOT_NULL_MESSAGE(event->args, "MTR SPD");
onMotorStoppedCalls++;
memcpy(&onMotorStoppedArgs, event->args, sizeof(struct MotorStopped));
}
int16_t anyClockwiseCount(void)
{
return (int16_t) anyWordExcept(0) & 0x7fff;
}
int16_t anyAntiClockwiseCount(void)
{
return -anyClockwiseCount();
}
int16_t anyEncoderCount(void)
{
return (int16_t) anyWordExcept(0);
}
void nearSchedulerAddOrUpdate(const struct NearSchedule *schedule)
{
nearSchedulerAddOrUpdateArgs[
nearSchedulerAddOrUpdateCalls++ % (
sizeof(nearSchedulerAddOrUpdateArgs) /
sizeof(const struct NearSchedule *))
] = schedule;
}
<file_sep>/src/firmware/src/Platform/Lcd/LcdSetDdramAddress.c
#include <xc.h>
#include <stdint.h>
#include "../NearScheduler.h"
#include "Lcd.h"
static void buggyCompilerWorkaround(void)
{
static const struct LcdSetAddressTransaction dummy =
{
.state = _OMNITARGET
};
}
void lcdSetDdramAddress(const struct LcdSetAddressTransaction *transaction)
{
if (!transaction || lcdState.flags.isBusy)
return;
lcdState.transaction.callback = transaction->callback;
lcdState.transaction.state = transaction->state;
static const struct NearSchedule waitForLcdCommand =
{
.ticks = MS_TO_TICKS(1),
.handler = &lcdTransactionCompleted
};
lcdWriteCommand(LCD_CMD_SETDDRAMADDRESS | transaction->address);
nearSchedulerAdd(&waitForLcdCommand);
lcdState.flags.isBusy = 1;
}
<file_sep>/src/firmware/src/Platform/HexDigits.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_HEXDIGITS_H
#define __CLUCK2SESAME_SRC_PLATFORM_HEXDIGITS_H
#include <stdint.h>
#include <stdbool.h>
extern void hexDigitsForByte(uint8_t *outTwoDigits, uint8_t inByte);
extern void hexDigitsForWord(uint8_t *outFourDigits, uint16_t inWord);
extern bool hexDigitsToWord(uint16_t *outWord, const uint8_t *inFourDigits);
#endif
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeNoCommand.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Nvm.h"
#include "Mock_HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixtureWithUart.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
TEST_FILE("Platform/Event.c")
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_uart1_receivesNoCommand_expectOkIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(4, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_RESULT, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE('O', deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE('K', deviceToHostBytes[2], "2");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[3], "EOL");
}
<file_sep>/src/firmware/tests/Platform/Motor/MotorFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_MOTOR_MOTORFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_MOTOR_MOTORFIXTURE_H
#include <stdint.h>
#include "Platform/NearScheduler.h"
#include "Platform/VoltageRegulator.h"
#include "Platform/Motor.h"
#define STEERING_MASK ( \
_CWG1STR_STRA_MASK | \
_CWG1STR_STRB_MASK | \
_CWG1STR_STRC_MASK | \
_CWG1STR_STRD_MASK)
extern uint8_t pwmTimerEnableCalls;
extern uint8_t pwmTimerDisableCalls;
extern uint8_t voltageRegulatorIsEnabledValue;
extern uint8_t voltageRegulatorEnableCalls;
extern uint8_t voltageRegulatorEnableSequence;
extern uint8_t voltageRegulatorDisableCalls;
extern uint8_t voltageRegulatorDisableSequence;
extern uint8_t onVoltageRegulatorDisabledCalls;
extern uint8_t onVoltageRegulatorDisabledSequence;
extern uint8_t onMotorEnabledCalls;
extern uint8_t onMotorEnabledSequence;
extern uint8_t onMotorDisabledCalls;
extern uint8_t onMotorDisabledSequence;
extern uint8_t onMotorStartedCalls;
extern struct MotorStarted onMotorStartedArgs;
extern uint8_t onMotorStoppedCalls;
extern struct MotorStopped onMotorStoppedArgs;
extern uint16_t nearSchedulerAddOrUpdateCalls;
extern const struct NearSchedule *nearSchedulerAddOrUpdateArgs[8];
extern void motorFixtureSetUp(void);
extern void motorFixtureTearDown(void);
extern void publishVoltageRegulatorEnabled(void);
extern void publishVoltageRegulatorDisabled(void);
extern void stubVoltageRegulatorIsEnabled(uint8_t value);
extern void mockOnVoltageRegulatorDisabled(void);
extern void stubVoltageRegulatorDisableToPublishEvent(void);
extern void ensureMotorFullyEnabled(void);
extern int16_t anyClockwiseCount(void);
extern int16_t anyAntiClockwiseCount(void);
extern int16_t anyEncoderCount(void);
#endif
<file_sep>/src/firmware/tests/NonDeterminism.c
#include <xc.h>
#include <stdint.h>
#include "NonDeterminism.h"
volatile int16_t rngSeed __at(0x0420);
static void ensureSeedIsInitialised(void)
{
static uint8_t isInitialised = 0;
if (isInitialised)
return;
isInitialised = 1;
if (rngSeed == 0)
rngSeed = 1;
rngSeed = rngSeed;
}
uint8_t anyBoolean(void)
{
return anyByte() % 2 == 0;
}
uint8_t anyByte(void)
{
ensureSeedIsInitialised();
uint8_t msb = rngSeed < 0 ? 1 : 0;
rngSeed <<= 1;
if (msb)
rngSeed ^= 0x002d;
return (uint8_t) rngSeed;
}
uint8_t anyByteExcept(uint8_t except)
{
uint8_t byte = anyByte();
while (byte == except)
byte = anyByte();
return byte;
}
uint8_t anyByteWithMaskSet(uint8_t mask)
{
return anyByte() | mask;
}
uint8_t anyByteWithMaskClear(uint8_t mask)
{
return anyByte() & ~mask;
}
uint8_t anyByteLessThan(uint8_t value)
{
return anyByte() % value;
}
uint16_t anyWordExcept(uint16_t except)
{
uint16_t word = anyWord();
while (word == except)
word = anyWord();
return word;
}
uint16_t anyWord(void)
{
uint16_t word = 0;
for (uint8_t i = 0; i < 2; i++)
word |= ((uint16_t) anyByte()) << (i * 8);
return word;
}
uint16_t anyWordLessThan(uint16_t value)
{
return anyWord() % value;
}
void *anyBytesInto(void *dest, size_t numberOfBytes)
{
if (dest)
{
uint8_t *byteDest = (uint8_t *) dest;
for (size_t i = 0; i < numberOfBytes; i++)
*(byteDest++) = anyByte();
}
return dest;
}
<file_sep>/src/firmware/src/Platform/NvmSettings.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_NVMSETTINGS_H
#define __CLUCK2SESAME_SRC_PLATFORM_NVMSETTINGS_H
#include <stdint.h>
#include "Event.h"
#include "../ApplicationNvmSettings.h"
#define NVM_SETTINGS_CHANGED ((EventType) 0x30)
struct NvmSettingsChanged { EMPTY_EVENT_ARGS };
union NvmSettings
{
uint8_t raw[32];
struct
{
union
{
uint8_t raw[15];
struct
{
struct
{
uint8_t contrast;
uint8_t backlightBrightness;
} lcd;
struct
{
uint8_t currentLimitNoLoad;
uint8_t currentLimitMaximumLoad;
} motor;
struct
{
uint16_t temperatureHighAdc;
uint8_t temperatureHighCelsius;
uint16_t temperatureCoefficient;
} temperature;
struct
{
uint16_t placeholder[2]; // TODO: FOR CALIBRATION PURPOSES
} crystal;
union
{
uint8_t all;
struct
{
unsigned int isCalibrationRequired : 1;
} bits;
} flags;
};
} platform;
union ApplicationNvmSettings application;
uint8_t crc8;
};
};
extern uint8_t nvmSettingsStore(const union NvmSettings *newSettings);
extern __section("NvmSettings") const volatile union NvmSettings nvmSettings;
#endif
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Nvm.h"
#include "Mock_HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectSubscriptionToWokenFromSleep(void)
{
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
assertWokenFromSleepSubscription();
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectNoSubscriptionToWokenFromSleep(void)
{
stubNvmSettingsWithoutCalibrationRequired();
calibrationModeInitialise();
assertNoWokenFromSleepSubscription();
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectClockReferenceModuleIsEnabled(void)
{
stubNvmSettingsWithCalibrationRequired();
PMD0 = anyByteWithMaskSet(_PMD0_CLKRMD_MASK);
uint8_t originalPmd0 = PMD0;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd0 & ~_PMD0_CLKRMD_MASK, PMD0);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectClockReferenceModuleIsDisabled(void)
{
stubNvmSettingsWithoutCalibrationRequired();
PMD0 = anyByteWithMaskClear(_PMD0_CLKRMD_MASK);
uint8_t originalPmd0 = PMD0;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd0 | _PMD0_CLKRMD_MASK, PMD0);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPinsAreDigital(void)
{
stubNvmSettingsWithCalibrationRequired();
static const uint8_t usedPins = _ANSELB_ANSB6_MASK | _ANSELB_ANSB7_MASK;
ANSELB = anyByteWithMaskSet(usedPins);
uint8_t originalAnselb = ANSELB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnselb & ~usedPins, ANSELB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPinsAreDigital(void)
{
stubNvmSettingsWithoutCalibrationRequired();
static const uint8_t usedPins = _ANSELB_ANSB6_MASK | _ANSELB_ANSB7_MASK;
ANSELB = anyByteWithMaskSet(usedPins);
uint8_t originalAnselb = ANSELB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalAnselb & ~usedPins, ANSELB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPgcPinIsOutput(void)
{
stubNvmSettingsWithCalibrationRequired();
TRISB = anyByteWithMaskSet(_TRISB_TRISB6_MASK);
uint8_t originalTrisb = TRISB & ~_TRISB_TRISB7_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB6_MASK, TRISB & ~_TRISB_TRISB7_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPgcPinIsOutput(void)
{
stubNvmSettingsWithoutCalibrationRequired();
TRISB = anyByteWithMaskSet(_TRISB_TRISB6_MASK);
uint8_t originalTrisb = TRISB & ~_TRISB_TRISB7_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB6_MASK, TRISB & ~_TRISB_TRISB7_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPgcPinIsMappedToReferenceClockOutput(void)
{
stubNvmSettingsWithCalibrationRequired();
RB6PPS = anyByteExcept(0x1b);
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0x1b, RB6PPS);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPgcPinIsNotMappedToAnyPeripheralOutput(void)
{
stubNvmSettingsWithoutCalibrationRequired();
RB6PPS = anyByteExcept(0);
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0, RB6PPS);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPgdPinIsOutput(void)
{
stubNvmSettingsWithCalibrationRequired();
TRISB = anyByteWithMaskSet(_TRISB_TRISB7_MASK);
uint8_t originalTrisb = TRISB & ~_TRISB_TRISB6_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB7_MASK, TRISB & ~_TRISB_TRISB6_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPgdPinIsOutput(void)
{
stubNvmSettingsWithoutCalibrationRequired();
TRISB = anyByteWithMaskSet(_TRISB_TRISB7_MASK);
uint8_t originalTrisb = TRISB & ~_TRISB_TRISB6_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB7_MASK, TRISB & ~_TRISB_TRISB6_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPgdPinIsOpenDrain(void)
{
stubNvmSettingsWithCalibrationRequired();
ODCONB = anyByteWithMaskClear(_ODCONB_ODCB7_MASK);
uint8_t originalOdconb = ODCONB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalOdconb | _ODCONB_ODCB7_MASK, ODCONB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPgdPinIsNotOpenDrain(void)
{
stubNvmSettingsWithoutCalibrationRequired();
ODCONB = anyByteWithMaskSet(_ODCONB_ODCB7_MASK);
uint8_t originalOdconb = ODCONB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalOdconb & ~_ODCONB_ODCB7_MASK, ODCONB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPgdPinIsMappedToUart1TxAndRx(void)
{
static const uint8_t ppsOutUart1Tx = 0x0f;
static const uint8_t ppsInRb7 = 0x0f;
stubNvmSettingsWithCalibrationRequired();
RB7PPS = anyByteExcept(0x10);
RX1DTPPS = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(ppsOutUart1Tx, RB7PPS, "TX");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(ppsInRb7, RX1DTPPS, "RX");
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPgdPinIsNotMappedToAnyPeripheralOutput(void)
{
stubNvmSettingsWithoutCalibrationRequired();
RB7PPS = anyByteExcept(0);
RX1DTPPS = anyByteExcept(0);
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, RB7PPS, "TX");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, RX1DTPPS, "RX");
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectIcspPinsAreLow(void)
{
stubNvmSettingsWithCalibrationRequired();
LATB = anyByteWithMaskSet(_LATB_LATB6_MASK | _LATB_LATB7_MASK);
uint8_t originalLatb = LATB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLatb & ~(_LATB_LATB6_MASK | _LATB_LATB7_MASK), LATB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectIcspPinsAreLow(void)
{
stubNvmSettingsWithoutCalibrationRequired();
LATB = anyByteWithMaskSet(_LATB_LATB6_MASK | _LATB_LATB7_MASK);
uint8_t originalLatb = LATB;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalLatb & ~(_LATB_LATB6_MASK | _LATB_LATB7_MASK), LATB);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectReferenceClockSourceIs32768HzCrystal(void)
{
stubNvmSettingsWithCalibrationRequired();
CLKRCLK = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0b0101 << _CLKRCLK_CLKRCLK_POSITION, CLKRCLK & _CLKRCLK_CLKRCLK_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectReferenceClockDutyCycleIs50Percent(void)
{
stubNvmSettingsWithCalibrationRequired();
CLKRCON = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0b10 << _CLKRCON_CLKRDC_POSITION, CLKRCON & _CLKRCON_CLKRDC_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectReferenceClockIsNotDivided(void)
{
stubNvmSettingsWithCalibrationRequired();
CLKRCON = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0b000 << _CLKRCON_CLKRDIV_POSITION, CLKRCON & _CLKRCON_CLKRDIV_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectReferenceClockIsNotEnabled(void)
{
stubNvmSettingsWithCalibrationRequired();
CLKRCON = anyByteWithMaskSet(_CLKRCON_CLKREN_MASK);
calibrationModeInitialise();
TEST_ASSERT_BIT_LOW(_CLKRCON_CLKREN_POSITION, CLKRCON);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1ModuleIsEnabled(void)
{
stubNvmSettingsWithCalibrationRequired();
PMD4 = anyByteWithMaskSet(_PMD4_UART1MD_MASK);
uint8_t originalPmd4 = PMD4;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd4 & ~_PMD4_UART1MD_MASK, PMD4);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsNotRequired_expectUart1ModuleIsDisabled(void)
{
stubNvmSettingsWithoutCalibrationRequired();
PMD4 = anyByteWithMaskClear(_PMD4_UART1MD_MASK);
uint8_t originalPmd4 = PMD4;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd4 | _PMD4_UART1MD_MASK, PMD4);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1UsesAsynchronous8bitModeWithLowBaudMultiplierAndEnabledTransmitter(void)
{
stubNvmSettingsWithCalibrationRequired();
TX1STA = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT(_TX1STA_TXEN_MASK, TX1STA & ~_TX1STA_TRMT_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1BaudRateIs9600bps(void)
{
stubNvmSettingsWithCalibrationRequired();
SP1BRG = anyWord();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT16(51, SP1BRG);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1Uses8bitModeAndIsEnabledForContinuousReception(void)
{
static const uint8_t readonlyBits = _RC1STA_FERR_MASK | _RC1STA_OERR_MASK | _RC1STA_RX9D_MASK;
stubNvmSettingsWithCalibrationRequired();
RC1STA = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(_RC1STA_SPEN_MASK | _RC1STA_CREN_MASK, RC1STA & ~readonlyBits);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1Uses8bitBaudRateGeneratorWithIdleHighTx(void)
{
stubNvmSettingsWithCalibrationRequired();
BAUD1CON = anyByte();
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(0, BAUD1CON & ~_BAUD1CON_RCIDL_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1TxInterruptIsDisabled(void)
{
stubNvmSettingsWithCalibrationRequired();
PIE3 = anyByteWithMaskSet(_PIE3_TX1IE_MASK);
uint8_t originalPie3 = PIE3 & ~_PIE3_RC1IE_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie3 & ~_PIE3_TX1IE_MASK, PIE3 & ~_PIE3_RC1IE_MASK);
}
void test_calibrationModeInitialise_calledWhenCalibrationIsRequired_expectUart1RxInterruptIsEnabled(void)
{
stubNvmSettingsWithCalibrationRequired();
PIE3 = anyByteWithMaskClear(_PIE3_RC1IE_MASK);
uint8_t originalPie3 = PIE3 & ~_PIE3_TX1IE_MASK;
calibrationModeInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie3 | _PIE3_RC1IE_MASK, PIE3 & ~_PIE3_TX1IE_MASK);
}
<file_sep>/src/firmware/src/Platform/VoltageRegulator.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_VOLTAGEREGULATOR_H
#define __CLUCK2SESAME_SRC_PLATFORM_VOLTAGEREGULATOR_H
#include "Event.h"
#define VOLTAGE_REGULATOR_ENABLED ((EventType) 0x18)
struct VoltageRegulatorEnabled { EMPTY_EVENT_ARGS };
#define VOLTAGE_REGULATOR_DISABLED ((EventType) 0x19)
struct VoltageRegulatorDisabled { EMPTY_EVENT_ARGS };
extern void voltageRegulatorInitialise(void);
extern void voltageRegulatorEnable(void);
extern uint8_t voltageRegulatorIsEnabled(void);
extern void voltageRegulatorDisable(void);
#endif
<file_sep>/src/firmware/tests/Platform/Clock/ClockGetSetNowFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/PowerManagement.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "ClockGetSetNowFixture.h"
#include "../../NonDeterminism.h"
#include "../../Fixture.h"
void clockGetSetNowFixtureSetUp(void)
{
eventInitialise();
clockInitialise();
T0CON0bits.T0EN = 0;
T0CON1bits.T0CKPS = 0;
TEST_ASSERT_EQUAL_UINT8_MESSAGE(59, TMR0H, "60-second timebase required !");
}
void clockGetSetNowFixtureTearDown(void)
{
}
void tick(void)
{
PIR0bits.TMR0IF = 1;
publishWokenFromSleep();
dispatchAllEvents();
}
uint8_t anyNonLeapYear(void)
{
return anyNonLeapYearLessThan(100);
}
uint8_t anyNonLeapYearLessThan(uint8_t value)
{
while (1)
{
uint8_t year = anyByteLessThan(value);
if (year & 3)
return year;
};
}
uint8_t anyLeapYear(void)
{
return anyByteLessThan(100) & ~3;
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeRefclkCommand.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <unity.h>
#include "Mock_Nvm.h"
#include "Mock_HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixtureWithUart.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
TEST_FILE("Platform/Event.c")
static uint8_t anyInvalidArgument(void);
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_uart1_receivesRefclkOffCommand_expect0IsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, '0', CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(3, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_RESULT, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE('0', deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[2], "EOL");
}
void test_uart1_receivesRefclkOffCommand_expectRefclkIsDisabled(void)
{
uint8_t originalClkrcon = CLKRCON;
CLKRCON |= _CLKRCON_CLKREN_MASK;
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, '0', CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8(originalClkrcon & ~_CLKRCON_CLKREN_MASK, CLKRCON);
}
void test_uart1_receivesRefclkOnCommand_expect1IsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, '1', CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(3, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_RESULT, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE('1', deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[2], "EOL");
}
void test_uart1_receivesRefclkOnCommand_expectRefclkIsDisabled(void)
{
uint8_t originalClkrcon = CLKRCON;
CLKRCON &= ~_CLKRCON_CLKREN_MASK;
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, '1', CALIBRATIONMODE_CMD_EOL};
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8(originalClkrcon | _CLKRCON_CLKREN_MASK, CLKRCON);
}
void test_uart1_receivesRefclkCommandWithInvalidArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, anyInvalidArgument(), CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidArgumentErrorIsTransmittedToHost(command, sizeof(command));
}
static uint8_t anyInvalidArgument(void)
{
while (true)
{
uint8_t arg = anyByte();
if (arg != '0' && arg != '1' && arg != CALIBRATIONMODE_CMD_EOL)
return arg;
}
}
void test_uart1_receivesRefclkCommandWithoutArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
void test_uart1_receivesRefclkCommandWithMoreThanOneArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_REFCLK, '1', '0', CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
<file_sep>/src/firmware/tests/Platform/Battery/TestBatteryInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/Battery.h"
#include "BatteryFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Battery.c")
void onBeforeTest(void)
{
batteryFixtureSetUp();
}
void onAfterTest(void)
{
batteryFixtureTearDown();
}
void test_batteryInitialise_called_expectChargerEnablePinIsOutput(void)
{
TRISB = anyByteWithMaskSet(_TRISB_TRISB3_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(TRISBbits.TRISB3);
}
void test_batteryInitialise_called_expectChargerEnablePinIsDigital(void)
{
ANSELB = anyByteWithMaskSet(_ANSELB_ANSB3_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(ANSELBbits.ANSB3);
}
void test_batteryInitialise_called_expectChargerEnablePinIsLow(void)
{
LATB = anyByteWithMaskSet(_LATB_LATB3_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(LATBbits.LATB3);
}
void test_batteryInitialise_called_expectChargerGoodPinIsInput(void)
{
TRISB = anyByteWithMaskClear(_TRISB_TRISB5_MASK);
batteryInitialise();
TEST_ASSERT_TRUE(TRISBbits.TRISB5);
}
void test_batteryInitialise_called_expectChargerGoodPinIsDigital(void)
{
ANSELB = anyByteWithMaskSet(_ANSELB_ANSB5_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(ANSELBbits.ANSB5);
}
void test_batteryInitialise_called_expectChargerGoodPinUsesTtlThresholds(void)
{
INLVLB = anyByteWithMaskSet(_INLVLB_INLVLB5_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(INLVLBbits.INLVLB5);
}
void test_batteryInitialise_called_expectChargingPinIsInput(void)
{
TRISB = anyByteWithMaskClear(_TRISB_TRISB4_MASK);
batteryInitialise();
TEST_ASSERT_TRUE(TRISBbits.TRISB4);
}
void test_batteryInitialise_called_expectChargingPinIsDigital(void)
{
ANSELB = anyByteWithMaskSet(_ANSELB_ANSB4_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(ANSELBbits.ANSB4);
}
void test_batteryInitialise_called_expectChargingPinUsesTtlThresholds(void)
{
INLVLB = anyByteWithMaskSet(_INLVLB_INLVLB4_MASK);
batteryInitialise();
TEST_ASSERT_FALSE(INLVLBbits.INLVLB4);
}
void test_batteryInitialise_called_expectNonChargerTrisBitsAreUnchanged(void)
{
static const uint8_t usedPins = _TRISB_TRISB3_MASK | _TRISB_TRISB4_MASK | _TRISB_TRISB5_MASK;
TRISB = anyByte();
uint8_t expectedTrisb = TRISB | usedPins;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedTrisb, TRISB | usedPins);
}
void test_batteryInitialise_called_expectNonChargerAnselBitsAreUnchanged(void)
{
static const uint8_t usedPins = _ANSELB_ANSB3_MASK | _ANSELB_ANSB4_MASK | _ANSELB_ANSB5_MASK;
ANSELB = anyByte();
uint8_t expectedAnselb = ANSELB | usedPins;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedAnselb, ANSELB | usedPins);
}
void test_batteryInitialise_called_expectNonChargerLatBitsAreUnchanged(void)
{
static const uint8_t usedPins = _LATB_LATB3_MASK | _LATB_LATB4_MASK | _LATB_LATB5_MASK;
LATB = anyByte();
uint8_t expectedLatb = LATB | usedPins;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedLatb, LATB | usedPins);
}
void test_batteryInitialise_called_expectNonChargerInputPinThresholdsAreUnchanged(void)
{
static const uint8_t usedPins = _INLVLB_INLVLB4_MASK | _INLVLB_INLVLB5_MASK;
INLVLB = anyByte();
uint8_t expectedInlvlb = INLVLB | usedPins;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedInlvlb, INLVLB | usedPins);
}
void test_batteryInitialise_called_expectIocModuleIsEnabled(void)
{
PMD0 = anyByteWithMaskSet(_PMD0_IOCMD_MASK);
uint8_t expectedPmd0 = PMD0 & ~_PMD0_IOCMD_MASK;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedPmd0, PMD0);
}
void test_batteryInitialise_called_expectIocInterruptsAreEnabled(void)
{
PIE0 = anyByteWithMaskClear(_PIE0_IOCIE_MASK);
uint8_t expectedPie0 = PIE0 | _PIE0_IOCIE_MASK;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedPie0, PIE0);
}
void test_batteryInitialise_called_expectIocIsEnabledForPositiveEdgeOnChargerGoodPin(void)
{
IOCBP = anyByteWithMaskClear(_IOCBP_IOCBP5_MASK);
uint8_t expectedIocbp = IOCBP | _IOCBP_IOCBP5_MASK;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedIocbp, IOCBP);
}
void test_batteryInitialise_called_expectIocIsEnabledForNegativeEdgeOnChargerGoodPin(void)
{
IOCBN = anyByteWithMaskClear(_IOCBN_IOCBN5_MASK);
uint8_t expectedIocbn = IOCBN | _IOCBN_IOCBN5_MASK;
batteryInitialise();
TEST_ASSERT_EQUAL_HEX8(expectedIocbn, IOCBN);
}
void test_batteryInitialise_expectNoBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
dispatchAllEvents();
TEST_ASSERT_NULL(batteryChargerEnabledEventArgs);
}
void test_batteryInitialise_expectBatteryChargerDisabledEventIsNotPublished(void)
{
batteryInitialise();
dispatchAllEvents();
TEST_ASSERT_NULL(batteryChargerDisabledEventArgs);
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorPinDirections.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectEncoderPinsAreInputs(void)
{
static const uint8_t encoderPins = _TRISC_TRISC2_MASK | _TRISC_TRISC3_MASK;
uint8_t originalTrisc = TRISC;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalTrisc | encoderPins, TRISC);
}
void test_voltageRegulatorEnabled_onPublished_expectCurrentSensePinIsInput(void)
{
uint8_t originalTrisb = TRISB;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalTrisb | _TRISB_TRISB1_MASK, TRISB);
}
void test_voltageRegulatorDisabled_onPublished_expectEncoderPinsAreOutputs(void)
{
static const uint8_t encoderPins = _TRISC_TRISC2_MASK | _TRISC_TRISC3_MASK;
TRISC = anyByteWithMaskSet(encoderPins);
uint8_t originalTrisc = TRISC;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalTrisc & ~encoderPins, TRISC);
}
void test_voltageRegulatorDisabled_onPublished_expectCurrentSensePinIsOutput(void)
{
TRISB = anyByteWithMaskSet(_TRISB_TRISB1_MASK);
uint8_t originalTrisb = TRISB;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalTrisb & ~_TRISB_TRISB1_MASK, TRISB);
}
<file_sep>/src/firmware/src/Platform/PowerManagement.c
#include <xc.h>
#include <stdint.h>
#include "Main.h"
#include "Event.h"
#include "PowerManagement.h"
static void onAllEventsDispatched(const struct Event *event);
void powerManagementInitialise(void)
{
PMD0 = (uint8_t) ~(_PMD0_SYSCMD_MASK | _PMD0_NVMMD_MASK);
PMD1 = 0xff;
PMD2 = 0xff;
PMD3 = 0xff;
PMD4 = 0xff;
PMD5 = 0xff;
static const struct EventSubscription onAllEventsDispatchedSubscription =
{
.type = ALL_EVENTS_DISPATCHED,
.handler = &onAllEventsDispatched,
.state = (void *) 0
};
eventSubscribe(&onAllEventsDispatchedSubscription);
INTCONbits.PEIE = 1;
}
static void onAllEventsDispatched(const struct Event *event)
{
eventPublish(WOKEN_FROM_SLEEP, &eventEmptyArgs);
if (T2CONbits.ON || PIE3bits.RC1IE)
CPUDOZEbits.IDLEN = 1;
else
CPUDOZEbits.IDLEN = 0;
CPUDOZEbits.DOZEN = 0;
VREGCONbits.VREGPM = 1;
asm("sleep");
asm("nop");
}
<file_sep>/src/firmware/src/Door/DoorCalibrate.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/Event.h"
#include "../Platform/Motor.h"
#include "Door.h"
static void onDoorClosedForCalibration(const struct Event *event);
static void onDoorAbortedForCalibration(const struct Event *event);
static const struct EventSubscription onDoorClosedSubscription =
{
.type = DOOR_CLOSED,
.handler = &onDoorClosedForCalibration,
.state = (void *) 0
};
static const struct EventSubscription onDoorAbortedSubscription =
{
.type = DOOR_ABORTED,
.handler = &onDoorAbortedForCalibration,
.state = (void *) 0
};
static struct DoorCalibrated doorCalibrationEventArgs;
void doorCalibrate(void)
{
motorEnable();
doorStartFindingBottom(
DoorState_FindBottom,
DoorState_FindBottom_WaitingForEnabledMotor);
eventSubscribe(&onDoorClosedSubscription);
eventSubscribe(&onDoorAbortedSubscription);
}
void doorStartFindingBottom(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState)
{
if (motorIsEnabled())
{
motorLimitIsNoLoad();
motorOn(FIND_BOTTOM_LOWERING);
doorState.current = motorEnabledState;
doorState.closed.loweredHeight = 0;
doorState.findBottomIterations = 0;
}
else
doorState.current = motorDisabledState;
}
static void onDoorClosedForCalibration(const struct Event *event)
{
const struct DoorClosed *closed = (const struct DoorClosed *) event->args;
// TODO: IF DOOR HEIGHT < (say) 100mm THEN IT'S A NONSENSE CONDITION - IT WASN'T RAISED HIGH ENOUGH. SO SET A FAULT FLAG...
doorCalibrationEventArgs.fault.all = 0;
doorCalibrationEventArgs.height = (uint16_t) closed->loweredHeight;
eventPublish(DOOR_CALIBRATED, &doorCalibrationEventArgs);
eventUnsubscribe(&onDoorAbortedSubscription);
eventUnsubscribe(&onDoorClosedSubscription);
}
static void onDoorAbortedForCalibration(const struct Event *event)
{
const struct DoorAborted *aborted = (const struct DoorAborted *) event->args;
doorCalibrationEventArgs.fault.all = aborted->fault.all;
doorCalibrationEventArgs.height = 0;
// TODO: SINCE NO DOOR_CALIBRATED EVENT IS PUBLISHED HERE, THE UI HANGS...
eventUnsubscribe(&onDoorAbortedSubscription);
eventUnsubscribe(&onDoorClosedSubscription);
}
<file_sep>/src/firmware/src/Platform/Motor/MotorOnOff.c
/* NOTE: The ceedling tests do not cover a lot of this file as it is complex due to the asynchronous nature of the motor
control. If you make changes then there is no substitute for bench testing the motor as it is quicker and simpler
and guaranteed to reflect the real world. */
#include <xc.h>
#include <stdint.h>
#include "../Event.h"
#include "../NearScheduler.h"
#include "Motor.h"
#define PWM_INCREMENT_TICK_COUNT 10
#define ENCODER_STATIC_COUNT_LIMIT 10
#define CCP1CON_MODE_MASK (0b1111 << _CCP1CON_MODE_POSITION)
#define CCP1CON_COMPARE_AND_SET_MODE (0b1000 << _CCP1CON_MODE_POSITION)
#define MOTOR_RUNNING_STATE_STOPPED 0
#define MOTOR_RUNNING_STATE_STARTING 1
#define MOTOR_RUNNING_STATE_STARTED 2
static void incrementPwmDutyCycle(void *state);
static void motorRunningStateMonitor(void *state);
static struct MotorStopped motorStoppedEventArgs;
static uint8_t motorRunningState;
static struct MotorStarted motorStartedEventArgs;
static const struct NearSchedule pwmDutyCycleIncrementingSchedule =
{
.ticks = PWM_INCREMENT_TICK_COUNT,
.handler = &incrementPwmDutyCycle
};
static const struct NearSchedule motorRunningStateMonitorSchedule =
{
.ticks = 32 * PWM_INCREMENT_TICK_COUNT / ENCODER_STATIC_COUNT_LIMIT,
.handler = &motorRunningStateMonitor
};
void motorOn(int16_t count)
{
if (count == 0 || (CWG1STR & 0x0f) || motorRunningState != MOTOR_RUNNING_STATE_STOPPED)
return;
motorRunningState = MOTOR_RUNNING_STATE_STARTING;
motorStartedEventArgs.count = count;
eventPublish(MOTOR_STARTED, &motorStartedEventArgs);
uint8_t steeringMask = _CWG1STR_STRA_MASK;
if (count < 0)
{
steeringMask = _CWG1STR_STRB_MASK;
count = -count;
if (count == -32768)
count = 0x7fff;
}
CCP1CON &= ~CCP1CON_MODE_MASK;
PWM4DCH = 48 >> 2;
PWM4DCL = 0;
CCPR1H = (uint8_t) ((count >> 8) & 0xff);
CCPR1L = (uint8_t) ((count >> 0) & 0xff);
TMR1H = 0;
TMR1L = 0;
CCP1CON |= CCP1CON_COMPARE_AND_SET_MODE;
/* *********************************************************************
ALERT: The interrupt flags need to be cleared *AFTER* the CCP mode
change, see section 28.1.3 of the datasheet for the single sentence
that alludes to this. */
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 0;
PIR6bits.CCP1IF = 0;
PIR5bits.CLC2IF = 0;
CWG1AS0bits.SHUTDOWN = 0;
PIR7bits.CWG1IF = 0;
/* ******************************************************************* */
CWG1STR |= steeringMask;
nearSchedulerAddOrUpdate(&pwmDutyCycleIncrementingSchedule);
nearSchedulerAddOrUpdate(&motorRunningStateMonitorSchedule);
}
static void incrementPwmDutyCycle(void *state)
{
if (!(CWG1STR & CWG1STR_STEERING_MASK))
return;
if (PWM4DCH != (256 - 8) >> 2)
nearSchedulerAddOrUpdate(&pwmDutyCycleIncrementingSchedule);
PWM4DCH += 8 >> 2;
}
void motorOff(void)
{
CWG1AS0bits.SHUTDOWN = 1;
if (CWG1STR & CWG1STR_STEERING_MASK)
{
CWG1STR &= ~CWG1STR_STEERING_MASK;
motorStoppedEventArgs.requestedCount = motorStartedEventArgs.count;
motorStoppedEventArgs.fault.all = 0;
motorStoppedEventArgs.fault.currentLimited = PIR2bits.C1IF != 0 ? 1 : 0;
motorStoppedEventArgs.fault.encoderOverflow = PIR4bits.TMR1IF != 0 ? 1 : 0;
}
PIR2bits.C1IF = 0;
PIR4bits.TMR1IF = 0;
PIR7bits.CWG1IF = 0;
}
static void motorRunningStateMonitor(void *state)
{
static uint16_t previousEncoderValue;
static uint8_t encoderStaticCount;
uint16_t encoderValue = (uint16_t) TMR1L;
encoderValue |= ((uint16_t) TMR1H) << 8;
if (motorRunningState == MOTOR_RUNNING_STATE_STARTED && encoderValue == previousEncoderValue)
{
if (++encoderStaticCount == ENCODER_STATIC_COUNT_LIMIT)
{
motorStoppedEventArgs.actualCount = (int16_t) encoderValue;
if (motorStoppedEventArgs.requestedCount < 0)
{
motorStoppedEventArgs.actualCount = -motorStoppedEventArgs.actualCount;
if (motorStoppedEventArgs.actualCount > motorStoppedEventArgs.requestedCount && motorStoppedEventArgs.fault.all == 0)
motorStoppedEventArgs.fault.encoderTimeout = 1;
}
else
{
if (motorStoppedEventArgs.actualCount < motorStoppedEventArgs.requestedCount && motorStoppedEventArgs.fault.all == 0)
motorStoppedEventArgs.fault.encoderTimeout = 1;
}
eventPublish(MOTOR_STOPPED, &motorStoppedEventArgs);
motorRunningState = MOTOR_RUNNING_STATE_STOPPED;
CWG1AS0bits.SHUTDOWN = 0;
return;
}
}
else
{
if (motorRunningState == MOTOR_RUNNING_STATE_STARTING)
motorRunningState = MOTOR_RUNNING_STATE_STARTED;
encoderStaticCount = 0;
}
previousEncoderValue = encoderValue;
nearSchedulerAddOrUpdate(&motorRunningStateMonitorSchedule);
}
<file_sep>/src/firmware/tests/Platform/Event/EventHandler.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_EVENTHANDLER_H
#define __CLUCK2SESAME_TESTS_PLATFORM_EVENTHANDLER_H
#include "Platform/Event.h"
extern void eventHandler(const struct Event *event);
extern void anotherEventHandler(const struct Event *event);
#endif
<file_sep>/src/firmware/src/SunEvents.h
#ifndef __CLUCK2SESAME_SRC_SUNEVENTS_H
#define __CLUCK2SESAME_SRC_SUNEVENTS_H
#include "Platform/Event.h"
#include "Platform/Clock.h"
#define SUN_EVENTS_CHANGED ((EventType) 0x50)
struct SunEventsChanged
{
struct Time sunrise;
struct Time sunset;
};
extern void sunEventsInitialise(void);
#endif
<file_sep>/src/firmware/src/Door/DoorOnCloseScheduleActioned.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/NvmSettings.h"
#include "../Platform/Motor.h"
#include "../ApplicationNvmSettings.h"
#include "Door.h"
void doorOnCloseScheduleActioned(const struct Event *event)
{
switch (doorState.current)
{
case DoorState_Closed:
doorState.transition = DoorTransition_Unchanged;
break;
case DoorState_Opened:
motorEnable();
doorStartClosing(
DoorState_Closing,
DoorState_Closing_WaitingForEnabledMotor);
doorState.transition = DoorTransition_Close;
break;
case DoorState_Unknown:
motorEnable();
doorStartFindingBottom(
DoorState_FindBottom,
DoorState_FindBottom_WaitingForEnabledMotor);
default:
doorState.transition = DoorTransition_Close;
};
}
void doorStartClosing(
enum DoorState motorEnabledState,
enum DoorState motorDisabledState)
{
if (motorIsEnabled())
{
motorLimitIsNoLoad();
motorOn((motorEnabledState == DoorState_ManualClosing)
? -((int16_t) MANUAL_MOVEMENT_LIMIT)
: -((int16_t) nvmSettings.application.door.height));
doorState.current = motorEnabledState;
doorState.closed.loweredHeight = 0;
}
else
doorState.current = motorDisabledState;
}
<file_sep>/src/firmware/tests/SunEvents/TestSunEventsInitialise2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/Nvm.h"
#include "Mock_Clock.h"
#include "SunEvents.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
TEST_FILE("SunEvents/SunEventsInitialise.c")
TEST_FILE("SunEvents/SunEventsCalculate.c")
static void ensureEventHandlerDoesNotGetOmittedByTheCompiler(void);
static struct Event onDateChangedEvent;
static const struct EventSubscription *onDateChanged;
static void eventSubscribeStub(
const struct EventSubscription *subscription,
int numCalls)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == DATE_CHANGED)
{
onDateChanged = subscription;
onDateChangedEvent.type = subscription->type;
onDateChangedEvent.state = subscription->state;
onDateChangedEvent.args = (void *) 0;
}
}
void onBeforeTest(void)
{
eventSubscribe_StubWithCallback(&eventSubscribeStub);
onDateChanged = (const struct EventSubscription *) 0;
}
void onAfterTest(void)
{
}
void test_sunEventsInitialise_called_expectSubscriptionToDateChanged(void)
{
sunEventsInitialise();
ensureEventHandlerDoesNotGetOmittedByTheCompiler();
TEST_ASSERT_NOT_NULL(onDateChanged);
}
static void ensureEventHandlerDoesNotGetOmittedByTheCompiler(void)
{
static volatile uint8_t dummy = 0;
if (onDateChanged && dummy)
onDateChanged->handler(&onDateChangedEvent);
}
<file_sep>/src/firmware/tests/Platform/Battery/TestBatteryChargerGoodFlag.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Battery.h"
#include "BatteryFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Battery.c")
void onBeforeTest(void)
{
batteryFixtureSetUp();
}
void onAfterTest(void)
{
batteryFixtureTearDown();
}
void test_batteryChargerEnabled_eventWhenChargerGoodPinIsHighWhenOtherParametersAllowCharging_expectNoBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
stubChargerGoodPinHigh();
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
dispatchAllEvents();
TEST_ASSERT_NULL(batteryChargerEnabledEventArgs);
}
void test_chargerEnablePin_getWhenChargerGoodPinIsHighWhenOtherParametersAllowCharging_expectChargerEnablePinIsLow(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
stubChargerGoodPinHigh();
LATBbits.LATB3 = 1;
dispatchAllEvents();
TEST_ASSERT_FALSE(LATBbits.LATB3);
}
void test_batteryChargerEnabled_eventWhenChargerGoodPinTransitionsFromHighToLowWhenOtherParametersAllowCharging_expectBatteryChargerEnabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
stubChargerGoodPinHigh();
dispatchAllEvents();
batteryChargerEnabledEventArgs = (const struct BatteryChargerEnabled *) 0;
stubChargerGoodPinLow();
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerEnabledEventArgs);
}
void test_chargerEnablePin_getWhenChargerGoodPinIsLowWhenOtherParametersAllowCharging_expectChargerEnablePinIsHigh(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
stubChargerGoodPinHigh();
dispatchAllEvents();
stubChargerGoodPinLow();
LATBbits.LATB3 = 0;
dispatchAllEvents();
TEST_ASSERT_TRUE(LATBbits.LATB3);
}
void test_onWokenFromSleep_eventWhenIocInterruptFlagSet_expectOnlyChargerGoodPinFlagIsCleared(void)
{
batteryInitialise();
IOCBF = anyByteWithMaskSet(_IOCBF_IOCBF5_MASK);
uint8_t originalIocbf = IOCBF;
publishWokenFromSleep();
dispatchAllEvents();
TEST_ASSERT_EQUAL_HEX8(originalIocbf & ~_IOCBF_IOCBF5_MASK, IOCBF);
}
void test_onWokenFromSleep_eventWhenIocInterruptFlagIsNotSet_expectChargingStateIsStillReEvaluated(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
dispatchAllEvents();
stubChargerGoodPinHigh();
IOCBF = 0;
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) 0;
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerDisabledEventArgs);
}
void test_batteryChargerDisabled_eventWhenChargerGoodPinTransitionsFromLowToHighWhenOtherParametersAllowCharging_expectBatteryChargerDisabledEventIsPublished(void)
{
batteryInitialise();
stubAllParametersThatWillEnableCharging();
dispatchAllEvents();
stubChargerGoodPinHigh();
batteryChargerDisabledEventArgs = (const struct BatteryChargerDisabled *) 0;
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(batteryChargerDisabledEventArgs);
}
<file_sep>/src/firmware/src/Door/DoorInitialise.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/Event.h"
#include "../Platform/FarScheduler.h"
#include "../Platform/NvmSettings.h"
#include "../Platform/Motor.h"
#include "../ApplicationNvmSettings.h"
#include "../SunEvents.h"
#include "Door.h"
static void onDateOrNvmSettingsChanged(const struct Event *event);
static void onSunEventsChanged(const struct Event *event);
static struct FarSchedule openingSchedule =
{
.eventType = DOOR_OPEN_SCHEDULE_ACTIONED
};
static struct FarSchedule closingSchedule =
{
.eventType = DOOR_CLOSE_SCHEDULE_ACTIONED
};
struct DoorStateInternal doorState;
void doorInitialise(void)
{
doorState.current = DoorState_Unknown;
doorState.transition = DoorTransition_Unchanged;
static const struct EventSubscription onDateChangedSubscription =
{
.type = DATE_CHANGED,
.handler = &onDateOrNvmSettingsChanged,
.state = (void *) 0
};
eventSubscribe(&onDateChangedSubscription);
static const struct EventSubscription onNvmSettingsChangedSubscription =
{
.type = NVM_SETTINGS_CHANGED,
.handler = &onDateOrNvmSettingsChanged,
.state = (void *) 0
};
eventSubscribe(&onNvmSettingsChangedSubscription);
static const struct EventSubscription onSunEventsChangedSubscription =
{
.type = SUN_EVENTS_CHANGED,
.handler = &onSunEventsChanged,
.state = (void *) 0
};
eventSubscribe(&onSunEventsChangedSubscription);
static const struct EventSubscription onDoorOpenScheduleActionedSubscription =
{
.type = DOOR_OPEN_SCHEDULE_ACTIONED,
.handler = &doorOnOpenScheduleActioned,
.state = (void *) 0
};
eventSubscribe(&onDoorOpenScheduleActionedSubscription);
static const struct EventSubscription onDoorCloseScheduleActionedSubscription =
{
.type = DOOR_CLOSE_SCHEDULE_ACTIONED,
.handler = &doorOnCloseScheduleActioned,
.state = (void *) 0
};
eventSubscribe(&onDoorCloseScheduleActionedSubscription);
static const struct EventSubscription onMotorStoppedSubscription =
{
.type = MOTOR_STOPPED,
.handler = &doorOnMotorStopped,
.state = (void *) 0
};
eventSubscribe(&onMotorStoppedSubscription);
static const struct EventSubscription onMotorEnabledSubscription =
{
.type = MOTOR_ENABLED,
.handler = &doorOnMotorEnabled,
.state = (void *) 0
};
eventSubscribe(&onMotorEnabledSubscription);
}
static void onDateOrNvmSettingsChanged(const struct Event *event)
{
farSchedulerRemove(&openingSchedule);
farSchedulerRemove(&closingSchedule);
if (!nvmSettings.application.door.mode.isTimeDriven)
return;
openingSchedule.time.hour = nvmSettings.application.door.autoOpenTime.hour,
openingSchedule.time.minute = nvmSettings.application.door.autoOpenTime.minute;
farSchedulerAdd(&openingSchedule);
closingSchedule.time.hour = nvmSettings.application.door.autoCloseTime.hour,
closingSchedule.time.minute = nvmSettings.application.door.autoCloseTime.minute;
farSchedulerAdd(&closingSchedule);
}
static void onSunEventsChanged(const struct Event *event)
{
if (!nvmSettings.application.door.mode.isSunEventDriven)
return;
const struct SunEventsChanged *args = (const struct SunEventsChanged *) event->args;
// TODO: OFFSETS FROM nvmSettings.application.door.sunEvents NEED ADDING !
farSchedulerRemove(&openingSchedule);
openingSchedule.time.hour = args->sunrise.hour,
openingSchedule.time.minute = args->sunrise.minute;
farSchedulerAdd(&openingSchedule);
farSchedulerRemove(&closingSchedule);
closingSchedule.time.hour = args->sunset.hour,
closingSchedule.time.minute = args->sunset.minute;
farSchedulerAdd(&closingSchedule);
}
<file_sep>/src/firmware/tests/Door/DoorFixture.h
#ifndef __CLUCK2SESAME_TESTS_DOOR_DOORFIXTURE_H
#define __CLUCK2SESAME_TESTS_DOOR_DOORFIXTURE_H
#include "Platform/FarScheduler.h"
#include "Platform/Motor.h"
#include "SunEvents.h"
#define PULSES_PER_10CM 1138
#define PULSES_PER_1M 11380
#define PULSES_PER_2MM 23
extern void doorFixtureInitialise(void);
extern void doorFixtureShutdown(void);
extern void stubNvmSettingsForTimeDrivenMode(void);
extern void stubNvmSettingsForManuallyDrivenMode(void);
extern void stubNvmSettingsForSunEventDrivenMode(void);
extern void stubNvmSettingsForSunEventDrivenModeWithOffsets(
int8_t sunriseMinutes,
int8_t sunsetMinutes);
extern void stubNvmSettingsForUnspecifiedMode(void);
extern void stubAnySunEvents(struct SunEventsChanged *eventArgs);
extern void stubDoorWithFault(uint8_t flags);
extern void stubDoorWithState(
enum DoorState state,
enum DoorTransition transition);
extern void stubMotorIsEnabled(void);
extern void stubMotorIsDisabled(void);
extern void publishDateChanged(void);
extern void publishNvmSettingsChanged(void);
extern void publishSunEventsChanged(
const struct SunEventsChanged *eventArgs);
extern void publishDoorOpenScheduleActioned(void);
extern void publishDoorCloseScheduleActioned(void);
extern void publishDoorAbortedWithAnyFault(void);
extern void publishMotorStopped(const struct MotorStopped *eventArgs);
extern void publishMotorStoppedWithNoFaults(void);
extern void publishMotorStoppedWithNoFaultsOnRaising(void);
extern void publishMotorStoppedWithNoFaultsOnLowering(void);
extern void publishMotorStoppedWithFaults(void);
extern void publishMotorStoppedWithFaultsOnRaising(void);
extern void publishMotorStoppedWithFaultsOnLowering(void);
extern void publishMotorStoppedWithNonCurrentLimitFaultOnRaising(void);
extern void publishMotorEnabled(void);
extern void assertFarSchedulesAreEqualWithAnyNonNullArgs(
const struct FarSchedule *expected,
const struct FarSchedule *actual);
extern void mockOnDoorAborted(void);
extern void mockOnDoorOpened(void);
extern void mockOnDoorClosed(void);
extern void enterFindBottomState(void);
extern uint8_t anyUnknownMotorFault(void);
extern uint8_t farSchedulerAddCalls;
extern uint8_t farSchedulerAddSequence[8];
extern const struct FarSchedule *farSchedulerAddArgs[8];
extern uint8_t farSchedulerRemoveCalls;
extern uint8_t farSchedulerRemoveSequence[8];
extern const struct FarSchedule *farSchedulerRemoveArgs[8];
extern uint8_t onDoorAbortedCalls;
extern const struct DoorAborted *onDoorAbortedArgs[8];
extern uint8_t onDoorOpenedCalls;
extern const struct DoorOpened *onDoorOpenedArgs[8];
extern uint8_t onDoorClosedCalls;
extern const struct DoorClosed *onDoorClosedArgs[8];
extern uint8_t motorEnableCalls;
extern uint8_t motorEnableSequence;
extern uint8_t motorDisableCalls;
extern uint8_t motorDisableSequence;
extern uint8_t motorOnCalls;
extern uint8_t motorOnSequence;
extern int16_t motorOnArgs[8];
extern uint8_t motorOffCalls;
extern uint8_t motorOffSequence;
extern uint8_t motorLimitIsNoLoadCalls;
extern uint8_t motorLimitIsNoLoadSequence;
extern uint8_t motorLimitIsMaximumLoadCalls;
extern uint8_t motorLimitIsMaximumLoadSequence;
#endif
<file_sep>/src/firmware/tests/Platform/PowerManagement/TestPowerManagement.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_POWERMANAGEMENT_TESTPOWERMANAGEMENT_H
#define __CLUCK2SESAME_TESTS_PLATFORM_POWERMANAGEMENT_TESTPOWERMANAGEMENT_H
#include "Platform/Event.h"
#endif
<file_sep>/src/firmware/tests/Platform/Motor/__TestMotorShutdown1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
static void wokenFromSleepWithShutdown(void);
static void wokenFromSleepWithoutShutdown(void);
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_wokenFromSleep_onPublishedWithShutdownOfClockwiseTurn_expectCcpLimitIsSameValue(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
uint8_t originalCcpr1h = CCPR1H;
uint8_t originalCcpr1l = CCPR1L;
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1h, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1l, CCPR1L, "CCPR1L");
}
static void wokenFromSleepWithShutdown(void)
{
PIR7bits.CWG1IF = 1;
publishWokenFromSleep();
dispatchAllEvents();
}
void test_wokenFromSleep_onPublishedWithShutdown_expectAllPwmOutputsAreDisabled(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskClear(STEERING_MASK);
uint8_t originalCwg1strWithClearSteering = CWG1STR;
motorOn(anyEncoderCount());
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8(originalCwg1strWithClearSteering, CWG1STR);
}
void test_wokenFromSleep_onPublishedWithoutShutdown_expectAllPwmOutputsAreUnchanged(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskClear(STEERING_MASK);
motorOn(anyEncoderCount());
uint8_t originalCwg1str = CWG1STR;
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 0;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(originalCwg1str, CWG1STR);
}
static void wokenFromSleepWithoutShutdown(void)
{
PIR7bits.CWG1IF = 0;
publishWokenFromSleep();
dispatchAllEvents();
}
void test_wokenFromSleep_onPublishedWithShutdown_expectShutdownInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR7 = anyByteWithMaskSet(_PIR7_CWG1IF_MASK);
uint8_t originalPir7 = PIR7;
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8(originalPir7 & ~_PIR7_CWG1IF_MASK, PIR7);
}
void test_wokenFromSleep_onPublishedWithShutdownWhenMotorIsOff_expectMotorStoppedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStoppedCalls);
}
void test_wokenFromSleep_onPublishedWithoutShutdown_expectMotorStoppedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 0;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStoppedCalls);
}
void test_wokenFromSleep_onPublishedWithoutShutdownButEncoderOverflowed_expectMotorStoppedEventIsPublished(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
PIR2bits.C1IF = 0;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(1, onMotorStoppedCalls);
}
void test_wokenFromSleep_onPublishedWithoutShutdownButCurrentLimited_expectMotorStoppedEventIsPublished(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 1;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(1, onMotorStoppedCalls);
}
void test_wokenFromSleep_onPublishedWithShutdown_expectMotorStoppedEventIsPublishedWithSameRequestedCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyEncoderCount();
motorOn(count);
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.requestedCount, "Count");
}
void test_wokenFromSleep_onPublishedWithShutdownWhenTurningClockwise_expectMotorStoppedEventIsPublishedWithTmr1AsActualCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyClockwiseCount();
motorOn(count);
TMR1H = (uint8_t) ((count >> 8) & 0xff);
TMR1L = (uint8_t) ((count >> 0) & 0xff);
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.actualCount, "Count");
}
void test_wokenFromSleep_onPublishedWithShutdownWhenTurningAntiClockwise_expectMotorStoppedEventIsPublishedWithTmr1AsActualCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyAntiClockwiseCount();
motorOn(count);
int16_t negatedCount = -count;
TMR1H = (uint8_t) ((negatedCount >> 8) & 0xff);
TMR1L = (uint8_t) ((negatedCount >> 0) & 0xff);
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.actualCount, "Count");
}
<file_sep>/src/schematics/Plots/seeed/mkseeed.sh
#!/bin/sh
PROJECT="Cluck2Sesame";
PLOT_REPORT="../${PROJECT} (Plot Report).txt";
PLOT_DIR="..";
ZIP_DIR="${PROJECT}";
ZIP_FILE="${PROJECT}.zip";
if [[ -d ${ZIP_DIR} ]]; then
rm ${ZIP_DIR}/*;
else
mkdir ${ZIP_DIR};
fi;
if [[ -a ${ZIP_FILE} ]]; then
rm ${ZIP_FILE};
fi;
cp "${PLOT_DIR}/${PROJECT} - Board Outline.gbr" "${ZIP_DIR}/Board Outline.GM1";
cp "${PLOT_DIR}/${PROJECT} - Bottom Copper.gbr" "${ZIP_DIR}/Bottom Layer.GBL";
cp "${PLOT_DIR}/${PROJECT} - Bottom Solder Mask.gbr" "${ZIP_DIR}/Bottom Solder Mask.GBS";
cp "${PLOT_DIR}/${PROJECT} - Bottom Paste Mask.gbr" "${ZIP_DIR}/Bottom Paste Mask.GBP";
cp "${PLOT_DIR}/${PROJECT} - Bottom Silkscreen.gbr" "${ZIP_DIR}/Bottom Overlay.GBO";
cp "${PLOT_DIR}/${PROJECT} - Drill Data - [Through Hole].drl" "${ZIP_DIR}/Drill Drawing.NC";
cp "${PLOT_DIR}/${PROJECT} - Drill Data - [Through Hole] (Unplated).drl" "${ZIP_DIR}/Drill Drawing Unplated.NC";
cp "${PLOT_DIR}/${PROJECT} - Top Copper.gbr" "${ZIP_DIR}/Top Layer.GTL";
cp "${PLOT_DIR}/${PROJECT} - Top Solder Mask.gbr" "${ZIP_DIR}/Top Solder Mask.GTS";
cp "${PLOT_DIR}/${PROJECT} - Top Silkscreen.gbr" "${ZIP_DIR}/Top Overlay.GTO";
cp "README.txt" "${ZIP_DIR}/README.TXT";
cp "${PLOT_REPORT}" "${ZIP_DIR}/DesignSpark Plot Report.TXT";
cp "${PLOT_DIR}/../Cluck2Sesame (Component Placement).csv" "${ZIP_DIR}/Component Placement.csv";
cp "BOM.xlsx" "${ZIP_DIR}";
zip -9 -r "${ZIP_FILE}" "${ZIP_DIR}";
echo;
echo "*** NOTE: MAKE SURE UNPLATED HOLES ARE CORRECT (PROBABLY EMPTY)";
<file_sep>/src/firmware/tests/Platform/Lcd/TestLcdConfigure.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Lcd.h"
#include "FakeLcd.h"
#include "LcdFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Poll.c")
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/NearScheduler.c")
TEST_FILE("Platform/PowerManagement.c")
TEST_FILE("Platform/PwmTimer.c")
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
TEST_FILE("Platform/Lcd/LcdInitialise.c")
TEST_FILE("Platform/Lcd/LcdEnableDisable.c")
TEST_FILE("Platform/Lcd/LcdConfigure.c")
TEST_FILE("Platform/Lcd/LcdWrite.c")
extern void poll(void);
void onBeforeTest(void)
{
lcdFixtureInitialise();
}
void onAfterTest(void)
{
lcdFixtureShutdown();
}
void test_lcdConfigure_called_expectFirstByteSentToLcdIsFunctionSetForByteMode(void)
{
lcdEnable();
while (!fakeLcdIsSessionInvalid && fakeLcdData == 0)
poll();
TEST_ASSERT_FALSE_MESSAGE(fakeLcdRs, "RS");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0b00110000, fakeLcdData, "DATA");
}
void test_lcdConfigure_called_expectLcdIsConfiguredInNybbleMode(void)
{
enableLcdAndWaitUntilDone();
TEST_ASSERT_TRUE(fakeLcdIsNybbleMode);
}
void test_lcdConfigure_called_expectLcdContrastPwmIsEnabled(void)
{
enableLcdAndWaitUntilDone();
TEST_ASSERT_TRUE(PWM5CONbits.PWM5EN);
}
void test_lcdConfigure_called_expectFunctionSetForTwoLinesAnd5x8Font(void)
{
enableLcdAndWaitUntilDone();
fakeLcdAssertFunctionRegister(
LCD_CMD_FUNCTION_TWOLINES | LCD_CMD_FUNCTION_FONT5X8);
}
void test_lcdConfigure_called_expectDisplayIsCleared(void)
{
enableLcdAndWaitUntilDone();
for (uint8_t i = 0; i < 32; i++)
{
TEST_ASSERT_EQUAL_HEX8(' ', fakeLcdDram[i]);
}
}
void test_lcdConfigure_called_expectDdramAddressIsZero(void)
{
enableLcdAndWaitUntilDone();
fakeLcdAssertDdramAddressRegisterIs(0);
}
void test_lcdConfigure_called_expectEntryModeSetForIncrementingAddressesAndNoShifting(void)
{
enableLcdAndWaitUntilDone();
fakeLcdAssertEntryModeRegister(
LCD_CMD_ENTRYMODE_INCREMENT | LCD_CMD_ENTRYMODE_NOSHIFT);
}
void test_lcdConfigure_called_expectDisplayIsOnWithCursorAndBlinkingBothOff(void)
{
enableLcdAndWaitUntilDone();
fakeLcdAssertDisplayRegister(LCD_CMD_DISPLAY_ON);
}
<file_sep>/src/firmware/src/Platform/Motor/MotorEnableDisable.c
#include <xc.h>
#include <stdint.h>
#include "../Event.h"
#include "../VoltageRegulator.h"
#include "../PwmTimer.h"
#include "Motor.h"
void motorEnable(void)
{
if (motorState.enableCount++ != 0)
return;
voltageRegulatorEnable();
pwmTimerEnable();
if (voltageRegulatorIsEnabled())
{
eventPublish(MOTOR_ENABLED, &eventEmptyArgs);
motorState.flags.isFullyEnabled = 1;
}
}
void motorDisable(void)
{
if (motorState.enableCount == 0)
return;
if (--motorState.enableCount == 0)
{
eventPublish(MOTOR_DISABLED, &eventEmptyArgs);
motorState.flags.isFullyEnabled = 0;
pwmTimerDisable();
voltageRegulatorDisable();
}
}
uint8_t motorIsEnabled(void)
{
return motorState.flags.isFullyEnabled != 0;
}
<file_sep>/src/firmware/tests/TestNvmSettings.c
#include <xc.h>
#include <unity.h>
#include "Platform/NvmSettings.h"
#include "Fixture.h"
TEST_FILE("Platform/NvmSettings.c")
void onBeforeTest(void)
{
}
void onAfterTest(void)
{
}
void test_nvmSettings_getLcdContrast_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0x65, nvmSettings.platform.lcd.contrast);
}
void test_nvmSettings_getLcdBacklightBrightness_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0x80, nvmSettings.platform.lcd.backlightBrightness);
}
void test_nvmSettings_getMotorCurrentLimitNoLoad_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0x07, nvmSettings.platform.motor.currentLimitNoLoad);
}
void test_nvmSettings_getMotorCurrentLimitMaximumLoad_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0x10, nvmSettings.platform.motor.currentLimitMaximumLoad);
}
void test_nvmSettings_getIsCalibrationRequired_expectTrue(void)
{
TEST_ASSERT_TRUE(nvmSettings.platform.flags.bits.isCalibrationRequired);
}
void test_nvmSettings_getLatitudeOffset_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0, nvmSettings.application.location.latitudeOffset);
}
void test_nvmSettings_getLongitudeOffset_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(0, nvmSettings.application.location.longitudeOffset);
}
void test_nvmSettings_getDoorAutoOpenTime_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.autoOpenTime.hour,
"Hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.autoOpenTime.minute,
"Minute");
}
void test_nvmSettings_getDoorAutoCloseTime_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.autoCloseTime.hour,
"Hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.autoCloseTime.minute,
"Minute");
}
void test_nvmSettings_getSunEventOffsets_expectDefaultValues(void)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.sunEvents.sunriseOffsetMinutes,
"Sunrise");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
nvmSettings.application.door.sunEvents.sunsetOffsetMinutes,
"Sunset");
}
void test_nvmSettings_getDoorHeight_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT16(0, nvmSettings.application.door.height);
}
void test_nvmSettings_getScreenTimeoutSeconds_expectDefaultValue(void)
{
TEST_ASSERT_EQUAL_UINT8(20, nvmSettings.application.ui.screenTimeoutSeconds);
}
<file_sep>/src/firmware/src/Platform/Event.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_EVENT_H
#define __CLUCK2SESAME_SRC_PLATFORM_EVENT_H
#include <stdint.h>
#define EMPTY_EVENT_ARGS uint8_t emptiness;
typedef uint8_t EventType;
struct Event
{
EventType type;
void *state;
const void *args;
};
typedef void (*EventHandler)(const struct Event *event);
struct EventSubscription
{
EventType type;
EventHandler handler;
void *state;
};
extern const struct Event eventEmptyArgs;
extern void eventInitialise(void);
extern void eventSubscribe(const struct EventSubscription *subscription);
extern void eventUnsubscribe(const struct EventSubscription *subscription);
extern void eventPublish(EventType type, const void *args);
extern int8_t eventDispatchNext(void);
#endif
<file_sep>/src/firmware/src/Door/DoorManualOverride.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/Motor.h"
#include "Door.h"
void doorManualStartOpening(void)
{
motorEnable();
doorStartOpening(
DoorState_ManualOpening,
DoorState_ManualOpening_WaitingForEnabledMotor);
// TODO: WHAT IF THE MOTOR IS ALREADY TURNING AS PART OF ANOTHER STATE ??? MAYBE IN THE MIDDLE OF AN OPEN OR CLOSE ? REVERSING ?
// TODO: WHAT IF THE MOTOR IS ALREADY TURNING AS PART OF A MANUAL STATE (IE. QUICK SUCCESSIVE BUTTON PRESSES) ?
// TODO: DO NOT MODIFY 'doorState.transition' SINCE THIS WILL BE UPDATED BY THE OPEN / CLOSE SCHEDULE, THEN AT LEAST IT WILL WORK PROPERLY WHEN WE SWITCH BACK FROM MANUAL CONTROL...
}
void doorManualStartClosing(void)
{
// TODO: ALONG SIMILAR LINES AS THE MANUAL OPEN...
motorEnable();
doorStartClosing(
DoorState_ManualClosing,
DoorState_ManualClosing_WaitingForEnabledMotor);
}
void doorManualStop(void)
{
motorOff();
}
<file_sep>/src/firmware/tests/Door/DoorFindBottomFixture.c
#include <xc.h>
#include <stdint.h>
#include "Platform/Event.h"
#include "Motor.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
const struct MotorStopped raisingStoppedImmediately =
{
.actualCount = 0,
.requestedCount = 1234,
.fault = { .currentLimited = 1 }
};
const struct MotorStopped raisingStoppedAtThreshold =
{
.requestedCount = 1234,
.actualCount = PULSES_PER_2MM,
.fault = { .currentLimited = 1 }
};
const struct MotorStopped raisingStoppedJustAfterThreshold =
{
.requestedCount = 1234,
.actualCount = PULSES_PER_2MM + 1,
.fault = { .currentLimited = 1 }
};
struct MotorStopped raisingStoppedAfterThreshold =
{
.requestedCount = 1234,
.actualCount = -1,
.fault = { .currentLimited = 1 }
};
void onBeforeTest(void)
{
doorFixtureInitialise();
raisingStoppedAfterThreshold.actualCount =
PULSES_PER_2MM + 1 + (int16_t) anyWordLessThan(10000);
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
<file_sep>/src/firmware/src/Platform/CalibrationMode.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_CALIBRATIONMODE_H
#define __CLUCK2SESAME_SRC_PLATFORM_CALIBRATIONMODE_H
#define CALIBRATIONMODE_CMD_REFCLK 'C'
#define CALIBRATIONMODE_CMD_READ 'R'
#define CALIBRATIONMODE_CMD_SAMPLEPARAMETERS 'S'
#define CALIBRATIONMODE_CMD_EOL '\n'
#define CALIBRATIONMODE_REPLY_ERROR 'E'
#define CALIBRATIONMODE_REPLY_RESULT '='
extern void calibrationModeInitialise(void);
#endif
<file_sep>/src/firmware/tests/Platform/FarScheduler/TestFarScheduler.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Mock_Clock.h"
#include "Platform/FarScheduler.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/FarScheduler.c")
static void onScheduled(const struct Event *event);
static void stubScheduleFor(
struct FarSchedule *schedule,
uint8_t hour,
uint8_t minute);
static struct EventSubscription onScheduledSubscription;
static uint8_t onScheduledCalls;
static const void *onScheduledArgs;
void onBeforeTest(void)
{
eventInitialise();
farSchedulerInitialise();
onScheduledCalls = 0;
onScheduledArgs = (void *) 0;
onScheduledSubscription.type = anyByteWithMaskSet(0x70);
onScheduledSubscription.handler = &onScheduled;
onScheduledSubscription.state = (void *) 0;
eventSubscribe(&onScheduledSubscription);
}
static void onScheduled(const struct Event *event)
{
onScheduledArgs = event->args;
onScheduledCalls++;
}
void onAfterTest(void)
{
}
void test_timeChanged_onPublishedWithMatchingScheduleTimeButAfterDateChanged_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, 4, 5);
farSchedulerAdd(&schedule);
eventPublish(DATE_CHANGED, &dateChangedArgs);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onScheduledCalls);
}
static void stubScheduleFor(
struct FarSchedule *schedule,
uint8_t hour,
uint8_t minute)
{
schedule->time.hour = hour;
schedule->time.minute = minute;
schedule->eventType = onScheduledSubscription.type;
schedule->eventArgs = (void *) (int) anyWord();
}
void test_timeChanged_onPublishedWithMatchingScheduleTime_expectScheduleIsActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, 4, 5);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onScheduledCalls, "Calls");
TEST_ASSERT_EQUAL_PTR_MESSAGE(schedule.eventArgs, onScheduledArgs, "Args");
}
void test_timeChanged_onPublishedWithMatchingScheduleTimeWhenEventArgsIsNull_expectScheduleIsActionedWithEmptyEventArgs(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, 4, 5);
schedule.eventArgs = (struct Event *) 0;
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onScheduledCalls, "Calls");
TEST_ASSERT_EQUAL_PTR_MESSAGE(&eventEmptyArgs, onScheduledArgs, "Args");
}
void test_timeChanged_onPublishedWithNonMatchingHourInTheFuture_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, now.hour + 1, now.minute);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onScheduledCalls, "Calls");
}
void test_timeChanged_onPublishedWithNonMatchingHourInThePast_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, now.hour - 1, now.minute);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onScheduledCalls, "Calls");
}
void test_timeChanged_onPublishedWithNonMatchingMinuteInThePast_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, now.hour, now.minute - 1);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onScheduledCalls, "Calls");
}
void test_timeChanged_onPublishedWithNonMatchingMinuteInTheFuture_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, now.hour, now.minute + 1);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onScheduledCalls, "Calls");
}
void test_timeChanged_onPublishedWhenMoreThanOneMatchingSchedule_expectAllSchedulesAreActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, now.hour, now.minute);
farSchedulerAdd(&schedule);
farSchedulerAdd(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(2, onScheduledCalls, "Calls");
}
void test_farSchedulerAdd_calledWhenNoMoreSpace_expectNoSchedulesAreOverwritten(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
static struct FarSchedule schedules[33];
for (uint8_t i = 0; i < 33; i++)
{
stubScheduleFor(&schedules[i], now.hour, now.minute + i);
farSchedulerAdd(&schedules[i]);
}
for (uint8_t i = 0; i < 32; i++)
{
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
now.minute++;
}
TEST_ASSERT_EQUAL_UINT8_MESSAGE(32, onScheduledCalls, "(1)");
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(32, onScheduledCalls, "(2)");
}
void test_farSchedulerAdd_calledWhenNoMoreSpaceButSomeSchedulesHaveBeenActioned_expectActionedSchedulesAreOverwritten(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
static struct FarSchedule schedules[33];
stubScheduleFor(&schedules[32], now.hour, now.minute);
farSchedulerAdd(&schedules[32]);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
now.minute++;
for (uint8_t i = 0; i < 32; i++)
{
stubScheduleFor(&schedules[i], now.hour, now.minute + i);
farSchedulerAdd(&schedules[i]);
}
for (uint8_t i = 0; i < 32; i++)
{
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
now.minute++;
}
TEST_ASSERT_EQUAL_UINT8(33, onScheduledCalls);
}
void test_farSchedulerRemove_called_expectScheduleIsNotActioned(void)
{
static const struct DateWithFlags today = { .year = 1, .month = 2, .day = 3 };
static const struct DateChanged dateChangedArgs = { .today = &today };
static const struct Time now = { .hour = 4, .minute = 5 };
static const struct TimeChanged timeChangedArgs = { .now = &now };
struct FarSchedule schedule;
stubScheduleFor(&schedule, 4, 5);
farSchedulerAdd(&schedule);
farSchedulerRemove(&schedule);
eventPublish(TIME_CHANGED, &timeChangedArgs);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onScheduledCalls);
}
<file_sep>/src/firmware/src/Platform/Motor/Motor.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_MOTOR_MOTOR_H
#define __CLUCK2SESAME_SRC_PLATFORM_MOTOR_MOTOR_H
#include "../Motor.h"
#define CWG1STR_STEERING_MASK ( \
_CWG1STR_STRA_MASK | \
_CWG1STR_STRB_MASK | \
_CWG1STR_STRC_MASK | \
_CWG1STR_STRD_MASK)
struct MotorState
{
uint8_t enableCount;
union
{
uint8_t all;
struct
{
unsigned int isFullyEnabled : 1;
};
} flags;
};
extern struct MotorState motorState;
#endif
<file_sep>/src/firmware/src/Platform/Initialise.c
#include <xc.h>
#include "Main.h"
#include "Event.h"
#include "Clock.h"
#include "NearScheduler.h"
#include "FarScheduler.h"
#include "PowerManagement.h"
#include "VoltageRegulator.h"
#include "Temperature.h"
#include "Battery.h"
#include "PwmTimer.h"
#include "Adc.h"
#include "Lcd.h"
#include "Motor.h"
#include "PeriodicMonitor.h"
#include "Buttons.h"
#include "CalibrationMode.h"
void initialise(void)
{
eventInitialise();
powerManagementInitialise();
clockInitialise();
nearSchedulerInitialise();
farSchedulerInitialise();
voltageRegulatorInitialise();
temperatureInitialise();
batteryInitialise();
pwmTimerInitialise();
adcInitialise();
lcdInitialise();
motorInitialise();
periodicMonitorInitialise();
buttonsInitialise();
calibrationModeInitialise();
applicationInitialise();
eventPublish(SYSTEM_INITIALISED, &eventEmptyArgs);
}
<file_sep>/src/firmware/tests/Platform/Battery/BatteryFixture.h
#ifndef __CLUCK2SESAME_TESTS_BATTERY_BATTERYFIXTURE_H
#define __CLUCK2SESAME_TESTS_BATTERY_BATTERYFIXTURE_H
#include <stdint.h>
#define FVR_IDEAL_MV 2048
#define FVR_TOLERANCE_MV 20
#define FVR_MINIMUM_VALID_SAMPLE 2768
#define FVR_MAXIMUM_VALID_SAMPLE 6672
extern void batteryFixtureSetUp(void);
extern void batteryFixtureTearDown(void);
extern uint16_t stubAnyDiaFvra2xMillivolts(void);
extern void stubDiaFvra2xMillivolts(uint16_t millivolts);
extern void stubAllParametersThatWillEnableCharging(void);
extern void stubChargerGoodPinLow(void);
extern void stubChargerGoodPinHigh(void);
extern void stubTemperatureWithinChargingRange(void);
extern void stubTemperatureOf(int16_t celsius);
extern void stubBatteryVoltageWithinChargingRange(void);
extern void stubBatteryVoltageOf(uint16_t millivolts);
extern const struct BatteryChargerEnabled *batteryChargerEnabledEventArgs;
extern const struct BatteryChargerDisabled *batteryChargerDisabledEventArgs;
#endif
<file_sep>/src/firmware/src/Platform/Adc.c
#include <xc.h>
#include <stdint.h>
#include "Adc.h"
#define ADCON1_RIGHT_JUSTIFIED _ADCON1_ADFM_MASK
#define ADCON1_TAD_2US (0b110 << _ADCON1_ADCS_POSITION)
#define ADCON1_VREF_IS_FVR (0b11 << _ADCON1_ADPREF_POSITION)
#define ADCON1_VREF_IS_VDD (0b00 << _ADCON1_ADPREF_POSITION)
void adcInitialise(void)
{
}
void adcSample(struct AdcSample *sample)
{
if (!sample)
return;
PMD2bits.ADCMD = 0;
ADCON0 = sample->channel;
ADCON1 = ADCON1_RIGHT_JUSTIFIED | ADCON1_TAD_2US | (sample->flags.vrefIsFvr ? ADCON1_VREF_IS_FVR : ADCON1_VREF_IS_VDD);
ADACT = 0;
for (uint8_t i = 0; i < 8 * (sample->flags.acquisitionTimeMultiple + 1); i++)
asm("nop");
sample->result = 0;
ADCON0bits.GOnDONE = 1;
for (uint8_t i = 0; i < sample->count; i++)
{
while (ADCON0bits.GOnDONE)
;;
ADCON0bits.GOnDONE = 1;
sample->result += ADRES;
}
PMD2bits.ADCMD = 1;
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorTimer1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD1bits.TMR1MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1IsEnabled(void)
{
T1CON = anyByteWithMaskClear(_T1CON_ON_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(T1CONbits.ON);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1PrescalerIs1To1(void)
{
T1CON = anyByte();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, T1CONbits.CKPS);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1IsSynchronousToAllowGlitchlessCompare(void)
{
T1CON = anyByteWithMaskSet(_T1CON_nSYNC_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(T1CONbits.nSYNC);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1ReadsAre16BitsBuffered(void)
{
T1CON = anyByteWithMaskClear(_T1CON_RD16_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(T1CONbits.RD16);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1CounterIsClear(void)
{
TMR1H = anyByteExcept(0);
TMR1L = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, TMR1L, "TMR1L");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, TMR1H, "TMR1H");
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1GatingIsDisabled(void)
{
T1GCON = anyByteWithMaskSet(_T1GCON_GE_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(T1GCONbits.GE);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1SourceIsEncoderPin(void)
{
T1CLK = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, T1CLK);
}
void test_voltageRegulatorEnabled_onPublished_expectEncoderAIsMappedToRc3(void)
{
T1CKIPPS = anyByteExcept(0x13);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0x13, T1CKIPPS);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1InterruptFlagIsCleared(void)
{
PIR4 = anyByteWithMaskSet(_PIR4_TMR1IF_MASK);
uint8_t originalPir4 = PIR4;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPir4 & ~_PIR4_TMR1IF_MASK, PIR4);
}
void test_voltageRegulatorEnabled_onPublished_expectTimer1InterruptWakesDeviceFromSleep(void)
{
PIE4 = anyByteWithMaskClear(_PIE4_TMR1IE_MASK);
uint8_t originalPie4 = PIE4;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPie4 | _PIE4_TMR1IE_MASK, PIE4);
}
<file_sep>/src/firmware/tests/Platform/TestPoll.c
#include <xc.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Mock_Event.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
TEST_FILE("Platform/Poll.c")
static int numberOfEventPublishCalls;
const struct Event eventEmptyArgs = { };
static void eventPublishThatIncrementsCounter(
EventType type,
const void *args,
int numCalls)
{
numberOfEventPublishCalls++;
}
void onBeforeTest(void)
{
numberOfEventPublishCalls = 0;
}
void onAfterTest(void)
{
}
void test_poll_calledWhenNextEventDispatched_expectAllEventsDispatchedEventIsNotPublished(void)
{
eventDispatchNext_ExpectAndReturn(1);
eventPublish_StubWithCallback(eventPublishThatIncrementsCounter);
poll();
TEST_ASSERT_EQUAL_INT(0, numberOfEventPublishCalls);
}
void test_poll_calledWhenNextEventNotDispatched_expectAllEventsDispatchedEventIsPublished(void)
{
static const struct AllEventsDispatched emptyArgs = { };
eventDispatchNext_ExpectAndReturn(0);
eventPublish_Expect(ALL_EVENTS_DISPATCHED, &emptyArgs);
poll();
}
<file_sep>/src/firmware/tests/Platform/Clock/TestClockInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
void onBeforeTest(void)
{
eventInitialise();
}
void onAfterTest(void)
{
}
void test_clockInitialise_called_expectTimer0ModuleIsEnabled(void)
{
PMD1 = anyByteWithMaskSet(_PMD1_TMR0MD_MASK);
uint8_t originalPmd1 = PMD1;
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPmd1 & ~_PMD1_TMR0MD_MASK, PMD1);
}
void test_clockInitialise_called_expectOscillatorIsEnabled(void)
{
OSCEN = anyByteWithMaskClear(_OSCEN_SOSCEN_MASK);
uint8_t originalOscen = OSCEN;
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(OSCEN | _OSCEN_SOSCEN_MASK, OSCEN);
}
void test_clockInitialise_called_expectOscillatorIsReadyToBeUsed(void)
{
clockInitialise();
TEST_ASSERT_TRUE(OSCSTATbits.SOR);
}
void test_clockInitialise_called_expectClockSourceIsOscillator(void)
{
T0CON1 = anyByte();
clockInitialise();
int source = (T0CON1 & _T0CON1_T0CS_MASK) >> _T0CON1_T0CS_POSITION;
TEST_ASSERT_EQUAL_INT(0b110, source & 0b111);
}
void test_clockInitialise_called_expectTimerIsAsynchronous(void)
{
T0CON1 = anyByteWithMaskClear(_T0CON1_T0ASYNC_MASK);
clockInitialise();
TEST_ASSERT_TRUE(T0CON1bits.T0ASYNC);
}
void test_clockInitialise_called_expectTimerPrescalerIs32768ToProduce1SecondTicks(void)
{
T0CON1 = anyByte();
clockInitialise();
int prescale = (T0CON1 & _T0CON1_T0CKPS_MASK) >> _T0CON1_T0CKPS_POSITION;
TEST_ASSERT_EQUAL_INT(0b1111, prescale & 0b1111);
}
void test_clockInitialise_called_expectTimerIsEnabled(void)
{
T0CON0 = anyByteWithMaskClear(_T0CON0_T0EN_MASK);
clockInitialise();
TEST_ASSERT_TRUE(T0CON0bits.T0EN);
}
void test_clockInitialise_called_expectTimerIsConfiguredAs8BitMode(void)
{
T0CON0 = anyByteWithMaskSet(_T0CON0_T016BIT_MASK);
clockInitialise();
TEST_ASSERT_FALSE(T0CON0bits.T016BIT);
}
void test_clockInitialise_called_expectTimerPostscalerIs1Second(void)
{
T0CON0 = anyByte();
clockInitialise();
int postscale = (T0CON0 & _T0CON0_T0OUTPS_MASK) >> _T0CON0_T0OUTPS_POSITION;
TEST_ASSERT_EQUAL_INT(0, postscale & 0b1111);
}
void test_clockInitialise_called_expectTimerInterruptFlagIsClear(void)
{
PIR0 = anyByteWithMaskSet(_PIR0_TMR0IF_MASK);
uint8_t originalPir0 = PIR0;
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPir0 & ~_PIR0_TMR0IF_MASK, PIR0);
}
void test_clockInitialise_called_expectTimerCanWakeDeviceFromSleep(void)
{
PIE0 = anyByteWithMaskClear(_PIE0_TMR0IE_MASK);
uint8_t originalPie0 = PIE0;
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(originalPie0 | _PIE0_TMR0IE_MASK, PIE0);
}
void test_clockInitialise_called_expectTimerIsZero(void)
{
TMR0L = anyByteExcept(0);
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(0, TMR0L);
}
void test_clockInitialise_called_expectTimerComparisonIs60Seconds(void)
{
TMR0H = anyByteExcept(59);
clockInitialise();
TEST_ASSERT_EQUAL_UINT8(59, TMR0H);
}
void test_clockInitialise_called_expectNowDateIsInitialisedAsEpoch(void)
{
clockInitialise();
struct DateAndTimeGet now =
{
.date =
{
.year = anyByte(),
.month = anyByte(),
.day = anyByte(),
.dayOfYear = anyWord(),
.flags = { .all = anyByte() }
}
};
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.date.year, "Year");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.month, "Month");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, now.date.day, "Day");
TEST_ASSERT_EQUAL_UINT16_MESSAGE(0, now.date.dayOfYear, "Day-of-Year");
TEST_ASSERT_TRUE_MESSAGE(now.date.flags.isLeapYear, "Leap");
TEST_ASSERT_FALSE_MESSAGE(now.date.flags.isDaylightSavings, "DST");
}
void test_clockInitialise_called_expectNowTimeIsInitialisedAsMidnight(void)
{
clockInitialise();
struct DateAndTimeGet now =
{
.time =
{
.hour = anyByte(),
.minute = anyByte(),
.second = anyByte()
}
};
clockGetNowGmt(&now);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.hour, "Hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.minute, "Minute");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, now.time.second, "Second");
}
<file_sep>/src/firmware/src/Platform/Clock.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_CLOCK_H
#define __CLUCK2SESAME_SRC_PLATFORM_CLOCK_H
#include <stdint.h>
#include "Event.h"
struct DateWithFlags;
struct Time;
#define DATE_CHANGED ((EventType) 0x10)
struct DateChanged
{
const struct DateWithFlags *today;
};
#define TIME_CHANGED ((EventType) 0x11)
struct TimeChanged
{
const struct Time *now;
};
struct Date
{
uint8_t day;
uint8_t month;
uint8_t year;
};
struct DateWithFlags
{
uint8_t day;
uint8_t month;
uint8_t year;
uint16_t dayOfYear;
union
{
uint8_t all;
struct
{
unsigned int isLeapYear : 1;
unsigned int isDaylightSavings : 1;
};
} flags;
};
struct Time
{
uint8_t second;
uint8_t minute;
uint8_t hour;
};
struct DateAndTimeSet
{
struct Time time;
struct Date date;
};
struct DateAndTimeGet
{
struct Time time;
struct DateWithFlags date;
};
extern void clockInitialise(void);
extern void clockGetNowGmt(struct DateAndTimeGet *now);
extern void clockSetNowGmt(const struct DateAndTimeSet *now);
extern uint8_t clockDaysInMonth(uint8_t month, uint8_t year);
#define clockIsLeapYear(year) (((year) & 3) == 0) /* Simplified version works for all dates 2000-2100 */
#endif
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorPwm.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD3bits.PWM4MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectPwmIsEnabled(void)
{
PWM4CON = anyByteWithMaskClear(_PWM4CON_PWM4EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(PWM4CONbits.PWM4EN);
}
void test_voltageRegulatorEnabled_onPublished_expectPwmOutputIsNotInverted(void)
{
PWM4CON = anyByteWithMaskSet(_PWM4CON_PWM4POL_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(PWM4CONbits.PWM4POL);
}
void test_voltageRegulatorEnabled_onPublished_expectPwmDutyCycleIsZero(void)
{
PWM4DCH = anyByteExcept(0);
PWM4DCL = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCH, "PWM4DCH");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, PWM4DCL, "PWM4DCL");
}
<file_sep>/src/firmware/src/Ui/UiMenuScreen.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "Ui.h"
#define OK_NEXT_LINE " OK >NEXT"
#define OK_POS UI_CURSOR_AT(0, 1)
#define NEXT_POS UI_CURSOR_AT(11, 1)
static void uiMenuScreenOptionSelected(void);
void uiMenuSettingsScreenmenu(void)
{
uiState.menu.itemText = "Change Settings ";
uiState.menu.onNext = &uiDateAndTimeStatusScreen;
uiState.menu.onOk = &UI_FIRST_SETTINGS_SCREEN;
uiMenuScreen();
}
void uiMenuScreen(void)
{
if (uiState.menu.itemText)
{
memcpy(
&uiState.screen[0],
uiState.menu.itemText,
UI_SCREEN_WIDTH + 1);
}
memcpy(
&uiState.screen[UI_SCREEN_WIDTH + 1],
OK_NEXT_LINE,
UI_SCREEN_WIDTH + 1);
uiState.input.menu.options.cursorPositions[0] = OK_POS;
uiState.input.menu.options.cursorPositions[1] = NEXT_POS;
uiState.input.menu.options.cursorPositions[2] = UI_NO_CURSOR;
uiState.input.cursorPosition = NEXT_POS;
uiState.input.selectedOptionIndex = 1;
uiState.input.buttons = &uiInputIsOptions;
uiState.input.onPreEnter = 0;
uiState.input.onEnter = &uiMenuScreenOptionSelected;
uiScreenBlit();
}
static void uiMenuScreenOptionSelected(void)
{
if (uiState.input.selectedOptionIndex == 0)
{
if (uiState.menu.onOk)
uiState.menu.onOk();
}
else
{
if (uiState.menu.onNext)
uiState.menu.onNext();
}
}
void uiMenuSettingsBackMenuScreen(void)
{
uiState.menu.itemText = "Back ";
uiState.menu.onNext = &UI_FIRST_SETTINGS_SCREEN;
uiState.menu.onOk = &UI_DEFAULT_SCREEN;
uiMenuScreen();
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorCwg.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD3bits.PWM4MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectCwgIsEnabled(void)
{
CWG1CON0 = anyByteWithMaskClear(_CWG1CON0_EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CWG1CON0bits.EN);
}
void test_voltageRegulatorEnabled_onPublished_expectDeadBandBufferLoadIsClear(void)
{
CWG1CON0bits.EN = 1;
CWG1CON0 = anyByteWithMaskSet(_CWG1CON0_LD_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1CON0bits.LD);
}
void test_voltageRegulatorEnabled_onPublished_expectSynchronousSteeringMode(void)
{
CWG1CON0 = anyByte();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, CWG1CON0bits.MODE);
}
void test_voltageRegulatorEnabled_onPublished_expectManualShutdownIsClear(void)
{
CWG1AS0 = anyByteWithMaskSet(_CWG1AS0_SHUTDOWN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS0bits.SHUTDOWN);
}
void test_voltageRegulatorEnabled_onPublished_expectAutoShutdownDoesNotRestart(void)
{
CWG1AS0 = anyByteWithMaskSet(_CWG1AS0_REN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS0bits.REN);
}
void test_voltageRegulatorEnabled_onPublished_expectAutoShutdownForcesOnesOnBAndDOutputsForBraking(void)
{
CWG1AS0 = anyByte();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL(0b11, CWG1AS0bits.LSBD);
}
void test_voltageRegulatorEnabled_onPublished_expectAutoShutdownForcesOnesOnAAndCOutputsForBraking(void)
{
CWG1AS0 = anyByte();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL(0b11, CWG1AS0bits.LSAC);
}
void test_voltageRegulatorEnabled_onPublished_expectAutoShutdownOnClc2Output(void)
{
CWG1AS1 = anyByteWithMaskClear(_CWG1AS1_AS4E_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CWG1AS1bits.AS4E);
}
void test_voltageRegulatorEnabled_onPublished_expectNoAutoShutdownOnComparator2Output(void)
{
CWG1AS1 = anyByteWithMaskSet(_CWG1AS1_AS3E_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS1bits.AS3E);
}
void test_voltageRegulatorEnabled_onPublished_expectNoAutoShutdownOnComparator1Output(void)
{
CWG1AS1 = anyByteWithMaskSet(_CWG1AS1_AS2E_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS1bits.AS2E);
}
void test_voltageRegulatorEnabled_onPublished_expectNoAutoShutdownOnTimer2(void)
{
CWG1AS1 = anyByteWithMaskSet(_CWG1AS1_AS1E_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS1bits.AS1E);
}
void test_voltageRegulatorEnabled_onPublished_expectNoAutoShutdownOnCwgInputPin(void)
{
CWG1AS1 = anyByteWithMaskSet(_CWG1AS1_AS0E_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CWG1AS1bits.AS0E);
}
void test_voltageRegulatorEnabled_onPublished_expectSteeringOverridesAreZero(void)
{
CWG1STR = anyByteWithMaskSet(0xf0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, CWG1STR & 0xf0);
}
void test_voltageRegulatorEnabled_onPublished_expectCwgInterruptFlagIsClear(void)
{
PIR7 = anyByteWithMaskSet(_PIR7_CWG1IF_MASK);
uint8_t originalPir7 = PIR7;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPir7 & ~_PIR7_CWG1IF_MASK, PIR7);
}
void test_voltageRegulatorEnabled_onPublished_expectCwgInterruptFlagWakesDeviceFromSleep(void)
{
PIE7 = anyByteWithMaskClear(_PIE7_CWG1IE_MASK);
uint8_t originalPie7 = PIE7;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPie7 | _PIE7_CWG1IE_MASK, PIE7);
}
void test_voltageRegulatorEnabled_onPublished_expectAllOutputsAreOverridden(void)
{
CWG1STR = anyByteWithMaskSet(0x0f);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, CWG1STR & 0x0f);
}
void test_voltageRegulatorEnabled_onPublished_expectClockSourceIsFosc(void)
{
CWG1CLKCON = anyByteWithMaskClear(1);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, CWG1CLKCON);
}
void test_voltageRegulatorEnabled_onPublished_expectInputSourceIsPwm4(void)
{
CWG1DAT = anyByteExcept(4);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(4, CWG1DAT);
}
void test_voltageRegulatorEnabled_onPublished_expectPwmAIsMappedToRc6(void)
{
RC6PPS = anyByteExcept(0x05);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0x05, RC6PPS);
}
void test_voltageRegulatorEnabled_onPublished_expectPwmBIsMappedToRc7(void)
{
RC7PPS = anyByteExcept(0x06);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0x06, RC7PPS);
}
<file_sep>/src/firmware/build/install-mplabx.sh
#!/bin/bash
MPLABX_VERSION="v5.20";
XC8_VERSION="v2.32";
MPLABX_INSTALLER_TAR="MPLABX-${MPLABX_VERSION}-linux-installer.tar";
MPLABX_INSTALLER="MPLABX-${MPLABX_VERSION}-linux-installer.sh";
XC8_INSTALLER="xc8-${XC8_VERSION}-full-install-linux-x64-installer.run";
wget --quiet "https://ww1.microchip.com/downloads/en/DeviceDoc/${MPLABX_INSTALLER_TAR}";
tar -xvf "${MPLABX_INSTALLER_TAR}";
sudo "./${MPLABX_INSTALLER}" -- --mode unattended;
wget --quiet "https://www.microchip.com/content/dam/mchp/documents/DEV/ProductDocuments/SoftwareTools/${XC8_INSTALLER}";
chmod +x "${XC8_INSTALLER}";
sudo "./${XC8_INSTALLER}" --mode unattended --netservername whatever;
<file_sep>/src/firmware/tests/Door/TestDoorOpeningOnMotorStopped3.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorIsTurnedOnAfterCurrentLimitIsSet(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_TRUE_MESSAGE(motorOnSequence > motorLimitIsNoLoadSequence, "Seq");
TEST_ASSERT_EQUAL_INT16_MESSAGE(-nvmSettings.application.door.height, motorOnArgs[0], "Arg");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorIsNotTurnedOn(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsClose_expectStateIsClosingWithCloseTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Opening,
.transition = DoorTransition_Close
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closing, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Close, state.transition, "T");
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsClose_expectStateIsFaultWithCloseTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Opening,
.transition = DoorTransition_Close
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishMotorStoppedWithFaults();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Close, state.transition, "T");
}
<file_sep>/src/firmware/src/Ui.h
#ifndef __CLUCK2SESAME_SRC_UI_H
#define __CLUCK2SESAME_SRC_UI_H
extern void uiInitialise(void);
#endif
<file_sep>/src/firmware/src/Platform/Temperature.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_TEMPERATURE_H
#define __CLUCK2SESAME_SRC_PLATFORM_TEMPERATURE_H
#include <stdint.h>
#include "Event.h"
#define TEMPERATURE_SAMPLED ((EventType) 0x3c)
struct TemperatureSampled
{
uint16_t sample;
int16_t currentCelsius;
int16_t deltaCelsius;
uint8_t deltaSeconds;
};
#define CELSIUS(celsius) ((int16_t) ((celsius) * 10))
extern void temperatureInitialise(void);
#endif
<file_sep>/src/firmware/src/Platform/Motor/MotorSetLimits.c
#include <xc.h>
#include <stdint.h>
#include "../NvmSettings.h"
#include "Motor.h"
void motorLimitIsNoLoad(void)
{
DAC1CON1 = nvmSettings.platform.motor.currentLimitNoLoad;
}
void motorLimitIsMaximumLoad(void)
{
DAC1CON1 = nvmSettings.platform.motor.currentLimitMaximumLoad;
}
<file_sep>/src/firmware/src/Platform/Motor.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_MOTOR_H
#define __CLUCK2SESAME_SRC_PLATFORM_MOTOR_H
#include <stdint.h>
#include "Event.h"
#define MOTOR_ENABLED ((EventType) 0x28)
struct MotorEnabled { EMPTY_EVENT_ARGS };
#define MOTOR_DISABLED ((EventType) 0x29)
struct MotorDisabled { EMPTY_EVENT_ARGS };
#define MOTOR_STARTED ((EventType) 0x2a)
struct MotorStarted
{
int16_t count;
};
#define MOTOR_STOPPED ((EventType) 0x2b)
struct MotorStopped
{
int16_t actualCount;
int16_t requestedCount;
union
{
uint8_t all;
uint8_t any;
struct
{
unsigned int currentLimited : 1;
unsigned int encoderTimeout : 1;
unsigned int encoderOverflow : 1;
};
} fault;
};
extern void motorInitialise(void);
extern void motorEnable(void);
extern uint8_t motorIsEnabled(void);
extern void motorDisable(void);
extern void motorOn(int16_t count);
extern void motorOff(void);
extern void motorLimitIsNoLoad(void);
extern void motorLimitIsMaximumLoad(void);
#endif
<file_sep>/src/firmware/tests/Platform/Lcd/LcdInternals.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_LCD_LCDINTERNALS_H
#define __CLUCK2SESAME_TESTS_PLATFORM_LCD_LCDINTERNALS_H
#include "Platform/Event.h"
extern void lcdConfigure(void);
#endif
<file_sep>/src/firmware/tests/Platform/Lcd/LcdFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "Platform/PowerManagement.h"
#include "Platform/NearScheduler.h"
#include "Platform/PwmTimer.h"
#include "Platform/Lcd.h"
#include "FakeLcd.h"
#include "LcdFixture.h"
#include "../../NonDeterminism.h"
extern void poll(void);
static void voltageRegulatorInitialise(void);
static void onLcdEnabled(const struct Event *event);
void voltageRegulatorDisable(void);
static uint8_t isLcdEnabled;
void lcdFixtureInitialise(void)
{
eventInitialise();
clockInitialise();
powerManagementInitialise();
nearSchedulerInitialise();
pwmTimerInitialise();
voltageRegulatorInitialise();
lcdInitialise();
fakeLcdInitialise();
isLcdEnabled = 0;
}
static void voltageRegulatorInitialise(void)
{
ANSELBbits.ANSB2 = 0;
LATBbits.LATB2 = 0;
TRISBbits.TRISB2 = 0;
}
void lcdFixtureShutdown(void)
{
fakeLcdShutdown();
voltageRegulatorDisable();
}
void enableLcdAndWaitUntilDone(void)
{
static const struct EventSubscription onLcdEnabledSubscription =
{
.type = LCD_ENABLED,
.handler = &onLcdEnabled,
.state = (void *) 0
};
eventSubscribe(&onLcdEnabledSubscription);
lcdEnable();
while (!fakeLcdIsSessionInvalid && !isLcdEnabled)
poll();
}
static void onLcdEnabled(const struct Event *event)
{
isLcdEnabled = 1;
}
void voltageRegulatorEnable(void)
{
LATBbits.LATB2 = 1;
}
void voltageRegulatorDisable(void)
{
LATBbits.LATB2 = 0;
}
uint8_t voltageRegulatorIsEnabled(void)
{
return LATBbits.LATB2 != 0;
}
<file_sep>/src/firmware/tests/Platform/Event/TestEventDispatch2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Platform/Event.h"
#include "Mock_EventHandler.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
#define MAX_EVENTS 16
static struct EventSubscription subscription;
static uint8_t eventState;
static struct EventSubscription anotherSubscription;
static uint8_t anotherEventState;
static void buggyCompilerWorkaround(void)
{
eventPublish(0, _OMNITARGET);
}
void onBeforeTest(void)
{
eventState = anyByte();
subscription.type = anyByte();
subscription.handler = &eventHandler;
subscription.state = &eventState;
anotherEventState = anyByte();
anotherSubscription.type = anyByteExcept(subscription.type);
anotherSubscription.handler = &anotherEventHandler;
anotherSubscription.state = &anotherEventState;
eventInitialise();
}
void onAfterTest(void)
{
}
void test_eventPublish_calledMoreTimesThanAvailableBufferSize_expectCircularBuffer(void)
{
for (uint8_t i = 0; i < MAX_EVENTS; i++)
eventPublish(subscription.type, NULL);
eventPublish(anotherSubscription.type, NULL);
anotherEventHandler_ExpectAnyArgs();
eventPublish(subscription.type, NULL);
eventHandler_ExpectAnyArgs();
eventSubscribe(&subscription);
eventSubscribe(&anotherSubscription);
for (uint8_t i = 0; i < MAX_EVENTS; i++)
eventDispatchNext();
}
void test_eventDispatchNext_calledMoreTimesThanEvents_expectCorrectNumberOfEventsAreDispatched(void)
{
eventSubscribe(&subscription);
eventPublish(subscription.type, NULL);
eventHandler_ExpectAnyArgs();
for (uint8_t i = 0; i < MAX_EVENTS + 1; i++)
eventDispatchNext();
}
void test_eventDispatchNext_calledWhenEventsDispatched_ExpectNonZeroIsReturned(void)
{
eventPublish(subscription.type, NULL);
TEST_ASSERT_NOT_EQUAL(0, eventDispatchNext());
}
void test_eventDispatchNext_calledWhenEventsNotDispatched_ExpectZeroIsReturned(void)
{
eventPublish(subscription.type, NULL);
eventDispatchNext();
TEST_ASSERT_EQUAL_INT8(0, eventDispatchNext());
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorCurrentSenseComparator.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD2bits.CMP1MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectComparatorIsEnabled(void)
{
CM1CON0 = anyByteWithMaskClear(_CM1CON0_EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CM1CON0bits.EN);
}
void test_voltageRegulatorEnabled_onPublished_expectComparatorOutputIsInverted(void)
{
CM1CON0 = anyByteWithMaskClear(_CM1CON0_POL_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CM1CON0bits.POL);
}
void test_voltageRegulatorEnabled_onPublished_expectComparatorHasHysteresis(void)
{
CM1CON0 = anyByteWithMaskClear(_CM1CON0_HYS_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CM1CON0bits.HYS);
}
void test_voltageRegulatorEnabled_onPublished_expectComparatorIsAsynchronous(void)
{
CM1CON0 = anyByteWithMaskSet(_CM1CON0_SYNC_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CM1CON0bits.SYNC);
}
void test_voltageRegulatorEnabled_onPublished_expectOnlyPositiveEdgeSetsInterruptFlag(void)
{
CM1CON1 = anyByteWithMaskClear(_CM1CON1_INTP_MASK) | _CM1CON1_INTN_MASK;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(CM1CON1bits.INTP, "INTP");
TEST_ASSERT_FALSE_MESSAGE(CM1CON1bits.INTN, "INTN");
}
void test_voltageRegulatorEnabled_onPublished_expectComparatorInterruptFlagIsCleared(void)
{
PIR2 = anyByteWithMaskSet(_PIR2_C1IF_MASK);
uint8_t originalPir2 = PIR2;
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPir2 & ~_PIR2_C1IF_MASK, PIR2);
}
void test_voltageRegulatorEnabled_onPublished_expectNegativeInputIsRb1(void)
{
CM1NCH = anyByteExcept(3);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(3, CM1NCH);
}
void test_voltageRegulatorEnabled_onPublished_expectPositiveInputIsDac(void)
{
CM1PCH = anyByteExcept(5);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(5, CM1PCH);
}
<file_sep>/src/firmware/src/Platform/PowerManagement.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_POWERMANAGEMENT_H
#define __CLUCK2SESAME_SRC_PLATFORM_POWERMANAGEMENT_H
#include "Event.h"
#define WOKEN_FROM_SLEEP ((EventType) 0x08)
struct WokenFromSleep { EMPTY_EVENT_ARGS };
extern void powerManagementInitialise(void);
#endif
<file_sep>/src/firmware/src/Platform/Main.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_MAIN_H
#define __CLUCK2SESAME_SRC_PLATFORM_MAIN_H
#include "Event.h"
#define SYSTEM_INITIALISED ((EventType) 0x01)
struct SystemInitialised { EMPTY_EVENT_ARGS };
#define ALL_EVENTS_DISPATCHED ((EventType) 0x02)
struct AllEventsDispatched { EMPTY_EVENT_ARGS };
extern void initialise(void);
extern void applicationInitialise(void);
extern void poll(void);
#endif
<file_sep>/src/firmware/src/Ui/UiScreen.c
#include <xc.h>
#include <stdint.h>
#include <stdlib.h>
#include "../Platform/NvmSettings.h"
#include "../Platform/NearScheduler.h"
#include "../Platform/Lcd.h"
#include "Ui.h"
static void uiOnScreenTimeout(void *state);
static void uiScreenSetAddressToHome(void *state);
static void __reentrant uiScreenBlitFirstLine(void *state);
static void uiScreenGotoSecondLine(void *state);
static void uiScreenBlitSecondLine(void *state);
static void uiScreenSetCursorPosition(void *state);
static void uiScreenTurnCursorOn(void *state);
static void uiScreenBlitDone(void *state);
static const struct NearSchedule uiScreenTimeoutSchedule =
{
.ticks = MS_TO_TICKS(1000),
.handler = &uiOnScreenTimeout
};
void uiScreenOn(void)
{
if (!uiState.flags.bits.isScreenOn)
{
lcdEnable();
uiState.flags.bits.isScreenOn = 1;
uiState.flags.bits.isScreenTimeoutDisabled = 0;
nearSchedulerAddOrUpdate(&uiScreenTimeoutSchedule);
}
}
void uiScreenOff(void)
{
uiState.flags.bits.isScreenBlitDirty = 0;
uiState.flags.bits.isScreenBeingBlitted = 0;
if (uiState.flags.bits.isScreenOn)
{
uiState.flags.bits.isScreenOn = 0;
lcdDisable();
}
}
void uiScreenStartTimeout(void)
{
uiState.flags.bits.isScreenTimeoutDisabled = 0;
uiState.screenTimeoutCount = 0;
nearSchedulerAddOrUpdate(&uiScreenTimeoutSchedule);
}
static void uiOnScreenTimeout(void *state)
{
if (uiState.flags.bits.isScreenTimeoutDisabled)
uiState.screenTimeoutCount = 0;
if (++uiState.screenTimeoutCount == nvmSettings.application.ui.screenTimeoutSeconds)
{
uiScreenOff();
uiState.screenTimeoutCount = 0;
}
else
nearSchedulerAddOrUpdate(&uiScreenTimeoutSchedule);
}
void uiScreenBlit(void)
{
if (!uiState.flags.bits.isLcdEnabled || uiState.flags.bits.isScreenBeingBlitted)
{
uiState.flags.bits.isScreenBlitDirty = uiState.flags.bits.isScreenBeingBlitted ? 1 : 0;
return;
}
uiState.flags.bits.isScreenBlitDirty = 0;
uiState.flags.bits.isScreenBeingBlitted = 1;
static const struct LcdSetCursorTransaction transaction =
{
.on = 0,
.callback = &uiScreenSetAddressToHome
};
lcdSetCursor(&transaction);
}
static void uiScreenSetAddressToHome(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
static const struct LcdSetAddressTransaction transaction =
{
.address = 0x00,
.callback = &uiScreenBlitFirstLine
};
lcdSetDdramAddress(&transaction);
}
static void __reentrant uiScreenBlitFirstLine(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
uiState.flags.bits.isScreenBlitDirty = 0;
static const struct LcdPutsTransaction transaction =
{
.buffer = &uiState.screen[0],
.callback = &uiScreenGotoSecondLine
};
lcdPuts(&transaction);
}
static void uiScreenGotoSecondLine(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
static const struct LcdSetAddressTransaction transaction =
{
.address = LCD_ADDRESS_LINE2,
.callback = &uiScreenBlitSecondLine
};
lcdSetDdramAddress(&transaction);
}
static void uiScreenBlitSecondLine(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
static const struct LcdPutsTransaction transaction =
{
.buffer = &uiState.screen[UI_SCREEN_WIDTH + 1],
.callback = &uiScreenSetCursorPosition
};
lcdPuts(&transaction);
}
static void uiScreenSetCursorPosition(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
struct LcdSetAddressTransaction transaction =
{
.address = uiState.input.cursorPosition,
.callback = &uiScreenTurnCursorOn
};
if (transaction.address > UI_SCREEN_WIDTH)
{
transaction.address -= (UI_SCREEN_WIDTH + 1);
transaction.address += LCD_ADDRESS_LINE2;
}
if (transaction.address < LCD_ADDRESS_LINE2 + UI_SCREEN_WIDTH)
lcdSetDdramAddress(&transaction);
else
uiScreenBlitDone((void *) 0);
}
static void uiScreenTurnCursorOn(void *state)
{
if (!uiState.flags.bits.isLcdEnabled)
return;
static const struct LcdSetCursorTransaction transaction =
{
.on = 1,
.callback = &uiScreenBlitDone
};
lcdSetCursor(&transaction);
}
static void uiScreenBlitDone(void *state)
{
uiState.flags.bits.isScreenBeingBlitted = 0;
if (uiState.flags.bits.isScreenBlitDirty)
uiScreenBlit();
}
int8_t uiScreenSignAndTwoDigitsFromPosition(uint8_t cursorPosition)
{
int8_t value = (int8_t) uiScreenTwoDigitsFromPosition(cursorPosition + 1);
if (uiState.screen[cursorPosition] == '-')
return -value;
return value;
}
uint8_t uiScreenTwoDigitsFromPosition(uint8_t cursorPosition)
{
return
(uiState.screen[cursorPosition] - '0') * 10 +
(uiState.screen[cursorPosition + 1] - '0');
}
void uiScreenTwoDigitsToPosition(uint8_t cursorPosition, uint8_t value)
{
div_t digits;
digits = div(value, 10);
uiState.screen[cursorPosition] = (char) ('0' + (uint8_t) digits.quot);
uiState.screen[cursorPosition + 1] = (char) ('0' + (uint8_t) digits.rem);
}
void uiScreenFourHexDigitsToPosition(uint8_t cursorPosition, uint16_t value)
{
uint8_t upper = (value >> 8) & 0xff;
uint8_t lower = (value >> 0) & 0xff;
uiScreenTwoHexDigitsToPosition(cursorPosition, upper);
uiScreenTwoHexDigitsToPosition(cursorPosition + 2, lower);
}
void uiScreenTwoHexDigitsToPosition(uint8_t cursorPosition, uint8_t value)
{
uint8_t upper = (value >> 4) & 0x0f;
uint8_t lower = (value >> 0) & 0x0f;
uiState.screen[cursorPosition] = ((upper > 9) ? ('A' - 10) : '0') + upper;
uiState.screen[cursorPosition + 1] = ((lower > 9) ? ('A' - 10) : '0') + lower;
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorClc.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD5bits.CLC2MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectClcIsEnabled(void)
{
CLC2CON = anyByteWithMaskClear(_CLC2CON_LC2EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CLC2CONbits.LC2EN);
}
void test_voltageRegulatorEnabled_onPublished_expectClcInterruptFlagDoesNotGetSetOnPositiveEdge(void)
{
CLC2CON = anyByteWithMaskSet(_CLC2CON_LC2INTP_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CLC2CONbits.LC2INTP);
}
void test_voltageRegulatorEnabled_onPublished_expectClcInterruptFlagDoesNotGetSetOnNegativeEdge(void)
{
CLC2CON = anyByteWithMaskSet(_CLC2CON_LC2INTN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_FALSE(CLC2CONbits.LC2INTN);
}
void test_voltageRegulatorEnabled_onPublished_expectClcCellIs4InputAnd(void)
{
CLC2CON = anyByteWithMaskSet(0b111 << _CLC2CON_LC2MODE0_POSITION);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0b010, CLC2CONbits.LC2MODE);
}
void test_voltageRegulatorEnabled_onPublished_expectClcOutputIsInvertedBecauseCwgShutdownIsActiveLow(void)
{
CLC2POL = anyByteWithMaskClear(_CLC2POL_LC2POL_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CLC2POLbits.LC2POL);
}
void test_voltageRegulatorEnabled_onPublished_expectClcGate1IsConfiguredAsTwoInputOrGate(void)
{
CLC2POL = anyByte();
CLC2GLS0 = anyByteExcept(0x0a);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0x0a, CLC2GLS0, "CLC2GLS0");
TEST_ASSERT_FALSE_MESSAGE(CLC2POLbits.LC2G1POL, "LC2G1POL");
}
void test_voltageRegulatorEnabled_onPublished_expectClcGate2IsConfiguredAsLogic1(void)
{
CLC2POL = anyByte();
CLC2GLS1 = anyByteExcept(0x00);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0x00, CLC2GLS1, "CLC2GLS1");
TEST_ASSERT_TRUE_MESSAGE(CLC2POLbits.LC2G2POL, "LC2G2POL");
}
void test_voltageRegulatorEnabled_onPublished_expectClcGate3IsConfiguredAsLogic1(void)
{
CLC2POL = anyByte();
CLC2GLS2 = anyByteExcept(0x00);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0x00, CLC2GLS2, "CLC2GLS2");
TEST_ASSERT_TRUE_MESSAGE(CLC2POLbits.LC2G3POL, "LC2G3POL");
}
void test_voltageRegulatorEnabled_onPublished_expectClcGate4IsConfiguredAsLogic1(void)
{
CLC2POL = anyByte();
CLC2GLS3 = anyByteExcept(0x00);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0x00, CLC2GLS3, "CLC2GLS3");
TEST_ASSERT_TRUE_MESSAGE(CLC2POLbits.LC2G4POL, "LC2G4POL");
}
void test_voltageRegulatorEnabled_onPublished_expectFirstInputChannelIsCurrentSenseComparatorOutput(void)
{
CLC2SEL0 = anyByteExcept(0b010110);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0b010110, CLC2SEL0);
}
void test_voltageRegulatorEnabled_onPublished_expectSecondInputChannelIsEncoderCcpOutput(void)
{
CLC2SEL1 = anyByteExcept(0b001111);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0b001111, CLC2SEL1);
}
void test_voltageRegulatorEnabled_onPublished_expectBothInputsAreRoutedToGate1(void)
{
CLC2GLS0 = anyByteExcept(0b001010);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0b001010, CLC2GLS0);
}
void test_voltageRegulatorEnabled_onPublished_expectGate2HasNoInputs(void)
{
CLC2GLS1 = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, CLC2GLS1);
}
void test_voltageRegulatorEnabled_onPublished_expectGate3HasNoInputs(void)
{
CLC2GLS2 = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, CLC2GLS2);
}
void test_voltageRegulatorEnabled_onPublished_expectGate4HasNoInputs(void)
{
CLC2GLS3 = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, CLC2GLS3);
}
<file_sep>/src/firmware/tests/SunEvents/TestSunEventsScenarios.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Nvm.h"
#include "TestSunEventsScenarios.h"
#include "SunEvents.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
TEST_FILE("SunEvents/SunEventsInitialise.c")
TEST_FILE("SunEvents/SunEventsCalculate.c")
static uint8_t assertSunEventsChanged;
static volatile uint8_t scenarioIndex;
static uint8_t scenarioIndexLastAsserted;
static volatile uint8_t stubDayOfYearHigh;
static volatile uint8_t stubDayOfYearLow;
static volatile int8_t stubLatitudeOffset;
static volatile int8_t stubLongitudeOffset;
static volatile uint8_t expectedSunriseHour;
static volatile uint8_t expectedSunriseMinute;
static volatile uint8_t expectedSunsetHour;
static volatile uint8_t expectedSunsetMinute;
static struct Event onLocationChangedEvent;
static const struct EventSubscription *onLocationChanged;
static struct Event onDateChangedEvent;
static const struct EventSubscription *onDateChanged;
void onBeforeTest(void)
{
assertSunEventsChanged = 1;
scenarioIndex = 0;
scenarioIndexLastAsserted = UINT8_MAX;
onLocationChanged = (const struct EventSubscription *) 0;
onDateChanged = (const struct EventSubscription *) 0;
}
void onAfterTest(void)
{
}
void test_onDateChanged_ExpectSunEventsChangedIsPublishedWithCalculatedSunEventTimes(void)
{
static struct Location location;
static const struct LocationChanged locationArgs = { .location = &location };
static struct DateWithFlags today;
static const struct DateChanged dateArgs = { .today = &today };
sunEventsInitialise();
onLocationChangedEvent.args = &locationArgs;
onDateChangedEvent.args = &dateArgs;
for (scenarioIndex = 0; ; scenarioIndex++)
{
today.dayOfYear = (((uint16_t) stubDayOfYearHigh) << 8) | stubDayOfYearLow;
if (today.dayOfYear > 365)
break;
location.latitudeOffset = stubLatitudeOffset;
location.longitudeOffset = stubLongitudeOffset;
assertSunEventsChanged = 0;
onLocationChanged->handler(&onLocationChangedEvent);
assertSunEventsChanged = 1;
onDateChanged->handler(&onDateChangedEvent);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
scenarioIndex,
scenarioIndexLastAsserted,
"No event published");
}
}
void eventSubscribe(const struct EventSubscription *subscription)
{
TEST_ASSERT_NOT_NULL_MESSAGE(subscription, "Null subscription");
TEST_ASSERT_NOT_NULL_MESSAGE(subscription->handler, "Null handler");
if (subscription->type == LOCATION_CHANGED)
{
onLocationChanged = subscription;
onLocationChangedEvent.type = subscription->type;
onLocationChangedEvent.state = subscription->state;
onLocationChangedEvent.args = (void *) 0;
}
else if (subscription->type == DATE_CHANGED)
{
onDateChanged = subscription;
onDateChangedEvent.type = subscription->type;
onDateChangedEvent.state = subscription->state;
onDateChangedEvent.args = (void *) 0;
}
else
{
TEST_FAIL_MESSAGE("Unknown subscription type");
}
}
void eventPublish(EventType type, const void *args)
{
if (assertSunEventsChanged && type == SUN_EVENTS_CHANGED)
{
scenarioIndexLastAsserted = scenarioIndex;
TEST_ASSERT_NOT_NULL_MESSAGE(args, "Null args");
const struct SunEventsChanged *event = (const struct SunEventsChanged *) args;
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expectedSunriseHour,
event->sunrise.hour,
"Sunrise hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expectedSunriseMinute,
event->sunrise.minute,
"Sunrise minute");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
event->sunrise.second,
"Sunrise second");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expectedSunsetHour,
event->sunset.hour,
"Sunset hour");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expectedSunsetMinute,
event->sunset.minute,
"Sunset minute");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
0,
event->sunset.second,
"Sunset second");
}
else if (type != SUN_EVENTS_CHANGED)
{
TEST_FAIL_MESSAGE("Unknown event type");
}
}
void test_onLocationChanged_ExpectSunEventsChangedIsPublishedWithCalculatedSunEventTimes(void)
{
static struct Location location;
static const struct LocationChanged locationArgs = { .location = &location };
static struct DateWithFlags today;
static const struct DateChanged dateArgs = { .today = &today };
sunEventsInitialise();
onLocationChangedEvent.args = &locationArgs;
onDateChangedEvent.args = &dateArgs;
for (scenarioIndex = 0; ; scenarioIndex++)
{
today.dayOfYear = (((uint16_t) stubDayOfYearHigh) << 8) | stubDayOfYearLow;
if (today.dayOfYear > 365)
break;
location.latitudeOffset = stubLatitudeOffset;
location.longitudeOffset = stubLongitudeOffset;
assertSunEventsChanged = 0;
onDateChanged->handler(&onDateChangedEvent);
assertSunEventsChanged = 1;
onLocationChanged->handler(&onLocationChangedEvent);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
scenarioIndex,
scenarioIndexLastAsserted,
"No event published");
}
}
<file_sep>/src/firmware/tests/Door/TestDoorFindBottom6.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
static void doMaximumFindBottomIterations(void);
void test_findBottomWhenRaisingLoweringSequenceHasRepeatedTenTimes_expectDoorAbortedIsPublishedWithLineTooLongFlag(void)
{
mockOnDoorAborted();
enterFindBottomState();
doMaximumFindBottomIterations();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onDoorAbortedCalls, "Calls");
TEST_ASSERT_NOT_NULL(onDoorAbortedArgs[0]);
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isJammed, "J");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isReversed, "R");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineSnapped, "S");
TEST_ASSERT_TRUE_MESSAGE(onDoorAbortedArgs[0]->fault.isLineTooLong, "L");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isEncoderBroken, "E");
TEST_ASSERT_FALSE_MESSAGE(onDoorAbortedArgs[0]->fault.isInsufficientPower, "P");
}
static void doMaximumFindBottomIterations(void)
{
for (uint8_t i = 0; i < 10; i++)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorAbortedCalls, "Calls");
publishMotorStoppedWithNoFaultsOnLowering();
publishMotorStopped(&raisingStoppedAtThreshold);
dispatchAllEvents();
}
}
void test_findBottomWhenRaisingLoweringSequenceHasRepeatedTenTimes_expectFaultStateWithUnmodifiedTransition(void)
{
mockOnDoorAborted();
enterFindBottomState();
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom, anyTransition);
doMaximumFindBottomIterations();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Fault, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(anyTransition, state.transition, "T");
}
void test_findBottomWhenRaisingLoweringSequenceHasRepeatedTenTimes_expectMotorIsDisabled(void)
{
mockOnDoorAborted();
enterFindBottomState();
doMaximumFindBottomIterations();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_findBottomWhenRaisingLoweringSequenceHasRepeatedTenTimes_expectMotorIsNotTurnedOnForAnotherIteration(void)
{
mockOnDoorAborted();
enterFindBottomState();
doMaximumFindBottomIterations();
TEST_ASSERT_EQUAL_UINT8(2 * 10, motorOnCalls);
}
void test_findBottomWhenRaisingLoweringSequenceHasRepeatedTenTimes_expectFindBottomAlgorithmCanBeRepeated(void)
{
mockOnDoorAborted();
enterFindBottomState();
doMaximumFindBottomIterations();
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(DoorState_Unknown, state.transition);
publishDoorCloseScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Close, state.transition, "T");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(21, motorOnCalls, "ON");
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/CalibrationModeFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_CALIBRATIONMODE_CALIBRATIONMODEFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_CALIBRATIONMODE_CALIBRATIONMODEFIXTURE_H
#include <stdint.h>
extern void calibrationModeFixtureSetUp(void);
extern void calibrationModeFixtureTearDown(void);
extern void stubNvmSettingsWithCalibrationRequired(void);
extern void stubNvmSettingsWithoutCalibrationRequired(void);
extern void assertWokenFromSleepSubscription(void);
extern void assertNoWokenFromSleepSubscription(void);
#endif
<file_sep>/src/firmware/src/Platform/Clock/ClockGetSetNow.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Event.h"
#include "Clock.h"
static struct DateAndTimeGet clockNow;
static const struct DateChanged dateChangedEventArgs =
{
.today = &clockNow.date
};
static const struct TimeChanged timeChangedEventArgs =
{
.now = &clockNow.time
};
void clockGetNowGmt(struct DateAndTimeGet *now)
{
clockNow.date.flags.isLeapYear = clockIsLeapYear(clockNow.date.year) ? 1 : 0;
clockNow.time.second = TMR0L;
if (PIR0bits.TMR0IF)
{
TMR0IF = 0;
clockTicked();
}
memcpy(now, &clockNow, sizeof(struct DateAndTimeGet));
}
void clockTicked(void)
{
uint8_t dateChanged = 0;
TMR0H = 59;
clockNow.time.second = TMR0L;
if (++clockNow.time.minute == 60)
{
if (++clockNow.time.hour == 24)
{
uint8_t lastDayOfMonth = clockDaysInMonth(clockNow.date.month, clockNow.date.year);
if (clockNow.date.day == lastDayOfMonth)
{
if (clockNow.date.month++ == 12)
{
if (++clockNow.date.year == 100)
clockNow.date.year = 0;
clockNow.date.flags.isLeapYear = clockIsLeapYear(clockNow.date.year) ? 1 : 0;
clockNow.date.month = 1;
clockNow.date.dayOfYear = UINT16_MAX;
}
clockNow.date.day = 0;
}
clockNow.date.day++;
clockNow.date.dayOfYear++;
clockNow.time.hour = 0;
dateChanged = 1;
}
clockNow.time.minute = 0;
}
if (dateChanged)
eventPublish(DATE_CHANGED, &dateChangedEventArgs);
eventPublish(TIME_CHANGED, &timeChangedEventArgs);
}
uint8_t clockDaysInMonth(uint8_t month, uint8_t year)
{
if (month == 2)
{
if ((year & 3) == 0)
return 29;
return 28;
}
uint8_t mask30Days = (month & 0b1001);
if (mask30Days == 0b1001 || mask30Days == 0b0000)
return 30;
return 31;
}
void clockSetNowGmt(const struct DateAndTimeSet *now)
{
memcpy(&clockNow, now, sizeof(struct DateAndTimeSet));
clockNow.date.flags.all = 0;
clockNow.date.flags.isLeapYear = clockIsLeapYear(clockNow.date.year) ? 1 : 0;
TMR0H = 59;
TMR0L = clockNow.time.second;
PIR0bits.TMR0IF = 0;
clockNow.date.dayOfYear = clockNow.date.day - 1;
uint8_t month = clockNow.date.month;
while (--month != 0)
clockNow.date.dayOfYear += clockDaysInMonth(month, clockNow.date.year);
eventPublish(DATE_CHANGED, &dateChangedEventArgs);
eventPublish(TIME_CHANGED, &timeChangedEventArgs);
}
<file_sep>/src/firmware/src/Platform/Battery.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_BATTERY_H
#define __CLUCK2SESAME_SRC_PLATFORM_BATTERY_H
#include <stdint.h>
#include "Event.h"
#define BATTERY_VOLTAGE_SAMPLED ((EventType) 0x1c)
struct BatteryVoltageSampled
{
uint16_t sample;
uint16_t millivolts;
};
#define BATTERY_CHARGER_ENABLED ((EventType) 0x1d)
struct BatteryChargerEnabled { EMPTY_EVENT_ARGS };
#define BATTERY_CHARGER_DISABLED ((EventType) 0x1e)
struct BatteryChargerDisabled { EMPTY_EVENT_ARGS };
extern void batteryInitialise(void);
#endif
<file_sep>/src/firmware/src/Ui/Ui.h
#ifndef __CLUCK2SESAME_SRC_UI_UI_H
#define __CLUCK2SESAME_SRC_UI_UI_H
#include "../Platform/Event.h"
#include "../Ui.h"
#define UI_SCREEN_WIDTH 16
#define UI_SCREEN_HEIGHT 2
#define UI_CURSOR_AT(x, y) ((uint8_t) (((y) * (UI_SCREEN_WIDTH + 1)) + (x)))
#define UI_NO_CURSOR UI_CURSOR_AT(0, UI_SCREEN_HEIGHT)
#define UI_DEFAULT_SCREEN uiDateAndTimeStatusScreen
#define UI_FIRST_SETTINGS_SCREEN uiDateAndTimeEntryMenuScreen
#define UI_LAST_SETTINGS_SCREEN uiMenuSettingsBackMenuScreen
struct ButtonBehaviour
{
void (*onPressed)(void);
void (*onReleased)(void);
};
struct ButtonsBehaviour
{
const struct ButtonBehaviour *left;
const struct ButtonBehaviour *right;
};
struct UiInput
{
union
{
struct
{
char min;
char max;
} range;
struct
{
uint8_t cursorPositions[3];
} options;
} menu;
uint8_t selectedOptionIndex;
uint8_t cursorPosition;
const struct ButtonsBehaviour *buttons;
void (*onPreEnter)(void);
void (*onEnter)(void);
};
struct UiState
{
union
{
uint16_t all;
struct
{
unsigned int isCalibrationMode : 1;
unsigned int isInitialSetupRequired : 1;
unsigned int isScreenOn : 1;
unsigned int isLcdEnabled : 1;
unsigned int isScreenTimeoutDisabled : 1;
unsigned int isScreenBeingBlitted : 1;
unsigned int isScreenBlitDirty : 1;
unsigned int isLeftButtonPressed : 1;
unsigned int isRightButtonPressed : 1;
unsigned int isButtonPressPreventedFromTurningOnScreen : 1;
unsigned int isButtonPressTurningOnScreen : 1;
unsigned int isDoorBeingManuallyControlled : 1;
unsigned int isDoorBeingCalibrated : 1;
} bits;
} flags;
char screen[2 * (UI_SCREEN_WIDTH + 1)];
uint8_t screenTimeoutCount;
struct UiInput input;
struct
{
const char *itemText;
void (*onNext)(void);
void (*onOk)(void);
} menu;
};
union NvmSettings;
extern struct UiState uiState;
extern union NvmSettings uiNvmSettings;
extern const struct ButtonsBehaviour uiInputIsUninitialised;
extern const struct ButtonsBehaviour uiInputIsRange;
extern const struct ButtonsBehaviour uiInputIsRangeOfTwo;
extern const struct ButtonsBehaviour uiInputIsOptions;
extern const struct ButtonsBehaviour uiInputIsStatusScreen;
extern const struct ButtonBehaviour uiInputIgnore;
extern const struct ButtonBehaviour uiInputIncrementRange;
extern const struct ButtonBehaviour uiInputToggleRangeOfTwo;
extern const struct ButtonBehaviour uiInputMoveToNextOption;
extern const struct ButtonBehaviour uiInputEntered;
extern void uiOnSystemInitialised(const struct Event *event);
extern void uiOnSystemInitialSetupCompleted(void);
extern void uiInputOnButtonsPressed(const struct Event *event);
extern void uiInputOnButtonsReleased(const struct Event *event);
extern void uiScreenOn(void);
extern void uiScreenOff(void);
extern void uiScreenStartTimeout(void);
extern void uiScreenBlit(void);
extern int8_t uiScreenSignAndTwoDigitsFromPosition(uint8_t cursorPosition);
extern uint8_t uiScreenTwoDigitsFromPosition(uint8_t cursorPosition);
extern void uiScreenTwoDigitsToPosition(uint8_t cursorPosition, uint8_t value);
extern void uiScreenFourHexDigitsToPosition(uint8_t cursorPosition, uint16_t value);
extern void uiScreenTwoHexDigitsToPosition(uint8_t cursorPosition, uint8_t value);
extern void uiMenuScreen(void);
extern void uiMenuSettingsMenuScreen(void);
extern void uiMenuSettingsBackMenuScreen(void);
extern void uiCalibrationModeScreen(void);
extern void uiDateAndTimeEntryMenuScreen(void);
extern void uiDateAndTimeEntryScreen(void);
extern void uiDateAndTimeStatusScreen(void);
extern void uiLatitudeAndLongitudeEntryScreen(void);
extern void uiDoorControlMenuScreen(void);
extern void uiDoorCalibrationMenuScreen(void);
extern void uiDoorCalibrationScreen(void);
#endif
<file_sep>/src/firmware/build/run-test.sh
#!/bin/bash
if [ $# -ne 5 ]; then
echo "Usage: $0 <mdb> <device> <elf> <fixtureSearchRoot> <fixtureFilename>";
exit 1;
fi;
MDB="${1}";
DEVICE="${2}";
TEST_FILENAME="${3}";
PARTIAL_FIXTURE_SEARCHDIR="${4}";
PARTIAL_FIXTURE_FILENAME="${5}";
PARTIAL_FIXTURE_PATH_AND_FILENAME="$(find ${PARTIAL_FIXTURE_SEARCHDIR} -name ${PARTIAL_FIXTURE_FILENAME} -exec readlink -f \{\} \; | head -n 1)";
PARTIAL_FIXTURE_PATH="$(dirname ${PARTIAL_FIXTURE_PATH_AND_FILENAME})";
FIXTURE_FILENAME="$(mktemp /tmp/ceedling-test-fixture.XXXXXXXX)";
RNG_SEED=${RANDOM};
RNG_SEED_HIGH=$(((${RNG_SEED} >> 8) & 0xff));
RNG_SEED_LOW=$((${RNG_SEED} & 0xff));
cat << EOF > ${FIXTURE_FILENAME}
device ${DEVICE}
hwtool SIM
set breakoptions.coreerrors Break
set breakoptions.corewarnings Break
set breakoptions.peripheralerrors Break
set breakoptions.peripheralwarnings Break
set breakoptions.stimulusmessags.errors Break
set breakoptions.stimulusmessags.warnings Break
set oscillator.auxfrequency 32
set oscillator.auxfrequencyunit Mega
set oscillator.rcfrequency 32
set oscillator.rcfrequencyunit Mega
set oscillator.frequency 8
set oscillator.frequencyunit Mega
set uart2io.uartioenabled true
set uart2io.output window
set periphADC1.altscl true
set periphADC1.minTacq 5
set periphADC1.tacqunits microseconds
program "${TEST_FILENAME}"
break unityBeforeRunHook
break unityBreakpointHook
break fpbase
reset
write 0x0420 ${RNG_SEED_LOW} ${RNG_SEED_HIGH}
run
wait
$(cat ${PARTIAL_FIXTURE_PATH_AND_FILENAME} | sed s/\$\{cwd\}/$(echo ${PARTIAL_FIXTURE_PATH} | sed 's/\//\\\//g')/g)
wait 30000
quit
EOF
${MDB} ${FIXTURE_FILENAME}
<file_sep>/src/firmware/tests/Platform/VoltageRegulator/TestVoltageRegulatorEnable1.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Mock_Event.h"
#include "Platform/VoltageRegulator.h"
#include "VoltageRegulatorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/VoltageRegulator.c")
TEST_FILE("Platform/VoltageRegulatorFixture.c")
const struct Event eventEmptyArgs = { };
void test_voltageRegulatorEnable_calledOnceWhenEnablePinIsLow_expectEnablePinIsHigh(void)
{
voltageRegulatorInitialise();
LATB = anyByteWithMaskClear(_LATB_LATB2_MASK);
voltageRegulatorEnable();
TEST_ASSERT_TRUE(LATBbits.LATB2);
}
void test_voltageRegulatorEnable_calledOnceWhenEnablePinIsHigh_expectEnablePinIsHigh(void)
{
voltageRegulatorInitialise();
LATB = anyByteWithMaskSet(_LATB_LATB2_MASK);
voltageRegulatorEnable();
TEST_ASSERT_TRUE(LATBbits.LATB2);
}
void test_voltageRegulatorEnable_calledOnceWhenVmcuSelPinIsLow_expectPinRemainsLow(void)
{
voltageRegulatorInitialise();
LATB = anyByteWithMaskClear(_LATB_LATB0_MASK);
voltageRegulatorEnable();
TEST_ASSERT_FALSE(LATBbits.LATB0);
}
void test_voltageRegulatorEnable_calledOnceWhenVmcuSelPinIsHigh_expectPinRemainsHigh(void)
{
voltageRegulatorInitialise();
LATB = anyByteWithMaskSet(_LATB_LATB0_MASK);
voltageRegulatorEnable();
TEST_ASSERT_TRUE(LATBbits.LATB0);
}
void test_voltageRegulatorEnable_calledOnce_expectNonVoltageRegulatorPinsRemainUnchanged(void)
{
static const uint8_t usedPins = _LATB_LATB0_MASK | _LATB_LATB2_MASK;
LATB = anyByte();
uint8_t expectedLatb = LATB | usedPins;
voltageRegulatorInitialise();
voltageRegulatorEnable();
TEST_ASSERT_EQUAL_UINT8(expectedLatb, LATB | usedPins);
}
void test_voltageRegulatorEnable_calledOnce_expectNoEventsPublished(void)
{
voltageRegulatorInitialise();
eventPublish_StubWithCallback(assertEventPublishNotCalled);
voltageRegulatorEnable();
}
void test_voltageRegulatorEnable_calledOnce_expectScheduleForRegulatedRailStabilisationTime(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
assertScheduleAddedWithHandler();
TEST_ASSERT_EQUAL_UINT8(MS_TO_TICKS(64), requestedSchedule->ticks);
}
void test_voltageRegulatorEnable_calledOnce_expectMcuVoltageRailIsSwitchedToRegulatedRail(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
assertScheduleAddedWithHandler();
LATB = anyByteWithMaskClear(_LATB_LATB0_MASK);
uint8_t originalLatb = LATB;
requestedSchedule->handler(requestedSchedule->state);
TEST_ASSERT_EQUAL_UINT8(originalLatb | _LATB_LATB0_MASK, LATB);
}
void test_voltageRegulatorEnable_calledOnce_expectScheduleForMcuVoltageRailStabilisationTime(void)
{
voltageRegulatorInitialise();
voltageRegulatorEnable();
void *state = requestedSchedule->state;
NearScheduleHandler handler = requestedSchedule->handler;
requestedSchedule = (const struct NearSchedule *) 0;
handler(state);
assertScheduleAddedWithHandler();
TEST_ASSERT_EQUAL_UINT8(MS_TO_TICKS(4), requestedSchedule->ticks);
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeUnknownCommand.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <unity.h>
#include "Mock_Nvm.h"
#include "Mock_HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixtureWithUart.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
TEST_FILE("Platform/Event.c")
static uint8_t anyUnknownCommand(void);
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_uart1_receivesInvalidCommand_expectErrorWithCorrectCodeIsTransmittedToHost(void)
{
uint8_t command[] = {anyUnknownCommand(), CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
static uint8_t anyUnknownCommand(void)
{
uint8_t unknownCommand;
while (true)
{
unknownCommand = anyByte();
switch (unknownCommand)
{
case CALIBRATIONMODE_CMD_EOL:
case CALIBRATIONMODE_CMD_READ:
case CALIBRATIONMODE_CMD_REFCLK:
case CALIBRATIONMODE_CMD_SAMPLEPARAMETERS:
break;
default:
return unknownCommand;
}
}
}
<file_sep>/src/utilities/sunrise-sunset/lookup/Makefile
CC=gcc
CCARGS=-ansi -Wall -pedantic -std=c99 -c
LD=gcc
LDARGS=
LIBS=-lm
EXE_FILE=lookup
OBJ_FILES=lookup.o
all: $(OBJ_FILES)
$(LD) $(LDARGS) -o $(EXE_FILE) $(OBJ_FILES) $(LIBS)
clean:
rm -Rf $(OBJ_FILES) $(EXE_FILE)
%.o: %.c
$(CC) $(CCARGS) -o $@ $<
<file_sep>/src/firmware/tests/NvmSettingsFixture.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "NvmSettingsFixture.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#define RETLW_HIGH 0b110100
static void nvmUnlockSequence(void);
void stubNvmApplicationSettings(const union ApplicationNvmSettings *stubbed)
{
union NvmSettings replacementSettings;
memcpy(
&replacementSettings.platform,
(const void *) &nvmSettings.platform,
sizeof(nvmSettings.platform));
memcpy(
&replacementSettings.application,
stubbed,
sizeof(nvmSettings.application));
stubNvmSettings(&replacementSettings);
}
void stubNvmSettings(const union NvmSettings *stubbed)
{
static const uint8_t *dest = (const uint8_t *) &nvmSettings;
NVMADR = ((uint16_t) dest) & 0x7fff;
NVMCON1bits.NVMREGS = 0;
NVMCON1bits.FREE = 1;
NVMCON1bits.WREN = 1;
nvmUnlockSequence();
NVMCON1bits.LWLO = 1;
NVMDATH = RETLW_HIGH;
const uint8_t *src = (const uint8_t *) stubbed;
for (uint8_t i = 0; i < sizeof(nvmSettings) - 1; i++)
{
NVMDATL = *(src++);
nvmUnlockSequence();
NVMADR++;
}
NVMCON1bits.LWLO = 0;
NVMDATL = *src;
nvmUnlockSequence();
NVMCON1bits.WREN = 0;
}
static void nvmUnlockSequence(void)
{
uint8_t interruptsWereEnabled = INTCONbits.GIE;
INTCONbits.GIE = 0;
NVMCON2 = 0x55;
NVMCON2 = 0xaa;
NVMCON1bits.WR = 1;
if (interruptsWereEnabled)
INTCONbits.GIE = 1;
}
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorCcp.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
PMD3bits.CCP1MD = 0;
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorEnabled_onPublished_expectCcpIsEnabled(void)
{
CCP1CON = anyByteWithMaskClear(_CCP1CON_EN_MASK);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_TRUE(CCP1CONbits.EN);
}
void test_voltageRegulatorEnabled_onPublished_expectCcpModeIsHeldInReset(void)
{
CCP1CON = anyByte();
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0b0000, CCP1CONbits.MODE);
}
void test_voltageRegulatorEnabled_onPublished_expectComparisonWordIsZero(void)
{
CCPR1H = anyByteExcept(0);
CCPR1L = anyByteExcept(0);
publishVoltageRegulatorEnabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, CCPR1L, "CCPR1L");
}
<file_sep>/src/firmware/tests/Platform/CalibrationMode/TestCalibrationModeReadCommand.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <unity.h>
#include "Platform/HexDigits.h"
#include "Mock_PeriodicMonitor.h"
#include "Mock_Nvm.h"
#include "Platform/CalibrationMode.h"
#include "CalibrationModeFixtureWithUart.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
#include "../../NvmSettingsFixture.h"
TEST_FILE("Platform/CalibrationMode.c")
TEST_FILE("Platform/Event.c")
static uint8_t anyNonHexDigit(void);
void onBeforeTest(void)
{
calibrationModeFixtureSetUp();
stubNvmSettingsWithCalibrationRequired();
calibrationModeInitialise();
}
void onAfterTest(void)
{
calibrationModeFixtureTearDown();
}
void test_uart1_receivesReadCommandWithAddress_expectNvmWordAtAddressIsTransmittedToHost(void)
{
uint16_t address = anyWord();
uint16_t wordAtAddress = anyWord();
uint8_t wordAtAddressHexDigits[4];
hexDigitsForWord(wordAtAddressHexDigits, wordAtAddress);
nvmWordAt_ExpectAndReturn(address, wordAtAddress);
uint8_t command[] = {CALIBRATIONMODE_CMD_READ, 'x', 'x', 'x', 'x', CALIBRATIONMODE_CMD_EOL};
hexDigitsForWord(&command[1], address);
fakeHostToDeviceSend(command, sizeof(command));
fakeHostWaitForDeviceResponse();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(6, deviceToHostNumberOfBytes, "NUM");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_REPLY_RESULT, deviceToHostBytes[0], "0");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(wordAtAddressHexDigits[0], deviceToHostBytes[1], "1");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(wordAtAddressHexDigits[1], deviceToHostBytes[2], "2");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(wordAtAddressHexDigits[2], deviceToHostBytes[3], "3");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(wordAtAddressHexDigits[3], deviceToHostBytes[4], "4");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(CALIBRATIONMODE_CMD_EOL, deviceToHostBytes[5], "EOL");
}
void test_uart1_receivesReadCommandWithNonHexDigit_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_READ, 'x', 'x', 'x', 'x', CALIBRATIONMODE_CMD_EOL};
hexDigitsForWord(&command[1], anyWord());
uint8_t nonHexIndex = 1 + anyByteLessThan(4);
command[nonHexIndex] = anyNonHexDigit();
uart1_receivesInvalidCommand_expectInvalidArgumentErrorIsTransmittedToHost(command, sizeof(command));
}
static uint8_t anyNonHexDigit(void)
{
while (true)
{
uint8_t nonHexDigit = anyByte();
if (nonHexDigit < '0' || nonHexDigit > 'f')
return nonHexDigit;
if (nonHexDigit > '9' && nonHexDigit < 'A')
return nonHexDigit;
if (nonHexDigit > 'F' && nonHexDigit < 'a')
return nonHexDigit;
}
}
void test_uart1_receivesReadCommandWithoutArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_READ, CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
void test_uart1_receivesRefclkCommandWithMoreThanOneFourByteArgument_expectErrorIsTransmittedToHost(void)
{
uint8_t command[] = {CALIBRATIONMODE_CMD_READ, '1', '2', '3', '4', '5', CALIBRATIONMODE_CMD_EOL};
uart1_receivesInvalidCommand_expectInvalidCommandErrorIsTransmittedToHost(command, sizeof(command));
}
<file_sep>/src/firmware/src/Platform/Main.c
#include <xc.h>
#include "Main.h"
#ifndef TEST
void main(void)
{
initialise();
while (1)
poll();
}
#endif
<file_sep>/src/firmware/src/Platform/NvmSettings.c
#include <xc.h>
#include <stdint.h>
#include "Event.h"
#include "NvmSettings.h"
#include "../ApplicationNvmSettings.h"
#define RETLW_HIGH 0b110100
#define PWM_VOLTS(x) ((uint8_t) ((256 * (x) / 3.3 + 0.5)))
#define DAC_VOLTS(x) ((uint8_t) ((32 * (x) / 3.3 + 0.5)))
#define DAC_VOLTS_PER_AMP (3 / 1.8)
#define DAC_AMPS(x) DAC_VOLTS((x) * DAC_VOLTS_PER_AMP)
static void nvmUnlockSequence(void);
static uint8_t nvmCrc8Next(uint8_t crc8, uint8_t input);
__section("NvmSettings") const volatile union NvmSettings nvmSettings =
{
.platform =
{
.lcd =
{
.contrast = PWM_VOLTS(1.3),
.backlightBrightness = PWM_VOLTS(1.65)
},
.motor =
{
.currentLimitNoLoad = DAC_AMPS(0.415), // TODO: PEAK 415mA, AVERAGE 140mA WHEN UNLOADED @ 4.2V...*HOWEVER*, THIS CHANGES FOR LOWER VOLTAGES...NEED TO ADAPT THIS PARAMETER ACCORDING TO MOTOR VOLTAGE !
.currentLimitMaximumLoad = DAC_AMPS(1.0) // TODO: THIS MAY ALSO HAVE A VOLTAGE DEPENDENCY AS WELL, ALTHOUGH THE WINDING RESISTANCE MAY BE THE LIMITING FACTOR...TEST IT...
},
.flags =
{
.bits =
{
.isCalibrationRequired = 1
}
}
},
.application =
{
.door =
{
.mode =
{
.isManuallyOverridden = 1
},
.height = 0
},
.ui =
{
.screenTimeoutSeconds = 20
}
},
.crc8 = 0x00 // TODO: THIS NEEDS CALCULATING, AND IT NEEDS VERIFYING ON BOOT
};
uint8_t nvmSettingsStore(const union NvmSettings *newSettings)
{
static const uint8_t *const dest = (const uint8_t *) &nvmSettings;
NVMADR = ((uint16_t) dest) & 0x7fff;
NVMCON1bits.WRERR = 0;
NVMCON1bits.NVMREGS = 0;
NVMCON1bits.FREE = 1;
NVMCON1bits.WREN = 1;
nvmUnlockSequence();
NVMCON1bits.LWLO = 1;
NVMDATH = RETLW_HIGH;
const uint8_t *src = (const uint8_t *) newSettings;
uint8_t crc8 = 0;
for (uint8_t i = 0; i < sizeof(nvmSettings) - 1; i++)
{
NVMDATL = *(src++);
crc8 = nvmCrc8Next(crc8, NVMDATH);
crc8 = nvmCrc8Next(crc8, NVMDATL);
nvmUnlockSequence();
NVMADR++;
}
NVMCON1bits.LWLO = 0;
NVMDATL = crc8;
nvmUnlockSequence();
NVMCON1bits.WREN = 0;
if (NVMCON1bits.WRERR)
return 0;
eventPublish(NVM_SETTINGS_CHANGED, &eventEmptyArgs);
return 1;
}
static void nvmUnlockSequence(void)
{
uint8_t interruptsWereEnabled = INTCONbits.GIE;
INTCONbits.GIE = 0;
NVMCON2 = 0x55;
NVMCON2 = 0xaa;
NVMCON1bits.WR = 1;
if (interruptsWereEnabled)
INTCONbits.GIE = 1;
}
static uint8_t nvmCrc8Next(uint8_t crc8, uint8_t input)
{
uint8_t i;
input ^= crc8;
for (i = 0; i < 8; i++)
{
uint8_t msb = input & 0x80;
input <<= 1;
if (msb != 0)
input ^= 0x07;
}
return input;
}
<file_sep>/src/firmware/tests/Door/TestDoorOpeningOnMotorStopped2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithFaults_expectDoorOpenedIsNotPublished(void)
{
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_Opening, anyTransition);
publishMotorStoppedWithFaults();
mockOnDoorOpened();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onDoorOpenedCalls, "Calls");
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorIsNotDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorCurrentLimitIsNoLoad(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsOpen_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsUnchanged_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsOpeningAndTransitionIsClose_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Opening, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
<file_sep>/src/firmware/tests/NonDeterminism.h
#ifndef __CLUCK2SESAME_TESTS_NONDETERMINISM_H
#define __CLUCK2SESAME_TESTS_NONDETERMINISM_H
#include <stdint.h>
extern uint8_t anyByte(void);
extern uint8_t anyByteExcept(uint8_t except);
extern uint8_t anyByteWithMaskSet(uint8_t mask);
extern uint8_t anyByteWithMaskClear(uint8_t mask);
extern uint8_t anyByteLessThan(uint8_t value);
extern uint8_t anyBoolean(void);
extern uint16_t anyWord(void);
extern uint16_t anyWordExcept(uint16_t except);
extern uint16_t anyWordLessThan(uint16_t value);
extern void *anyBytesInto(void *dest, size_t numberOfBytes);
#endif
<file_sep>/src/firmware/src/Door.h
#ifndef __CLUCK2SESAME_SRC_DOOR_H
#define __CLUCK2SESAME_SRC_DOOR_H
#include <stdint.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
union DoorFaults
{
uint8_t all;
uint8_t any;
struct
{
unsigned int isJammed : 1;
unsigned int isReversed : 1;
unsigned int isLineSnapped : 1;
unsigned int isLineTooLong : 1;
unsigned int isEncoderBroken : 1;
unsigned int isInsufficientPower : 1;
};
};
#define DOOR_OPEN_SCHEDULE_ACTIONED ((EventType) 0x58)
struct DoorOpenScheduleActioned { EMPTY_EVENT_ARGS };
#define DOOR_CLOSE_SCHEDULE_ACTIONED ((EventType) 0x59)
struct DoorCloseScheduleActioned { EMPTY_EVENT_ARGS };
#define DOOR_OPENED ((EventType) 0x5a)
struct DoorOpened { EMPTY_EVENT_ARGS };
#define DOOR_CLOSED ((EventType) 0x5b)
struct DoorClosed
{
int16_t loweredHeight;
};
#define DOOR_ABORTED ((EventType) 0x5c)
struct DoorAborted
{
union DoorFaults fault;
};
#define DOOR_CALIBRATED ((EventType) 0x5d)
struct DoorCalibrated
{
uint16_t height;
union DoorFaults fault;
};
enum DoorTransition
{
DoorTransition_Unchanged,
DoorTransition_Open,
DoorTransition_Close
};
enum DoorState
{
DoorState_Unknown,
DoorState_Fault,
DoorState_ManualOpening_WaitingForEnabledMotor,
DoorState_ManualOpening,
DoorState_ManualClosing_WaitingForEnabledMotor,
DoorState_ManualClosing,
DoorState_FindBottom,
DoorState_FindBottom_WaitingForEnabledMotor,
DoorState_Opening,
DoorState_Opening_WaitingForEnabledMotor,
DoorState_Opened,
DoorState_Closing,
DoorState_Closing_WaitingForEnabledMotor,
DoorState_Closed
};
struct DoorStateWithContext
{
union
{
uint8_t all;
uint8_t any;
struct
{
unsigned int isManuallyOverridden : 1;
unsigned int isSunEventDriven : 1;
unsigned int isTimeDriven : 1;
};
} flags;
struct Time autoOpenTime;
struct Time autoCloseTime;
union DoorFaults fault;
enum DoorTransition transition;
enum DoorState current;
};
extern void doorInitialise(void);
extern void doorGetState(struct DoorStateWithContext *state);
extern void doorCalibrate(void);
extern void doorManualStartOpening(void);
extern void doorManualStartClosing(void);
extern void doorManualStop(void);
#endif
<file_sep>/src/firmware/tests/Door/TestDoorFindBottom4.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIs2mmOnCloseTransition_expectFindBottomStateAndUnmodifiedTransition(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
uint8_t anyTransition = anyByte();
stubDoorWithState(DoorState_FindBottom, anyTransition);
publishMotorStopped(&raisingStoppedAtThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(anyTransition, state.transition, "T");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnCloseTransition_expectClosedStateAndUnchangedTransition(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Close);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closed, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnUnchangedTransition_expectClosedStateAndUnchangedTransition(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Unchanged);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closed, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Unchanged, state.transition, "T");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectOpeningStateAndOpenTransition(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Opening, state.current, "S");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorIsNotDisabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, motorDisableCalls);
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorIsNotReEnabled(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(1, motorEnableCalls);
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorCurrentLimitIsMaximum(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorLimitIsNoLoadCalls = 0;
motorLimitIsMaximumLoadCalls = 0;
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorLimitIsMaximumLoadCalls, "M");
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorCurrentLimitIsChangedBeforeMotorIsTurnedOn(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorLimitIsNoLoadCalls = 0;
motorLimitIsMaximumLoadCalls = 0;
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_TRUE(motorLimitIsMaximumLoadSequence < motorOnSequence);
}
void test_findBottomWhenRaisingStopHasCurrentLimitFaultAndActualCountIsMoreThan2mmOnOpenTransition_expectMotorIsTurnedOn(void)
{
enterFindBottomState();
publishMotorStoppedWithNoFaultsOnLowering();
dispatchAllEvents();
motorOnCalls = 0;
stubDoorWithState(DoorState_FindBottom, DoorTransition_Open);
publishMotorStopped(&raisingStoppedAfterThreshold);
dispatchAllEvents();
struct DoorStateWithContext state;
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(
nvmSettings.application.door.height,
motorOnArgs[0],
"Height");
}
<file_sep>/src/firmware/src/Platform/Motor/MotorInitialise.c
#include <xc.h>
#include "../Event.h"
#include "../PowerManagement.h"
#include "../NvmSettings.h"
#include "../VoltageRegulator.h"
#include "Motor.h"
#define CWG1CON0_SYNCHRONOUS_STEERING_MODE (0b001 << _CWG1CON0_MODE_POSITION)
#define CWG1AS0_FORCE_ALL_ONES_BRAKING_ON_SHUTDOWN ( \
(0b11 << _CWG1AS0_LSBD_POSITION) | \
(0b11 << _CWG1AS0_LSAC_POSITION))
#define CWG1AS1_SHUTDOWN_ON_COMPARATOR1 _CWG1AS1_AS2E_MASK
#define CWG1AS1_SHUTDOWN_ON_CLC2 _CWG1AS1_AS4E_MASK
#define CWG1CLKCON_USE_FOSC 1
#define CWG1DAT_USE_PWM4 0b0100
#define CCP1CON_HOLD_IN_RESET_MODE (0b0000 << _CCP1CON_MODE_POSITION)
#define CM1NCH_CURRENT_SENSE_PIN 0b011
#define CM1PCH_DAC 0b101
#define T1CLK_USE_T1CKIN_PIN 0
#define CLCCON_MODE_AND4 (0b010 << _CLC2CON_LC2MODE_POSITION)
#define CLCSEL_CURRENT_SENSE_COMPARATOR 0b010110
#define CLCSEL_CCP 0b001111
#define PPS_IN_RC3 0x13
#define PPS_OUT_CWG1A 0x05
#define PPS_OUT_CWG1B 0x06
static void onVoltageRegulatorEnabled(const struct Event *event);
static inline void configureTimer1AndCcpForEncoder(void);
static inline void configureClcAsOrGateForCcpAndComparator(void);
static inline void configurePwmAsOffAndComparatorAsCurrentSenseUsingDac(void);
static inline void configureCwgForPwmOutputWithClcShutdown(void);
static void onVoltageRegulatorDisabled(const struct Event *event);
static void onWokenFromSleep(const struct Event *event);
struct MotorState motorState;
void motorInitialise(void)
{
LATC &= 0b00110011;
ANSELC &= 0b00110011;
TRISC &= 0b00110011;
LATBbits.LATB1 = 0;
ANSELBbits.ANSB1 = 1;
TRISBbits.TRISB1 = 0;
static const struct EventSubscription onVoltageRegulatorEnabledSubscription =
{
.type = VOLTAGE_REGULATOR_ENABLED,
.handler = &onVoltageRegulatorEnabled,
.state = (void *) 0
};
eventSubscribe(&onVoltageRegulatorEnabledSubscription);
static const struct EventSubscription onVoltageRegulatorDisabledSubscription =
{
.type = VOLTAGE_REGULATOR_DISABLED,
.handler = &onVoltageRegulatorDisabled,
.state = (void *) 0
};
eventSubscribe(&onVoltageRegulatorDisabledSubscription);
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
motorState.enableCount = 0;
motorState.flags.all = 0;
}
static void onVoltageRegulatorEnabled(const struct Event *event)
{
// TODO: THE NVM_SETTINGS_CHANGED EVENT SHOULD BE HANDLED
PMD2bits.DAC1MD = 0;
DAC1CON1 = nvmSettings.platform.motor.currentLimitMaximumLoad;
DAC1CON0 = _DAC1CON0_EN_MASK;
TRISBbits.TRISB1 = 1;
TRISCbits.TRISC2 = 1;
TRISCbits.TRISC3 = 1;
configureTimer1AndCcpForEncoder();
configureClcAsOrGateForCcpAndComparator();
configureCwgForPwmOutputWithClcShutdown();
configurePwmAsOffAndComparatorAsCurrentSenseUsingDac();
RC6PPS = PPS_OUT_CWG1A;
RC7PPS = PPS_OUT_CWG1B;
if (motorState.enableCount != 0)
{
eventPublish(MOTOR_ENABLED, &eventEmptyArgs);
motorState.flags.isFullyEnabled = 1;
}
}
static inline void configureTimer1AndCcpForEncoder(void)
{
PMD1bits.TMR1MD = 0;
PMD3bits.CCP1MD = 0;
T1CKIPPS = PPS_IN_RC3;
TMR1H = 0;
TMR1L = 0;
T1GCON = 0;
PIR4bits.TMR1IF = 0;
PIE4bits.TMR1IE = 1;
T1CLK = T1CLK_USE_T1CKIN_PIN;
T1CON = _T1CON_ON_MASK | _T1CON_RD16_MASK;
CCPR1H = 0;
CCPR1L = 0;
CCP1CON = _CCP1CON_EN_MASK | CCP1CON_HOLD_IN_RESET_MODE;
}
static inline void configureClcAsOrGateForCcpAndComparator(void)
{
PMD5bits.CLC2MD = 0;
CLC2SEL0 = CLCSEL_CURRENT_SENSE_COMPARATOR;
CLC2SEL1 = CLCSEL_CCP;
CLC2GLS0 = _CLC2GLS0_LC2G1D1T_MASK | _CLC2GLS0_LC2G1D2T_MASK;
CLC2GLS1 = 0;
CLC2GLS2 = 0;
CLC2GLS3 = 0;
CLC2POL = 0b10001110;
CLC2CON = _CLC2CON_LC2EN_MASK | CLCCON_MODE_AND4;
// TODO: SET UP TMR1IF AS AN INPUT AS WELL (THAT'S AN OVERFLOW CONDITION)
}
static inline void configureCwgForPwmOutputWithClcShutdown(void)
{
PMD4bits.CWG1MD = 0;
CWG1AS0 = CWG1AS0_FORCE_ALL_ONES_BRAKING_ON_SHUTDOWN;
CWG1AS1 = CWG1AS1_SHUTDOWN_ON_CLC2;
CWG1STR = 0;
CWG1CLKCON = CWG1CLKCON_USE_FOSC;
CWG1DAT = CWG1DAT_USE_PWM4;
PIR7bits.CWG1IF = 0;
PIE7bits.CWG1IE = 1;
CWG1CON0 = _CWG1CON0_EN_MASK | CWG1CON0_SYNCHRONOUS_STEERING_MODE;
}
static inline void configurePwmAsOffAndComparatorAsCurrentSenseUsingDac(void)
{
PMD2bits.CMP1MD = 0;
PMD3bits.PWM4MD = 0;
CM1NCH = CM1NCH_CURRENT_SENSE_PIN;
CM1PCH = CM1PCH_DAC;
CM1CON1 = _CM1CON1_INTP_MASK;
PIR2bits.C1IF = 0;
PWM4DCH = 0;
PWM4DCL = 0;
PWM4CON = _PWM4CON_PWM4EN_MASK;
CM1CON0 = _CM1CON0_EN_MASK | _CM1CON0_HYS_MASK | _CM1CON0_POL_MASK;
}
static void onVoltageRegulatorDisabled(const struct Event *event)
{
PMD4bits.CWG1MD = 1;
PMD5bits.CLC2MD = 1;
PMD3bits.PWM4MD = 1;
PMD3bits.CCP1MD = 1;
PMD1bits.TMR1MD = 1;
PMD2bits.CMP1MD = 1;
PMD2bits.DAC1MD = 1;
TRISBbits.TRISB1 = 0;
TRISCbits.TRISC2 = 0;
TRISCbits.TRISC3 = 0;
}
static void onWokenFromSleep(const struct Event *event)
{
if (PIR7bits.CWG1IF || PIR4bits.TMR1IF || PIR2bits.C1IF)
motorOff();
}
<file_sep>/src/firmware/src/Ui/UiDateAndTimeScreen.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Event.h"
#include "../Platform/Clock.h"
#include "Ui.h"
#define ENTRY_DATE_YY1_POS UI_CURSOR_AT(2, 1)
#define ENTRY_DATE_YY2_POS (ENTRY_DATE_YY1_POS + 1)
#define ENTRY_DATE_YY_MM_SEPARATOR_POS (ENTRY_DATE_YY2_POS + 1)
#define ENTRY_DATE_MM1_POS (ENTRY_DATE_YY_MM_SEPARATOR_POS + 1)
#define ENTRY_DATE_MM2_POS (ENTRY_DATE_MM1_POS + 1)
#define ENTRY_DATE_MM_DD_SEPARATOR_POS (ENTRY_DATE_MM2_POS + 1)
#define ENTRY_DATE_DD1_POS (ENTRY_DATE_MM_DD_SEPARATOR_POS + 1)
#define ENTRY_DATE_DD2_POS (ENTRY_DATE_DD1_POS + 1)
#define ENTRY_DATE_TIME_SEPARATOR_POS (ENTRY_DATE_DD2_POS + 1)
#define ENTRY_TIME_HH1_POS (ENTRY_DATE_TIME_SEPARATOR_POS + 1)
#define ENTRY_TIME_HH2_POS (ENTRY_TIME_HH1_POS + 1)
#define ENTRY_TIME_HH_MM_SEPARATOR_POS (ENTRY_TIME_HH2_POS + 1)
#define ENTRY_TIME_MM1_POS (ENTRY_TIME_HH_MM_SEPARATOR_POS + 1)
#define ENTRY_TIME_MM2_POS (ENTRY_TIME_MM1_POS + 1)
#define ENTRY_DATE_ENTRY_COMPLETED (ENTRY_TIME_MM2_POS + 1)
#define STATUS_DATE_YY1_POS UI_CURSOR_AT(2, 0)
#define STATUS_DATE_YY2_POS (STATUS_DATE_YY1_POS + 1)
#define STATUS_DATE_YY_MM_SEPARATOR_POS (STATUS_DATE_YY2_POS + 1)
#define STATUS_DATE_MM1_POS (STATUS_DATE_YY_MM_SEPARATOR_POS + 1)
#define STATUS_DATE_MM2_POS (STATUS_DATE_MM1_POS + 1)
#define STATUS_DATE_MM_DD_SEPARATOR_POS (STATUS_DATE_MM2_POS + 1)
#define STATUS_DATE_DD1_POS (STATUS_DATE_MM_DD_SEPARATOR_POS + 1)
#define STATUS_DATE_DD2_POS (STATUS_DATE_DD1_POS + 1)
#define STATUS_DATE_TIME_SEPARATOR_POS (STATUS_DATE_DD2_POS + 1)
#define STATUS_TIME_HH1_POS (STATUS_DATE_TIME_SEPARATOR_POS + 1)
#define STATUS_TIME_HH2_POS (STATUS_TIME_HH1_POS + 1)
#define STATUS_TIME_HH_MM_SEPARATOR_POS (STATUS_TIME_HH2_POS + 1)
#define STATUS_TIME_MM1_POS (STATUS_TIME_HH_MM_SEPARATOR_POS + 1)
#define STATUS_TIME_MM2_POS (STATUS_TIME_MM1_POS + 1)
static void uiDateAndTimeScreenEnterNextDigit(void);
static void uiDateAndTimeScreenTimeChanged(const struct Event *event);
static void uiDateAndTimeScreenStatusExit(void);
static const struct EventSubscription onTimeChangedSubscription =
{
.type = TIME_CHANGED,
.handler = &uiDateAndTimeScreenTimeChanged
};
static const char *const uiDateAndTimeScreens =
"Today is... \0"
"202Y-MM-DD hh:mm\0"
"Temp, Volt, etc.";
#define DATE_AND_TIME_ENTRY_SCREEN_LINES (uiDateAndTimeScreens + 0)
#define DATE_AND_TIME_STATUS_SCREEN_LINES (uiDateAndTimeScreens + UI_SCREEN_WIDTH + 1)
void uiDateAndTimeEntryMenuScreen(void)
{
uiState.menu.itemText = "Set clock ? ";
uiState.menu.onNext = &uiDoorCalibrationMenuScreen;
uiState.menu.onOk = &uiDateAndTimeEntryScreen;
uiMenuScreen();
}
void uiDateAndTimeEntryScreen(void)
{
memcpy(
uiState.screen,
DATE_AND_TIME_ENTRY_SCREEN_LINES,
sizeof(uiState.screen));
uiState.input.cursorPosition = ENTRY_DATE_YY1_POS;
uiState.input.menu.range.min = '2';
uiState.input.menu.range.max = '9';
uiState.input.buttons = &uiInputIsRange;
uiState.input.onEnter = &uiDateAndTimeScreenEnterNextDigit;
uiState.input.onPreEnter = 0;
uiScreenBlit();
}
static void uiDateAndTimeScreenEnterNextDigit(void)
{
static struct DateAndTimeSet dateAndTime;
uiState.input.menu.range.min = '0';
switch (++uiState.input.cursorPosition)
{
case ENTRY_DATE_YY2_POS:
uiState.input.menu.range.max = '9';
break;
case ENTRY_DATE_YY_MM_SEPARATOR_POS:
uiState.input.cursorPosition++;
dateAndTime.date.year = uiScreenTwoDigitsFromPosition(ENTRY_DATE_YY1_POS);
uiState.input.menu.range.max = '1';
break;
case ENTRY_DATE_MM2_POS:
if (uiState.screen[ENTRY_DATE_MM1_POS] == '1')
{
uiState.input.menu.range.max = '2';
}
else
{
uiState.input.menu.range.min = '1';
uiState.input.menu.range.max = '9';
}
break;
case ENTRY_DATE_MM_DD_SEPARATOR_POS:
uiState.input.cursorPosition++;
dateAndTime.date.month = uiScreenTwoDigitsFromPosition(ENTRY_DATE_MM1_POS);
if (dateAndTime.date.month == 2)
uiState.input.menu.range.max = '2';
else
uiState.input.menu.range.max = '3';
break;
case ENTRY_DATE_DD2_POS:
if (uiState.screen[ENTRY_DATE_DD1_POS] == '0')
{
uiState.input.menu.range.min = '1';
uiState.input.menu.range.max = '9';
}
else if (uiState.screen[ENTRY_DATE_DD1_POS] == uiState.input.menu.range.max)
{
uint8_t daysInMonth = clockDaysInMonth(dateAndTime.date.month, dateAndTime.date.year);
if (daysInMonth == 28)
uiState.input.menu.range.max = '8';
else if (daysInMonth == 29)
uiState.input.menu.range.max = '9';
else if (daysInMonth == 30)
uiState.input.menu.range.max = '0';
else
uiState.input.menu.range.max = '1';
}
break;
case ENTRY_DATE_TIME_SEPARATOR_POS:
uiState.input.cursorPosition++;
dateAndTime.date.day = uiScreenTwoDigitsFromPosition(ENTRY_DATE_DD1_POS);
uiState.input.menu.range.max = '2';
break;
case ENTRY_TIME_HH2_POS:
if (uiState.screen[ENTRY_TIME_HH1_POS] == '2')
uiState.input.menu.range.max = '3';
else
uiState.input.menu.range.max = '9';
break;
case ENTRY_TIME_HH_MM_SEPARATOR_POS:
uiState.input.cursorPosition++;
dateAndTime.time.hour = uiScreenTwoDigitsFromPosition(ENTRY_TIME_HH1_POS);
uiState.input.menu.range.max = '5';
break;
case ENTRY_TIME_MM2_POS:
uiState.input.menu.range.max = '9';
break;
case ENTRY_DATE_ENTRY_COMPLETED:
dateAndTime.time.minute = uiScreenTwoDigitsFromPosition(ENTRY_TIME_MM1_POS);
// TODO: THIS NEEDS TO BE LOCAL TIME, NOT GMT...BUT IT'LL DO FOR NOW...
clockSetNowGmt(&dateAndTime);
if (uiState.flags.bits.isInitialSetupRequired)
{
uiLatitudeAndLongitudeEntryScreen();
}
else
{
UI_DEFAULT_SCREEN();
}
return;
}
uiState.screen[uiState.input.cursorPosition] = uiState.input.menu.range.min;
uiScreenBlit();
}
void uiDateAndTimeStatusScreen(void)
{
memcpy(
uiState.screen,
DATE_AND_TIME_STATUS_SCREEN_LINES,
sizeof(uiState.screen));
eventSubscribe(&onTimeChangedSubscription);
uiDateAndTimeScreenTimeChanged((const struct Event *) 0);
uiState.input.cursorPosition = UI_NO_CURSOR;
uiState.input.buttons = &uiInputIsStatusScreen;
uiState.input.onEnter = &uiDateAndTimeScreenStatusExit;
uiScreenBlit();
}
static void uiDateAndTimeScreenTimeChanged(const struct Event *event)
{
static struct DateAndTimeGet now;
// TODO: THIS NEEDS TO BE LOCAL TIME, NOT GMT...BUT IT'LL DO FOR NOW...
clockGetNowGmt(&now);
uiScreenTwoDigitsToPosition(STATUS_DATE_YY1_POS, now.date.year);
uiScreenTwoDigitsToPosition(STATUS_DATE_MM1_POS, now.date.month);
uiScreenTwoDigitsToPosition(STATUS_DATE_DD1_POS, now.date.day);
uiScreenTwoDigitsToPosition(STATUS_TIME_HH1_POS, now.time.hour);
uiScreenTwoDigitsToPosition(STATUS_TIME_MM1_POS, now.time.minute);
}
static void uiDateAndTimeScreenStatusExit(void)
{
eventUnsubscribe(&onTimeChangedSubscription);
uiDoorControlMenuScreen();
}
<file_sep>/src/firmware/tests/Platform/Motor/__TestMotorShutdown2.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
static void wokenFromSleepWithShutdown(void);
static void wokenFromSleepWithoutShutdown(void);
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_wokenFromSleep_onPublishedWithShutdownWhenNoFaults_expectMotorStoppedEventIsPublishedWithClearFaults(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 0;
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onMotorStoppedArgs.fault.all, "Fault");
}
static void wokenFromSleepWithShutdown(void)
{
PIR7bits.CWG1IF = 1;
publishWokenFromSleep();
dispatchAllEvents();
}
void test_wokenFromSleep_onPublishedWithShutdownWhenEncoderOverflowed_expectMotorStoppedEventIsPublishedWithEncoderOverflowFault(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedArgs.fault.encoderOverflow, "Fault");
}
void test_wokenFromSleep_onPublishedWithShutdownWhenEncoderOverflowed_expectTmr1InterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
wokenFromSleepWithShutdown();
TEST_ASSERT_FALSE(PIR4bits.TMR1IF);
}
void test_wokenFromSleep_onPublishedWithoutShutdownWhenEncoderOverflowed_expectMotorIsTurnedOff(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
PIR2bits.C1IF = 0;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(0, CWG1STR & ~STEERING_MASK);
}
static void wokenFromSleepWithoutShutdown(void)
{
PIR7bits.CWG1IF = 0;
publishWokenFromSleep();
dispatchAllEvents();
}
void test_wokenFromSleep_onPublishedWithShutdownWhenCurrentLimited_expectMotorStoppedEventIsPublishedWithCurrentLimitedFault(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
PIR4bits.TMR1IF = 0;
wokenFromSleepWithShutdown();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedArgs.fault.currentLimited, "Fault");
}
void test_wokenFromSleep_onPublishedWithShutdownWhenCurrentLimited_expectCurrentSenseComparatorInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
wokenFromSleepWithShutdown();
TEST_ASSERT_FALSE(PIR2bits.C1IF);
}
void test_wokenFromSleep_onPublishedWithoutShutdownWhenCurrentLimited_expectMotorIsTurnedOff(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
PIR4bits.TMR1IF = 0;
wokenFromSleepWithoutShutdown();
TEST_ASSERT_EQUAL_UINT8(0, CWG1STR & ~STEERING_MASK);
}
// TODO: motorOff() - PWM stops increasing (no more schedules)
// TODO: MOTOR_STOPPED when timeout - expect fault.encoderTimeout set
<file_sep>/src/firmware/tests/Platform/Motor/TestMotorModulesDisabled.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_voltageRegulatorDisabled_onPublished_expectCurrentSenseComparatorAndDacAreDisabled(void)
{
static const uint8_t modules = _PMD2_CMP1MD_MASK | _PMD2_DAC1MD_MASK;
PMD2 = anyByteWithMaskClear(modules);
uint8_t originalPmd2 = PMD2;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd2 | modules, PMD2);
}
void test_voltageRegulatorDisabled_onPublished_expectEncoderCcpAndMotorPwmModulesAreDisabled(void)
{
static const uint8_t modules = _PMD3_CCP1MD_MASK | _PMD3_PWM4MD_MASK;
PMD3 = anyByteWithMaskClear(modules);
uint8_t originalPmd3 = PMD3;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd3 | modules, PMD3);
}
void test_voltageRegulatorDisabled_onPublished_expectTimer1ModuleIsDisabled(void)
{
PMD1 = anyByteWithMaskClear(_PMD1_TMR1MD_MASK);
uint8_t originalPmd1 = PMD1;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd1 | _PMD1_TMR1MD_MASK, PMD1);
}
void test_voltageRegulatorDisabled_onPublished_expectCwgModuleIsDisabled(void)
{
PMD4 = anyByteWithMaskClear(_PMD4_CWG1MD_MASK);
uint8_t originalPmd4 = PMD4;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd4 | _PMD4_CWG1MD_MASK, PMD4);
}
void test_voltageRegulatorDisabled_onPublished_expectClc2ModuleIsDisabled(void)
{
PMD5 = anyByteWithMaskClear(_PMD5_CLC2MD_MASK);
uint8_t originalPmd5 = PMD5;
publishVoltageRegulatorDisabled();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(originalPmd5 | _PMD5_CLC2MD_MASK, PMD5);
}
<file_sep>/src/firmware/src/Platform/Lcd/LcdPuts.c
#include <xc.h>
#include <stdint.h>
#include "../NearScheduler.h"
#include "Lcd.h"
static void buggyCompilerWorkaround(void)
{
static const struct LcdPutsTransaction dummy =
{
.buffer = _OMNITARGET,
.state = _OMNITARGET
};
}
static void __reentrant lcdPutsStateMachine(void *state);
void __reentrant lcdPuts(const struct LcdPutsTransaction *transaction)
{
if (!transaction || lcdState.flags.isBusy)
return;
lcdState.transaction.callback = transaction->callback;
lcdState.transaction.state = transaction->state;
lcdState.flags.isBusy = 1;
lcdPutsStateMachine((void *) transaction->buffer);
}
static void __reentrant lcdPutsStateMachine(void *state)
{
const char *buffer = (const char *) state;
if (buffer && *buffer)
{
lcdWriteData((uint8_t) *buffer);
struct NearSchedule waitForLcdCommand =
{
.ticks = MS_TO_TICKS(1),
.handler = &lcdPutsStateMachine,
.state = (void *) (buffer + 1)
};
nearSchedulerAdd(&waitForLcdCommand);
}
else
lcdTransactionCompleted((void *) 0);
}
<file_sep>/src/firmware/src/Platform/Lcd/LcdEnableDisable.c
#include <xc.h>
#include <stdint.h>
#include "../VoltageRegulator.h"
#include "../PwmTimer.h"
#include "Lcd.h"
void lcdEnable(void)
{
if (++lcdState.enableCount > 1)
return;
voltageRegulatorEnable();
pwmTimerEnable();
if (voltageRegulatorIsEnabled())
lcdConfigure();
}
void lcdOnVoltageRegulatorEnabled(const struct Event *event)
{
if (lcdState.enableCount == 0)
{
ANSELAbits.ANSA2 = 1;
TRISAbits.TRISA2 = 1;
}
else
lcdConfigure();
}
void lcdOnVoltageRegulatorDisabled(const struct Event *event)
{
TRISAbits.TRISA2 = 0;
ANSELAbits.ANSA2 = 0;
}
void lcdDisable(void)
{
if (lcdState.enableCount == 0)
return;
if (--lcdState.enableCount == 0)
{
lcdState.flags.isBusy = 1;
LATA &= 0b00000011;
LATCbits.LATC4 = 0;
ANSELAbits.ANSA2 = 1;
TRISAbits.TRISA2 = 1;
eventPublish(LCD_DISABLED, &eventEmptyArgs);
pwmTimerDisable();
voltageRegulatorDisable();
}
}
<file_sep>/src/firmware/tests/TestApplicationInitialise.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Main.h"
#include "Fixture.h"
TEST_FILE("ApplicationInitialise.c")
struct CallDetails
{
uint8_t sequence;
uint8_t count;
};
static void clearCallsFor(struct CallDetails *calls);
static void assertCalledOnceAtSequence(struct CallDetails *call, uint8_t sequence);
static void registerCallFor(struct CallDetails *calls);
static uint8_t callSequence;
static struct CallDetails locationInitialiseCalls;
static struct CallDetails sunEventsInitialiseCalls;
static struct CallDetails doorInitialiseCalls;
static struct CallDetails uiInitialiseCalls;
void onBeforeTest(void)
{
callSequence = 1;
clearCallsFor(&locationInitialiseCalls);
clearCallsFor(&sunEventsInitialiseCalls);
clearCallsFor(&doorInitialiseCalls);
clearCallsFor(&uiInitialiseCalls);
}
static void clearCallsFor(struct CallDetails *calls)
{
calls->sequence = 0;
calls->count = 0;
}
void onAfterTest(void)
{
}
void test_applicationInitialise_called_expectLocationIsInitialisedFirst(void)
{
applicationInitialise();
assertCalledOnceAtSequence(&locationInitialiseCalls, 1);
}
static void assertCalledOnceAtSequence(struct CallDetails *call, uint8_t sequence)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, call->count, "Count");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(sequence, call->sequence, "Sequence");
}
void locationInitialise(void)
{
registerCallFor(&locationInitialiseCalls);
}
static void registerCallFor(struct CallDetails *calls)
{
calls->sequence = callSequence++;
calls->count++;
}
void test_applicationInitialise_called_expectSunEventsAreInitialisedAfterLocation(void)
{
applicationInitialise();
assertCalledOnceAtSequence(&sunEventsInitialiseCalls, 2);
}
void sunEventsInitialise(void)
{
registerCallFor(&sunEventsInitialiseCalls);
}
void test_applicationInitialise_called_expectDoorIsInitialisedAfterSunEvents(void)
{
applicationInitialise();
assertCalledOnceAtSequence(&doorInitialiseCalls, 3);
}
void doorInitialise(void)
{
registerCallFor(&doorInitialiseCalls);
}
void test_applicationInitialise_called_expectUiIsInitialisedAfterDoor(void)
{
applicationInitialise();
assertCalledOnceAtSequence(&uiInitialiseCalls, 4);
}
void uiInitialise(void)
{
registerCallFor(&uiInitialiseCalls);
}
<file_sep>/src/firmware/tests/Door/TestDoorClosingOnMotorStopped3.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsClose_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorIsNotDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsClosexpectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorIsDisabled(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorDisableCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsClose_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithNoFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWthNoFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorCurrentLimitIsMaximumLoad(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithNoFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(1, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsClose_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Close);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsUnchanged_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Unchanged);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
void test_motorStopped_onPublishedWithFaultsWhenStateIsClosingAndTransitionIsOpen_expectMotorCurrentLimitIsUnchanged(void)
{
stubMotorIsEnabled();
stubDoorWithState(DoorState_Closing, DoorTransition_Open);
publishMotorStoppedWithFaults();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsNoLoadCalls);
TEST_ASSERT_EQUAL_UINT8(0, motorLimitIsMaximumLoadCalls);
}
<file_sep>/src/firmware/src/Platform/PwmTimer.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_PWMTIMER_H
#define __CLUCK2SESAME_SRC_PLATFORM_PWMTIMER_H
extern void pwmTimerInitialise(void);
extern void pwmTimerEnable(void);
extern void pwmTimerDisable(void);
#endif
<file_sep>/src/firmware/src/Platform/Buttons.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_BUTTONS_H
#define __CLUCK2SESAME_SRC_PLATFORM_BUTTONS_H
#include <stdint.h>
#include "Event.h"
#define BUTTONS_PRESSED ((EventType) 0x40)
struct ButtonsPressed
{
uint8_t mask;
};
#define BUTTONS_RELEASED ((EventType) 0x41)
struct ButtonsReleased
{
uint8_t mask;
};
extern void buttonsInitialise(void);
#endif
<file_sep>/src/firmware/tests/Platform/Clock/ClockFixture.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/PowerManagement.h"
#include "Platform/Event.h"
#include "Platform/Clock.h"
#include "ClockFixture.h"
#include "../../NonDeterminism.h"
static uint8_t stubCallSequence;
const struct DateChanged *dateChanged;
uint8_t dateChangedCalls;
uint8_t dateChangedSequence;
const struct TimeChanged *timeChanged;
uint8_t timeChangedCalls;
uint8_t timeChangedSequence;
void clockFixtureSetUp(void)
{
stubCallSequence = 1;
dateChanged = (const struct DateChanged *) 0;
dateChangedCalls = 0;
dateChangedSequence = 0;
timeChanged = (const struct TimeChanged *) 0;
timeChangedCalls = 0;
timeChangedSequence = 0;
}
void clockFixtureTearDown(void)
{
}
void stubAnyDateTimeWithHourAndMinute(uint8_t hour, uint8_t minute)
{
stubAnyDateTimeWithDayAndHourAndMinute(
1 + anyByteLessThan(28),
hour,
minute);
}
void stubAnyDateTimeWithDayAndHourAndMinute(
uint8_t day,
uint8_t hour,
uint8_t minute)
{
stubAnyDateTime();
struct DateAndTimeGet now;
clockGetNowGmt(&now);
now.date.day = day;
now.time.hour = hour;
now.time.minute = minute;
clockSetNowGmt((const struct DateAndTimeSet *) &now);
}
void stubAnyDateTime(void)
{
struct DateAndTimeSet now =
{
.date =
{
.year = anyByteLessThan(100),
.month = 1 + anyByteLessThan(12),
.day = 1 + anyByteLessThan(28)
},
.time =
{
.hour = anyByteLessThan(24),
.minute = anyByteLessThan(60),
.second = anyByteLessThan(60)
}
};
clockSetNowGmt(&now);
}
void assertEqualDateTime(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
assertEqualDateTimeExceptMinute(expected, actual);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->time.minute, actual->time.minute, "MM");
}
void assertEqualDateTimeExceptMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
assertEqualDateTimeExceptHourAndMinute(expected, actual);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->time.hour, actual->time.hour, "HH");
}
void assertEqualDateTimeExceptHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
assertEqualDateTimeExceptDayAndHourAndMinute(expected, actual);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->date.day, actual->date.day, "DD");
TEST_ASSERT_EQUAL_UINT16_MESSAGE(
expected->date.dayOfYear, actual->date.dayOfYear, "DoY");
}
void assertEqualDateTimeExceptDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
assertEqualDateTimeExceptMonthAndDayAndHourAndMinute(expected, actual);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->date.month, actual->date.month, "M");
}
void assertEqualDateTimeExceptMonthAndDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(expected, actual);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->date.year, actual->date.year, "Y");
}
void assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual)
{
TEST_ASSERT_EQUAL_UINT8_MESSAGE(
expected->time.second, actual->time.second, "SS");
}
void assertEqualDate(const struct Date *expected, const struct Date *actual)
{
TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, sizeof(struct Date));
}
void assertEqualTime(
const struct Time *expected,
const struct Time *actual)
{
TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, sizeof(struct Time));
}
void mockOnDateChanged(void)
{
static const struct EventSubscription onDateChangedSubscription =
{
.type = DATE_CHANGED,
.handler = &onDateChanged
};
eventSubscribe(&onDateChangedSubscription);
}
void onDateChanged(const struct Event *event)
{
dateChanged = (const struct DateChanged *) event->args;
dateChangedCalls++;
dateChangedSequence = stubCallSequence++;
}
void mockOnTimeChanged(void)
{
static const struct EventSubscription onTimeChangedSubscription =
{
.type = TIME_CHANGED,
.handler = &onTimeChanged
};
eventSubscribe(&onTimeChangedSubscription);
}
void onTimeChanged(const struct Event *event)
{
timeChanged = (const struct TimeChanged *) event->args;
timeChangedCalls++;
timeChangedSequence = stubCallSequence++;
}
<file_sep>/src/utilities/calibrator/cluck2sesame_device.py
import time
from cluck2sesame_parameters_sample import Cluck2SesameParametersSample
from cluck2sesame_nvm_settings import Cluck2SesameNvmSettings
from pic16f15356_device_information_area import Pic16f15356DeviceInformationArea
class Cluck2SesameDevice:
NVM_SETTINGS_ADDRESS = 0x3f80
def __init__(self, serial_factory):
if serial_factory is None:
raise TypeError('serial_factory')
self._serial_factory = serial_factory
self._serial = None
def __enter__(self):
self._serial = self._serial_factory()
if self._serial is None:
raise TypeError('serial')
self._serial = self._serial.__enter__()
if self._serial is None:
raise TypeError('serial.__enter__')
self._reset()
return self
def _reset(self):
self._serial.write(b"\n")
time.sleep(1)
self._serial.reset_input_buffer()
def __exit__(self, *args):
if self._serial is not None:
self._serial.__exit__()
self._serial = None
def refclk_on(self):
return self._send_command('C1') == '1'
def _send_command(self, command):
if self._serial is None:
raise Exception('Attempted to use the device outside of a "with" block or after disposal')
self._serial.write(bytearray(command + "\n", encoding='ascii'))
echo = str(self._serial.readline(), encoding='ascii').strip()
if echo != command:
raise Exception('Echo expected but corrupted; ' + command + ' --> ' + echo)
result = str(self._serial.readline(), encoding='ascii').strip()
if not result.startswith('='):
raise Exception('Unsuccessful command; ' + command + ' --> ' + result)
return result.lstrip('=')
def refclk_off(self):
return self._send_command('C0') == '0'
def sample_parameters(self):
return Cluck2SesameParametersSample.from_raw(self._send_command('S'))
def read_device_information_area(self):
return Pic16f15356DeviceInformationArea(0x8100, self._read_nvm_at(range(0x8100, 0x8120)))
def _read_nvm_at(self, addr_range):
if not isinstance(addr_range, range):
addr_range = range(addr_range, addr_range + 1)
return [int(self._send_command('R{:04x}'.format(addr)), base=16) for addr in addr_range]
def read_nvm_settings(self):
return Cluck2SesameNvmSettings(
Cluck2SesameDevice.NVM_SETTINGS_ADDRESS,
self._read_nvm_at(range(Cluck2SesameDevice.NVM_SETTINGS_ADDRESS, Cluck2SesameDevice.NVM_SETTINGS_ADDRESS + 32)))
<file_sep>/src/utilities/sunrise-sunset/curve-fitting/curve-fit.c
/*
Hacking playground for curve-fitting the accurate Sunrise / Sunset
calculations documented at:
https://alcor.concordia.ca/~gpkatch/gdate-method.html
Coefficients can be calculated with the Octave '*curve-fit*.m' curve-fitting
scripts and visualised with the Octave 'examine*.m' scripts.
Years are specified from 0, so the Epoch (2000-01-01) is 0000-01-01. This
prevents integer overflow.
The date calculations are done from a base of 0000-03-01 (ie. using March
as the first month of the year). This allows easy calculations on date
differences without complicated leap year conditions. See here:
https://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
https://alcor.concordia.ca/~gpkatch/gdate-method.html
The complicated date calculations shouldn't be necessary in the PIC as the
curve-fitting algorithms only require the day of the year as their input
parameter ([0,365] for leap years, [0,364] for regular years).
*/
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define DEG2RAD(phi) (double) ((phi) / 180 * M_PI)
#define LOOKUP_LENGTH 366
#define LOOKUP_LATITUDE 55
#define LOOKUP_LONGITUDE 0
typedef short FixedQ1_15;
typedef unsigned short FixedQ0_16;
typedef struct
{
int year : 16;
int month : 8;
int day : 8;
} GregorianDate;
typedef struct
{
double day;
double latitude;
double longitude;
double eventHeight;
double correctionSign;
double eventTime;
} SunEventState;
static const GregorianDate epoch = {0, 1, 1};
static double sunriseLookupTable[LOOKUP_LENGTH];
static double sunsetLookupTable[LOOKUP_LENGTH];
static void initialiseLookupTables(void);
static void calculateSunriseLookupTable(double *table, int length);
static FixedQ1_15 fixedAdd(FixedQ1_15 a, FixedQ1_15 b);
static FixedQ1_15 fixedMul(FixedQ1_15 a, FixedQ1_15 b);
static FixedQ1_15 fixedAdd5(
FixedQ1_15 a,
FixedQ1_15 b,
FixedQ1_15 c,
FixedQ1_15 d,
FixedQ1_15 e);
static FixedQ1_15 sine(FixedQ0_16 phi);
static void calculateSunsetLookupTable(double *table, int length);
static int daysSinceEpoch(const GregorianDate date);
static int dateToDays(const GregorianDate date);
static double sunriseTime(int day, double latitude, double longitude);
static void sunEventTime(SunEventState *const state);
static void sunEventTimeIteration(SunEventState *const state);
static double sunsetTime(int day, double latitude, double longitude);
static int writeSunriseSunsetTable(const char *const filename);
static double fittedSunriseTime(int day, double latitude, double longitude);
static int dayOfYearFromDayOfCentury(int day);
static GregorianDate daysSinceEpochToDate(int day);
static GregorianDate daysToDate(int day);
static double fittedSunsetTime(int day, double latitude, double longitude);
static int writeFittedSunriseSunsetTable(const char *const filename);
static FixedQ1_15 sunriseLatitudeAdjustment(int day, double latitude);
static FixedQ1_15 interpolateSunEvent(
double latitudeDifference,
FixedQ1_15 adjustment);
static FixedQ1_15 longitudeAdjustment(double longitude);
static FixedQ1_15 sunsetLatitudeAdjustment(int day, double latitude);
int main(void)
{
double latitude = 55;
double longitude = 0;
int epochDays = dateToDays(epoch);
printf(
"Epoch (2000-01-01) = %.4d-%.2d-%.2d\n",
epoch.year, epoch.month, epoch.day);
printf("Epoch day zero = %d\n", epochDays);
initialiseLookupTables();
for (int year = 0; year < 100; year++)
{
GregorianDate date = {year, 1, 1};
int day = daysSinceEpoch(date);
double timeOfSunrise = 24 * sunriseTime(day, latitude, longitude);
int sunriseHour = (int) timeOfSunrise;
int sunriseMinute = (int) ((timeOfSunrise - sunriseHour) * 60);
double timeOfFittedSunrise =
24 * fittedSunriseTime(day, latitude, longitude);
int fittedSunriseHour = (int) timeOfFittedSunrise;
int fittedSunriseMinute =
(int) ((timeOfFittedSunrise - fittedSunriseHour) * 60);
double timeOfSunset = 24 * sunsetTime(day, latitude, longitude);
int sunsetHour = (int) timeOfSunset;
int sunsetMinute = (int) ((timeOfSunset - sunsetHour) * 60);
double timeOfFittedSunset =
24 * fittedSunsetTime(day, latitude, longitude);
int fittedSunsetHour = (int) timeOfFittedSunset;
int fittedSunsetMinute =
(int) ((timeOfFittedSunset - fittedSunsetHour) * 60);
printf(
"%d Sunrise time: %.2d:%.2d (approximately %.2d:%.2d)\n",
day,
sunriseHour,
sunriseMinute,
fittedSunriseHour,
fittedSunriseMinute);
printf(
"%d Sunset time : %.2d:%.2d (approximately %.2d:%.2d)\n",
day,
sunsetHour,
sunsetMinute,
fittedSunsetHour,
fittedSunsetMinute);
}
return
writeSunriseSunsetTable("sunrise-sunset-reference.txt") +
writeFittedSunriseSunsetTable("sunrise-sunset-fitted.txt");
}
static void initialiseLookupTables(void)
{
calculateSunriseLookupTable(sunriseLookupTable, LOOKUP_LENGTH);
calculateSunsetLookupTable(sunsetLookupTable, LOOKUP_LENGTH);
}
#define FITTED(x, coeff, a, b, c) \
fixedMul(\
coeff[(a)], \
sine(fixedAdd( \
coeff[(b)], \
fixedMul(coeff[(c)], ((x) << 15) / LOOKUP_LENGTH)) << 1))
#define FITTED2(x, cMultiple, coeff, a, b, c) \
fixedMul(\
coeff[(a)], \
sine(fixedAdd5( \
coeff[(b)], \
cMultiple > 0 ? ((x) << 15) / LOOKUP_LENGTH : 0, \
cMultiple > 1 ? ((x) << 15) / LOOKUP_LENGTH : 0, \
cMultiple > 2 ? ((x) << 15) / LOOKUP_LENGTH : 0, \
fixedMul( \
coeff[(c)], \
((x) << 15) / LOOKUP_LENGTH)) << 1))
static void calculateSunriseLookupTable(double *table, int length)
{
/*
static const double coefficients[] = {
0.3898969,
0.2572719,
0.5758223,
0.0192193,
0.0065314,
-0.2439130,
2.4077379,
0.1083663,
0.3261631,
0.9156712
};
*/
static const FixedQ1_15 coefficients[] = {
(FixedQ1_15) 12776,
(FixedQ1_15) 8430,
(FixedQ1_15) 18869,
(FixedQ1_15) 630,
(FixedQ1_15) 214,
(FixedQ1_15) -7993,
(FixedQ1_15) 13361, /* PLUS TWO */
(FixedQ1_15) 3551,
(FixedQ1_15) 10688,
(FixedQ1_15) 30005
};
for (int day = 0; day < length; day++)
{
/*
*(table++) = 32768 * (
coefficients[0] +
(coefficients[1] * sin((coefficients[2] + coefficients[3] * day / LOOKUP_LENGTH) * 2 * M_PI)) +
(coefficients[4] * sin((coefficients[5] + coefficients[6] * day / LOOKUP_LENGTH) * 2 * M_PI)) +
(coefficients[7] * sin((coefficients[8] + coefficients[9] * day / LOOKUP_LENGTH) * 2 * M_PI)));
*/
*(table++) = fixedAdd5(
0,
coefficients[0],
FITTED(day, coefficients, 1, 2, 3),
FITTED2(day, 2, coefficients, 4, 5, 6),
FITTED(day, coefficients, 7, 8, 9));
}
}
static FixedQ1_15 fixedAdd(FixedQ1_15 a, FixedQ1_15 b)
{
int result = (int) a + b;
return (FixedQ1_15) (result & 0xffff);
}
static FixedQ1_15 fixedMul(FixedQ1_15 a, FixedQ1_15 b)
{
int result = ((int) a * b) >> 15;
return (FixedQ1_15) (result & 0xffff);
}
static FixedQ1_15 fixedAdd5(
FixedQ1_15 a,
FixedQ1_15 b,
FixedQ1_15 c,
FixedQ1_15 d,
FixedQ1_15 e)
{
int result = (int) a + b + c + d + e;
return (FixedQ1_15) result;
}
static FixedQ1_15 sine(FixedQ0_16 phi)
{
static FixedQ1_15 lookup[65536];
static int isLookupInitialised = 0;
if (!isLookupInitialised)
{
FILE *fd = fopen(
"../../trigonometry/cordic/cordic-fixed-sine-table.bin",
"rb");
if (!fd)
{
printf("!!! FAILED TO OPEN CORDIC SINE LOOKUP FOR READING !!!\n");
return 0;
}
for (int i = 0; i < 65536; i++)
{
unsigned char bytes[2];
fread(bytes, 2, 1, fd);
lookup[i] = (FixedQ1_15) (
(((FixedQ0_16) bytes[0]) << 8) | ((FixedQ0_16) bytes[1]));
}
fclose(fd);
isLookupInitialised = !0;
}
return lookup[phi];
}
static void calculateSunsetLookupTable(double *table, int length)
{
/*
static const double coefficients[] = {
0.738356,
0.140778,
0.906435,
0.815517,
0.012820,
0.279684,
1.779505,
0.041605,
0.605375,
0.581904
};
*/
static const FixedQ1_15 coefficients[] = {
(FixedQ1_15) 24194,
(FixedQ1_15) 4613,
(FixedQ1_15) 29702,
(FixedQ1_15) 26723,
(FixedQ1_15) 420,
(FixedQ1_15) 9165,
(FixedQ1_15) 25543, /* PLUS ONE */
(FixedQ1_15) 1363,
(FixedQ1_15) 19837,
(FixedQ1_15) 19068
};
for (int day = 0; day < length; day++)
{
/*
*(table++) = 32768 * (
coefficients[0] +
(coefficients[1] * sin((coefficients[2] + coefficients[3] * day / LOOKUP_LENGTH) * 2 * M_PI)) +
(coefficients[4] * sin((coefficients[5] + coefficients[6] * day / LOOKUP_LENGTH) * 2 * M_PI)) +
(coefficients[7] * sin((coefficients[8] + coefficients[9] * day / LOOKUP_LENGTH) * 2 * M_PI)));
*/
*(table++) = fixedAdd5(
0,
coefficients[0],
FITTED(day, coefficients, 1, 2, 3),
FITTED2(day, 1, coefficients, 4, 5, 6),
FITTED(day, coefficients, 7, 8, 9));
}
}
static int daysSinceEpoch(const GregorianDate date)
{
return dateToDays(date) - dateToDays(epoch);
}
static int dateToDays(const GregorianDate date)
{
/* https://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
/* https://alcor.concordia.ca/~gpkatch/gdate-method.html */
int month = (date.month + 9) % 12;
int year = date.year - month / 10;
int day = date.day;
return
365 * year + year / 4 - year / 100 + year / 400 +
(month * 306 + 5) / 10 + (day - 1);
}
static double sunriseTime(int day, double latitude, double longitude)
{
SunEventState state = {
day,
DEG2RAD(latitude),
DEG2RAD(longitude),
DEG2RAD(0),
1,
M_PI
};
sunEventTime(&state);
return state.eventTime / (2 * M_PI);
}
static void sunEventTime(SunEventState *const state)
{
for (int i = 0; i < 5; i++)
sunEventTimeIteration(state);
}
static void sunEventTimeIteration(SunEventState *const state)
{
/* http://www.stargazing.net/kepler/sunrise.html */
double t = (state->day + (state->eventTime / (2 * M_PI))) / 36525.0;
double L = 280.46 + 36000.77 * t;
double G = 357.528 + 35999.05 * t;
double ec = 1.915 * sin(DEG2RAD(G)) + 0.02 * sin(DEG2RAD(2 * G));
double lambda = L + ec;
double E =
-ec + 2.466 * sin(DEG2RAD(2 * lambda)) -
0.053 * sin(DEG2RAD(4 * lambda));
double GHA = state->eventTime - M_PI + DEG2RAD(E);
double obl = 23.4393 - 0.0130 * t;
double delta = asin(sin(DEG2RAD(obl)) * sin(DEG2RAD(lambda)));
double coscNumerator =
sin(state->eventHeight) - sin(state->latitude) * sin(delta);
double coscDenominator = cos(state->latitude) * cos(delta);
double cosc = coscNumerator / coscDenominator;
double correction = (cosc > 1 ? 0 : (cosc < -1 ? M_PI : acos(cosc)));
state->eventTime -=
GHA + state->longitude + correction * state->correctionSign;
}
static double sunsetTime(int day, double latitude, double longitude)
{
SunEventState state = {
day,
DEG2RAD(latitude),
DEG2RAD(longitude),
DEG2RAD(0),
-1,
M_PI
};
sunEventTime(&state);
return state.eventTime / (2 * M_PI);
}
static int writeSunriseSunsetTable(const char *const filename)
{
FILE *fd = fopen(filename, "wt");
if (!fd)
{
printf("Unable to open %s for writing.\n", filename);
return 1;
}
printf("Writing table to %s...\n", filename);
for (int day = 0; day < 36525; day++)
{
double sunriseTimes[] = {
sunriseTime(day, 55, 0),
fittedSunriseTime(day, 55, 0),
sunriseTime(day, 60, 0),
sunriseTime(day, 50, 0)
};
double sunsetTimes[] = {
sunsetTime(day, 55, 0),
fittedSunsetTime(day, 55, 0),
sunsetTime(day, 60, 0),
sunsetTime(day, 50, 0)
};
fprintf(
fd,
"%d"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\n",
day,
sunriseTimes[0],
sunsetTimes[0],
sunriseTimes[1],
sunsetTimes[1],
sunriseTimes[2],
sunsetTimes[2],
sunriseTimes[3],
sunsetTimes[3]);
}
fclose(fd);
return 0;
}
static double fittedSunriseTime(int day, double latitude, double longitude)
{
int dayOfYear = dayOfYearFromDayOfCentury(day);
if (dayOfYear < 7)
dayOfYear = 357;
if (dayOfYear > 357)
dayOfYear = 357;
return
(sunriseLookupTable[dayOfYear] +
sunriseLatitudeAdjustment(dayOfYear, latitude) +
longitudeAdjustment(longitude)) / 32768;
}
static int dayOfYearFromDayOfCentury(int day)
{
GregorianDate date = daysSinceEpochToDate(day);
GregorianDate startOfYear = {date.year, 1, 1};
int dayOfYear = day - daysSinceEpoch(startOfYear);
if (dayOfYear < 0 || dayOfYear > 365)
{
printf(
"!!! ERROR !!! THIS SHOULDN'T HAPPEN; "
"dayOfYear = %d, date = %.4d-%.2d-%.2d\n",
dayOfYear,
date.year,
date.month,
date.day);
return 0;
}
return dayOfYear;
}
static GregorianDate daysSinceEpochToDate(int day)
{
return daysToDate(dateToDays(epoch) + day);
}
static GregorianDate daysToDate(int day)
{
/* https://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
/* https://alcor.concordia.ca/~gpkatch/gdate-method.html */
GregorianDate date;
int mi, ddd;
date.year = (10000 * day + 14780) / 3652425;
ddd = day - (
365 * date.year +
date.year / 4 -
date.year / 100 +
date.year / 400);
if (ddd < 0)
{
date.year--;
ddd = day - (
365 * date.year +
date.year / 4 -
date.year / 100 +
date.year / 400);
}
mi = (100 * ddd + 52) / 3060;
date.month = (mi + 2) % 12 + 1;
date.year = date.year + (mi + 2) / 12;
date.day = ddd - (mi * 306 + 5) / 10 + 1;
return date;
}
static double fittedSunsetTime(int day, double latitude, double longitude)
{
int dayOfYear = dayOfYearFromDayOfCentury(day);
return
(sunsetLookupTable[dayOfYear] +
sunsetLatitudeAdjustment(dayOfYear, latitude) +
longitudeAdjustment(longitude)) / 32768;
}
static int writeFittedSunriseSunsetTable(const char *const filename)
{
double latitude = 55.0;
double longitude = 0.0;
FILE *fd = fopen(filename, "wt");
if (!fd)
{
printf("Unable to open %s for writing.\n", filename);
return 1;
}
printf("Writing table to %s...\n", filename);
for (int day = 0; day < LOOKUP_LENGTH; day++)
{
double fittedSunrise = fittedSunriseTime(day, latitude, longitude);
double actualSunrise = sunriseTime(day, latitude, longitude);
double fittedSunset = fittedSunsetTime(day, latitude, longitude);
double actualSunset = sunsetTime(day, latitude, longitude);
fprintf(
fd,
"%d"
"\t%.8e\t%.8e"
"\t%.8e\t%.8e"
"\n",
day,
actualSunrise,
fittedSunrise,
actualSunset,
fittedSunset);
}
fclose(fd);
return 0;
}
static FixedQ1_15 sunriseLatitudeAdjustment(int day, double latitude)
{
/*
static const double coefficientsPositive[] = {
-0.0150405,
-0.0065156,
-0.3172214,
0.0027572,
0.0054313,
-0.6837716,
0.9239776,
0.0097276,
-0.7135158,
0.0024573
};
static const double coefficientsNegative[] = {
-0.0111063,
-0.0116334,
-0.1816415,
-0.3339923,
-0.0012709,
-0.9382433,
1.4463577,
0.0080276,
-0.4461986,
-0.2802890
};
*/
static const FixedQ1_15 coefficientsPositive[] = {
(FixedQ1_15) -493,
(FixedQ1_15) -214,
(FixedQ1_15) -10395,
(FixedQ1_15) 90,
(FixedQ1_15) 178,
(FixedQ1_15) -22406,
(FixedQ1_15) 30277,
(FixedQ1_15) 319,
(FixedQ1_15) -23380,
(FixedQ1_15) 81
};
static const FixedQ1_15 coefficientsNegative[] = {
(FixedQ1_15) -364,
(FixedQ1_15) -381,
(FixedQ1_15) -5952,
(FixedQ1_15) -10944,
(FixedQ1_15) -42,
(FixedQ1_15) -30744,
(FixedQ1_15) 14626, /* PLUS ONE */
(FixedQ1_15) 263,
(FixedQ1_15) -14621,
(FixedQ1_15) -9185
};
double latitudeDifference = fabs(latitude - LOOKUP_LATITUDE);
FixedQ1_15 adjustment = latitude > LOOKUP_LATITUDE
? fixedAdd5(
0,
coefficientsPositive[0],
FITTED(day, coefficientsPositive, 1, 2, 3),
FITTED(day, coefficientsPositive, 4, 5, 6),
FITTED(day, coefficientsPositive, 7, 8, 9))
: fixedAdd5(
0,
coefficientsNegative[0],
FITTED(day, coefficientsNegative, 1, 2, 3),
FITTED2(day, 1, coefficientsNegative, 4, 5, 6),
FITTED(day, coefficientsNegative, 7, 8, 9));
return interpolateSunEvent(latitudeDifference, adjustment);
}
static FixedQ1_15 interpolateSunEvent(
double latitudeDifference,
FixedQ1_15 adjustment)
{
int iterations = (int) latitudeDifference;
FixedQ1_15 latitudeFraction =
(FixedQ1_15) ((latitudeDifference - iterations) * 32768);
int accumulator = fixedMul(latitudeFraction, adjustment);
for (int i = 0; i < iterations; i++)
accumulator += adjustment;
return accumulator;
}
static FixedQ1_15 longitudeAdjustment(double longitude)
{
int differenceInTenthsOfDegree =
(int) ((longitude - LOOKUP_LONGITUDE) * 10);
return (FixedQ1_15) (differenceInTenthsOfDegree * -8);
}
static FixedQ1_15 sunsetLatitudeAdjustment(int day, double latitude)
{
/*
static const double coefficientsPositive[] = {
2.0157e-02,
5.1045e-03,
7.9097e-01,
9.8548e-01,
2.7135e-02,
8.6629e-01,
1.8893e-03,
9.3824e-04,
7.9225e-01,
3.1405e+00
};
static const double coefficientsNegative[] = {
0.0365669,
0.0046257,
0.7767135,
2.1298537,
0.0395382,
0.6516846,
0.2099763,
-0.0039906,
-0.2582441,
2.2096205
};
*/
static const FixedQ1_15 coefficientsPositive[] = {
(FixedQ1_15) 661,
(FixedQ1_15) 167,
(FixedQ1_15) 25919,
(FixedQ1_15) 32292,
(FixedQ1_15) 889,
(FixedQ1_15) 28387,
(FixedQ1_15) 62,
(FixedQ1_15) 31,
(FixedQ1_15) 25960,
(FixedQ1_15) 4604, /* PLUS THREE */
};
static const FixedQ1_15 coefficientsNegative[] = {
(FixedQ1_15) 1198,
(FixedQ1_15) 152,
(FixedQ1_15) 25451,
(FixedQ1_15) 4255, /* PLUS TWO */
(FixedQ1_15) 1296,
(FixedQ1_15) 21354,
(FixedQ1_15) 6881,
(FixedQ1_15) -131,
(FixedQ1_15) -8462,
(FixedQ1_15) 6869 /* PLUS TWO */
};
double latitudeDifference = fabs(latitude - LOOKUP_LATITUDE);
FixedQ1_15 adjustment = latitude > LOOKUP_LATITUDE
? fixedAdd5(
0,
coefficientsPositive[0],
FITTED(day, coefficientsPositive, 1, 2, 3),
FITTED(day, coefficientsPositive, 4, 5, 6),
FITTED2(day, 3, coefficientsPositive, 7, 8, 9))
: fixedAdd5(
0,
coefficientsNegative[0],
FITTED2(day, 2, coefficientsNegative, 1, 2, 3),
FITTED(day, coefficientsNegative, 4, 5, 6),
FITTED2(day, 2, coefficientsNegative, 7, 8, 9));
return interpolateSunEvent(latitudeDifference, adjustment);
}
<file_sep>/src/firmware/src/Door/DoorOnMotorEnabled.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/NvmSettings.h"
#include "../Platform/Motor.h"
#include "../ApplicationNvmSettings.h"
#include "Door.h"
void doorOnMotorEnabled(const struct Event *event)
{
switch (doorState.current)
{
case DoorState_Opening_WaitingForEnabledMotor:
doorStartOpening(DoorState_Opening, DoorState_Unknown);
break;
case DoorState_Closing_WaitingForEnabledMotor:
doorStartClosing(DoorState_Closing, DoorState_Unknown);
break;
case DoorState_FindBottom_WaitingForEnabledMotor:
doorStartFindingBottom(DoorState_FindBottom, DoorState_Unknown);
break;
case DoorState_ManualOpening_WaitingForEnabledMotor:
doorStartOpening(DoorState_ManualOpening, DoorState_Unknown);
break;
case DoorState_ManualClosing_WaitingForEnabledMotor:
doorStartClosing(DoorState_ManualClosing, DoorState_Unknown);
break;
default:
doorState.current = DoorState_Unknown;
};
}
<file_sep>/src/firmware/tests/Platform/Clock/ClockFixture.h
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_CLOCK_CLOCKFIXTURE_H
#define __CLUCK2SESAME_TESTS_PLATFORM_CLOCK_CLOCKFIXTURE_H
#include <stdint.h>
#include "Platform/Event.h"
#include "Platform/Clock.h"
extern void clockFixtureSetUp(void);
extern void clockFixtureTearDown(void);
extern void stubAnyDateTimeWithHourAndMinute(uint8_t hour, uint8_t minute);
extern void stubAnyDateTimeWithDayAndHourAndMinute(
uint8_t day,
uint8_t hour,
uint8_t minute);
extern void stubAnyDateTime(void);
extern void assertEqualDateTime(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDateTimeExceptMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDateTimeExceptHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDateTimeExceptDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDateTimeExceptMonthAndDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDateTimeExceptYearAndMonthAndDayAndHourAndMinute(
const struct DateAndTimeGet *expected,
const struct DateAndTimeGet *actual);
extern void assertEqualDate(
const struct Date *expected,
const struct Date *actual);
extern void assertEqualTime(
const struct Time *expected,
const struct Time *actual);
extern void mockOnTimeChanged(void);
extern void onTimeChanged(const struct Event *event);
extern void mockOnDateChanged(void);
extern void onDateChanged(const struct Event *event);
extern const struct DateChanged *dateChanged;
extern uint8_t dateChangedCalls;
extern uint8_t dateChangedSequence;
extern const struct TimeChanged *timeChanged;
extern uint8_t timeChangedCalls;
extern uint8_t timeChangedSequence;
#endif
<file_sep>/src/firmware/tests/Door/TestDoorUnknownOnOpenScheduleActioned.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectStateIsFindBottomWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByteExcept(DoorTransition_Open)
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectMotorIsEnabled(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorEnableCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectMotorIsLoweredAbout10cm(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorOnCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(-PULSES_PER_10CM, motorOnArgs[0], "Arg");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectMotorCurrentLimitIsNoLoad(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectMotorIsEnabledBeforeCurrentLimitIsChanged(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_TRUE(motorEnableSequence < motorLimitIsNoLoadSequence);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsEnabled_expectMotorCurrentLimitIsChangedBeforeMotorIsTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsEnabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_TRUE(motorLimitIsNoLoadSequence < motorOnSequence);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsDisabled_expectStateIsFindBottomWaitingForEnabledMotorWithOpenTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByteExcept(DoorTransition_Open)
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom_WaitingForEnabledMotor, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T");
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsDisabled_expectMotorIsEnabled(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(1, motorEnableCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsDisabled_expectMotorIsNotTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_doorOpenScheduleActioned_onPublishedWhenStateIsUnknownAndMotorIsDisabled_expectMotorCurrentLimitIsNotChanged(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_Unknown,
.transition = anyByte()
};
stubMotorIsDisabled();
stubDoorWithState(state.current, state.transition);
publishDoorOpenScheduleActioned();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
<file_sep>/src/firmware/src/Platform/NearScheduler.c
#include <xc.h>
#include <stdint.h>
#include "Event.h"
#include "PowerManagement.h"
#include "NearScheduler.h"
#define MAX_SCHEDULES 8
#define NCO_32768HZ_4MS_INCREMENT 8000
#define NCOCLK_SOURCE_SOSC (0b0101 << _NCO1CLK_N1CKS_POSITION)
static void buggyCompilerWorkaround(void)
{
static const struct NearSchedule dummy =
{
.state = _OMNITARGET
};
}
static void nearSchedulerAddTo(const struct NearSchedule *schedule, struct NearSchedule *ptr);
static void onWokenFromSleep(const struct Event *event);
static uint8_t ticks;
static struct NearSchedule schedules[MAX_SCHEDULES];
static struct NearSchedule *noMoreSchedules = schedules + MAX_SCHEDULES;
static uint8_t numberOfPendingSchedules;
void nearSchedulerInitialise(void)
{
PMD1bits.NCO1MD = 0;
asm("nop");
NCO1CON = 0;
NCO1CLK = NCOCLK_SOURCE_SOSC;
NCO1INCU = 0;
NCO1INCH = (uint8_t) ((NCO_32768HZ_4MS_INCREMENT >> 8) & 0xff);
NCO1INCL = (uint8_t) ((NCO_32768HZ_4MS_INCREMENT >> 0) & 0xff);
PIR7bits.NCO1IF = 0;
PIE7bits.NCO1IE = 1;
static const struct EventSubscription onWokenFromSleepSubscription =
{
.type = WOKEN_FROM_SLEEP,
.handler = &onWokenFromSleep,
.state = (void *) 0
};
eventSubscribe(&onWokenFromSleepSubscription);
for (uint8_t i = 0; i < MAX_SCHEDULES; i++)
schedules[i].handler = (NearScheduleHandler) 0;
numberOfPendingSchedules = 0;
}
void nearSchedulerAdd(const struct NearSchedule *schedule)
{
if (!schedule || !schedule->handler)
return;
struct NearSchedule *ptr;
for (ptr = schedules; ptr != noMoreSchedules; ptr++)
{
if (!ptr->handler)
break;
}
if (ptr == noMoreSchedules)
return; // TODO: THIS SHOULD REGISTER A FAULT
nearSchedulerAddTo(schedule, ptr);
}
static void nearSchedulerAddTo(const struct NearSchedule *schedule, struct NearSchedule *ptr)
{
if (!ptr->handler)
numberOfPendingSchedules++;
ptr->ticks = ticks + schedule->ticks + 1;
ptr->handler = schedule->handler;
ptr->state = schedule->state;
if (!NCO1CONbits.N1EN)
{
if (schedule->ticks != 0)
ptr->ticks--;
NCO1ACCU = 0;
NCO1ACCH = 0;
NCO1ACCL = 0;
NCO1CONbits.N1EN = 1;
}
}
void nearSchedulerAddOrUpdate(const struct NearSchedule *schedule)
{
if (!schedule || !schedule->handler)
return;
struct NearSchedule *ptrUpdate;
struct NearSchedule *ptrFree = (struct NearSchedule *) 0;
for (ptrUpdate = schedules; ptrUpdate != noMoreSchedules; ptrUpdate++)
{
if (ptrUpdate->handler == schedule->handler)
break;
if (!ptrFree && !ptrUpdate->handler)
ptrFree = ptrUpdate;
}
if (ptrUpdate == noMoreSchedules)
{
if (!ptrFree)
return; // TODO: THIS SHOULD REGISTER A FAULT
ptrUpdate = ptrFree;
}
nearSchedulerAddTo(schedule, ptrUpdate);
}
static void onWokenFromSleep(const struct Event *event)
{
if (!PIR7bits.NCO1IF)
return;
PIR7bits.NCO1IF = 0;
ticks++;
for (struct NearSchedule *ptr = schedules; ptr != noMoreSchedules; ptr++)
{
if (ptr->handler && ptr->ticks == ticks)
{
NearScheduleHandler handler = ptr->handler;
ptr->handler = (NearScheduleHandler) 0;
numberOfPendingSchedules--;
handler(ptr->state);
}
}
if (numberOfPendingSchedules == 0)
NCO1CONbits.N1EN = 0;
}
<file_sep>/src/firmware/src/Platform/HexDigits.c
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include "HexDigits.h"
static uint8_t hexDigitHigh(uint8_t value);
static uint8_t hexDigitLow(uint8_t value);
static uint8_t hexDigitToNybble(uint8_t hexDigit);
void hexDigitsForByte(uint8_t *outTwoDigits, uint8_t inByte)
{
*(outTwoDigits++) = hexDigitHigh(inByte);
*outTwoDigits = hexDigitLow(inByte);
}
static uint8_t hexDigitHigh(uint8_t value)
{
return hexDigitLow((value >> 4) & 0x0f);
}
static uint8_t hexDigitLow(uint8_t value)
{
value &= 0x0f;
if (value > 9)
return 'a' + (value - 10);
return '0' + value;
}
void hexDigitsForWord(uint8_t *outFourDigits, uint16_t inWord)
{
hexDigitsForByte(outFourDigits, (uint8_t) (inWord >> 8));
hexDigitsForByte(outFourDigits + 2, (uint8_t) inWord);
}
bool hexDigitsToWord(uint16_t *outWord, const uint8_t *inFourDigits)
{
if (!outWord || !inFourDigits)
return false;
uint16_t word = 0;
for (uint8_t i = 0; i < 4; i++, inFourDigits++)
{
uint8_t nybble = hexDigitToNybble(*inFourDigits);
if (nybble > 15)
return false;
word = (word << 4) | nybble;
}
*outWord = word;
return true;
}
static uint8_t hexDigitToNybble(uint8_t hexDigit)
{
if (hexDigit >= '0' && hexDigit <= '9')
return hexDigit - '0';
if (hexDigit >= 'a' && hexDigit <= 'f')
return 10 + hexDigit - 'a';
if (hexDigit >= 'A' && hexDigit <= 'F')
return 10 + hexDigit - 'A';
return 0xff;
}
<file_sep>/src/firmware/tests/Door/TestDoorFindBottomOnCloseScheduleActioned.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "DoorFindBottomFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void test_doorCloseScheduleActioned_onPublishedWhenStateIsFindBottom_expectSameStateWithCloseTransition(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_FindBottom,
.transition = anyByteExcept(DoorTransition_Close)
};
stubDoorWithState(state.current, state.transition);
publishDoorCloseScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_FindBottom, state.current, "A");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Close, state.transition, "T");
}
void test_doorCloseScheduleActioned_onPublishedWhenStateIsFindBottom_expectMotorIsNotEnabled(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_FindBottom,
.transition = anyByte()
};
stubDoorWithState(state.current, state.transition);
publishDoorCloseScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, motorEnableCalls);
}
void test_doorCloseScheduleActioned_onPublishedWhenStateIsFindBottom_expectMotorIsNotTurnedOn(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_FindBottom,
.transition = anyByte()
};
stubDoorWithState(state.current, state.transition);
publishDoorCloseScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls);
}
void test_doorCloseScheduleActioned_onPublishedWhenStateIsFindBottom_expectMotorCurrentLimitIsNotChanged(void)
{
struct DoorStateWithContext state =
{
.current = DoorState_FindBottom,
.transition = anyByte()
};
stubDoorWithState(state.current, state.transition);
publishDoorCloseScheduleActioned();
dispatchAllEvents();
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M");
}
<file_sep>/src/firmware/src/Door/DoorOnMotorStopped.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/NvmSettings.h"
#include "../Platform/Motor.h"
#include "../ApplicationNvmSettings.h"
#include "Door.h"
void doorOnMotorStopped(const struct Event *event)
{
const struct MotorStopped *args = (const struct MotorStopped *) event->args;
uint8_t fault = 0;
switch (doorState.current)
{
case DoorState_Opening:
if (args->fault.any)
{
if (args->fault.currentLimited)
fault = DOOR_JAMMED;
goto motorFaulted;
}
if (doorState.transition != DoorTransition_Close)
{
motorDisable();
doorState.current = DoorState_Opened;
doorState.transition = DoorTransition_Unchanged;
eventPublish(DOOR_OPENED, &doorState.opened);
}
else
{
eventPublish(DOOR_OPENED, &doorState.opened);
doorStartClosing(DoorState_Closing, DoorState_Closing);
}
break;
case DoorState_Closing:
doorState.closed.loweredHeight -= args->actualCount;
if (args->fault.any)
{
if (args->fault.currentLimited)
fault = DOOR_REVERSED;
goto motorFaulted;
}
if (doorState.transition != DoorTransition_Open)
{
motorDisable();
doorState.current = DoorState_Closed;
doorState.transition = DoorTransition_Unchanged;
eventPublish(DOOR_CLOSED, &doorState.closed);
}
else
{
eventPublish(DOOR_CLOSED, &doorState.closed);
doorStartOpening(DoorState_Opening, DoorState_Opening);
}
break;
case DoorState_FindBottom:
doorState.closed.loweredHeight -= args->actualCount;
if (args->requestedCount < 0)
{
if (args->fault.any)
{
if (args->fault.currentLimited)
fault = DOOR_REVERSED;
goto motorFaulted;
}
motorOn(FIND_BOTTOM_RAISING);
doorState.findBottomIterations++;
}
else
{
if (args->fault.currentLimited)
{
if (args->actualCount > FIND_BOTTOM_THRESHOLD)
{
eventPublish(DOOR_CLOSED, &doorState.closed);
if (doorState.transition != DoorTransition_Open)
{
motorDisable();
doorState.current = DoorState_Closed;
doorState.transition = DoorTransition_Unchanged;
}
else
{
doorStartOpening(DoorState_Opening, DoorState_Opening);
}
}
else
{
if (doorState.findBottomIterations == MAX_FIND_BOTTOM_ITERATIONS)
{
fault = LINE_TOO_LONG;
goto motorFaulted;
}
motorOn(FIND_BOTTOM_LOWERING);
}
}
else
{
if (args->fault.all == 0 || args->fault.encoderOverflow)
fault = LINE_SNAPPED;
goto motorFaulted;
}
}
break;
case DoorState_ManualOpening:
if (args->fault.any)
{
if (args->fault.currentLimited)
fault = DOOR_JAMMED;
goto motorFaulted;
}
motorDisable();
doorState.current = DoorState_Unknown;
break;
case DoorState_ManualClosing:
if (args->fault.any)
{
if (args->fault.currentLimited)
fault = DOOR_REVERSED;
goto motorFaulted;
}
motorDisable();
doorState.current = DoorState_Unknown;
break;
case DoorState_Fault:
case DoorState_Unknown:
break;
case DoorState_Opening_WaitingForEnabledMotor:
case DoorState_Closing_WaitingForEnabledMotor:
case DoorState_ManualOpening_WaitingForEnabledMotor:
case DoorState_ManualClosing_WaitingForEnabledMotor:
motorDisable();
default:
doorState.current = DoorState_Unknown;
};
return;
motorFaulted:
if (fault == 0)
{
if (args->fault.encoderTimeout)
fault = ENCODER_BROKEN;
if (args->fault.encoderOverflow)
fault = LINE_TOO_LONG;
}
motorDisable();
doorState.current = DoorState_Fault;
doorState.aborted.fault.all = fault;
eventPublish(DOOR_ABORTED, &doorState.aborted);
}
<file_sep>/src/firmware/tests/Door/TestDoorInitialState.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorGetState.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_doorGetState_calledAfterInitialised_expectStateIsUnknown(void)
{
struct DoorStateWithContext state =
{
.current = anyByteExcept(DoorState_Unknown)
};
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(DoorState_Unknown, state.current);
}
void test_doorGetState_calledAfterInitialised_expectTransitionIsUnchanged(void)
{
struct DoorStateWithContext state =
{
.transition = anyByteExcept(DoorTransition_Unchanged)
};
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(DoorTransition_Unchanged, state.transition);
}
void test_doorGetState_calledWhenDoorIsTimeDriven_expectCorrectModeFlags(void)
{
stubNvmSettingsForTimeDrivenMode();
doorInitialise();
struct DoorStateWithContext state = { .flags = anyByte() };
doorGetState(&state);
TEST_ASSERT_TRUE_MESSAGE(state.flags.isTimeDriven, "T");
TEST_ASSERT_FALSE_MESSAGE(state.flags.isSunEventDriven, "S");
TEST_ASSERT_FALSE_MESSAGE(state.flags.isManuallyOverridden, "M");
}
void test_doorGetState_calledWhenDoorIsSunEventDriven_expectCorrectModeFlags(void)
{
stubNvmSettingsForSunEventDrivenMode();
doorInitialise();
struct DoorStateWithContext state = { .flags = anyByte() };
doorGetState(&state);
TEST_ASSERT_FALSE_MESSAGE(state.flags.isTimeDriven, "T");
TEST_ASSERT_TRUE_MESSAGE(state.flags.isSunEventDriven, "S");
TEST_ASSERT_FALSE_MESSAGE(state.flags.isManuallyOverridden, "M");
}
void test_doorGetState_calledWhenDoorIsManuallyOverridden_expectCorrectModeFlags(void)
{
stubNvmSettingsForManuallyDrivenMode();
doorInitialise();
struct DoorStateWithContext state = { .flags = anyByte() };
doorGetState(&state);
TEST_ASSERT_FALSE_MESSAGE(state.flags.isTimeDriven, "T");
TEST_ASSERT_FALSE_MESSAGE(state.flags.isSunEventDriven, "S");
TEST_ASSERT_TRUE_MESSAGE(state.flags.isManuallyOverridden, "M");
}
void test_doorGetState_calledWhenDoorIsInUnspecifiedMode_expectCorrectModeFlags(void)
{
stubNvmSettingsForUnspecifiedMode();
doorInitialise();
struct DoorStateWithContext state = { .flags = anyByte() };
doorGetState(&state);
TEST_ASSERT_FALSE_MESSAGE(state.flags.isTimeDriven, "T");
TEST_ASSERT_FALSE_MESSAGE(state.flags.isSunEventDriven, "S");
TEST_ASSERT_TRUE_MESSAGE(state.flags.isManuallyOverridden, "M");
}
void test_doorGetState_calledAfterInitialised_expectNoFault(void)
{
struct DoorStateWithContext state =
{
.fault =
{
.all = anyByteExcept(0)
}
};
doorGetState(&state);
TEST_ASSERT_EQUAL_UINT8(0, state.fault.all);
}
<file_sep>/src/firmware/src/Ui/UiLatitudeAndLongitudeScreen.c
#include <xc.h>
#include <stdint.h>
#include <string.h>
#include "../Platform/NvmSettings.h"
#include "../Location.h"
#include "Ui.h"
#if LONGLAT_ONE_DEGREE != 10
#error The UI is based on the assumption that one degree is 10 units and the fractional part is a single unit
#endif
#define LATITUDE_ORIGIN_DEGREES 55
#define LONGITUDE_ORIGIN_DEGREES 0
#define LAT_SIGN_POS UI_CURSOR_AT(0, 1)
#define LAT_WHOLE1_POS (LAT_SIGN_POS + 1)
#define LAT_WHOLE2_POS (LAT_WHOLE1_POS + 1)
#define LAT_WHOLE_FRAC_SEPARATOR_POS (LAT_WHOLE2_POS + 1)
#define LAT_FRAC1_POS (LAT_WHOLE_FRAC_SEPARATOR_POS + 1)
#define LAT_LONG_SEPARATOR_POS (LAT_FRAC1_POS + 1)
#define LONG_SIGN_POS (LAT_LONG_SEPARATOR_POS + 1)
#define LONG_WHOLE1_POS (LONG_SIGN_POS + 1)
#define LONG_WHOLE2_POS (LONG_WHOLE1_POS + 1)
#define LONG_WHOLE_FRAC_SEPARATOR_POS (LONG_WHOLE2_POS + 1)
#define LONG_FRAC1_POS (LONG_WHOLE_FRAC_SEPARATOR_POS + 1)
#define LATLONG_ENTRY_COMPLETED (LONG_FRAC1_POS + 1)
static void uiLatitudeAndLongitudeScreenEnterNextDigit(void);
static int8_t uiDegreesFromScreenPosition(uint8_t cursorPosition, int8_t origin);
// TODO: THESE NEED WRITING AND PUTTING SOMEWHERE...
static void uiLatitudeAndLongitudeStatusScreen(void) { uiState.input.buttons = &uiInputIsUninitialised; }
// END OF TODO...
void uiLatitudeAndLongitudeEntryScreen(void)
{
memcpy(
uiState.screen,
"Lat-Long is... \0"
"+5y.y +xx.x ",
sizeof(uiState.screen));
uiState.input.cursorPosition = LAT_WHOLE1_POS;
uiState.input.menu.range.min = '5';
uiState.input.menu.range.max = '6';
uiState.input.buttons = &uiInputIsRange;
uiState.input.onEnter = &uiLatitudeAndLongitudeScreenEnterNextDigit;
uiState.input.onPreEnter = 0;
uiScreenBlit();
}
static void uiLatitudeAndLongitudeScreenEnterNextDigit(void)
{
uiState.input.menu.range.min = '0';
switch (++uiState.input.cursorPosition)
{
case LAT_WHOLE2_POS:
if (uiState.screen[LAT_WHOLE1_POS] == '6')
uiState.input.menu.range.max = '0';
else
uiState.input.menu.range.max = '9';
break;
case LAT_WHOLE_FRAC_SEPARATOR_POS:
uiState.input.cursorPosition++;
if (uiState.screen[LAT_WHOLE1_POS] == '6')
uiState.input.menu.range.max = '0';
else
uiState.input.menu.range.max = '9';
break;
case LAT_LONG_SEPARATOR_POS:
uiState.input.cursorPosition++;
uiNvmSettings.application.location.latitudeOffset = uiDegreesFromScreenPosition(LAT_SIGN_POS, LATITUDE_ORIGIN_DEGREES);
uiState.input.menu.range.min = '+';
uiState.input.menu.range.max = '-';
uiState.input.buttons = &uiInputIsRangeOfTwo;
break;
case LONG_WHOLE1_POS:
uiState.input.menu.range.max = '1';
uiState.input.buttons = &uiInputIsRange;
break;
case LONG_WHOLE2_POS:
if (uiState.screen[LONG_WHOLE1_POS] == '1')
uiState.input.menu.range.max = '0';
else
uiState.input.menu.range.max = '9';
break;
case LONG_WHOLE_FRAC_SEPARATOR_POS:
uiState.input.cursorPosition++;
if (uiState.screen[LONG_WHOLE1_POS] == '1')
uiState.input.menu.range.max = '0';
else
uiState.input.menu.range.max = '9';
break;
case LATLONG_ENTRY_COMPLETED:
uiNvmSettings.application.location.longitudeOffset = uiDegreesFromScreenPosition(LONG_SIGN_POS, LONGITUDE_ORIGIN_DEGREES);
if (uiState.flags.bits.isInitialSetupRequired)
{
uiDoorCalibrationScreen();
}
else
{
nvmSettingsStore(&uiNvmSettings);
uiLatitudeAndLongitudeStatusScreen();
}
return;
}
uiState.screen[uiState.input.cursorPosition] = uiState.input.menu.range.min;
uiScreenBlit();
}
static int8_t uiDegreesFromScreenPosition(uint8_t cursorPosition, int8_t origin)
{
int8_t offset = LONGLAT_ONE_DEGREE * (uiScreenSignAndTwoDigitsFromPosition(cursorPosition) - origin);
uint8_t fractionalDigit = uiState.screen[cursorPosition + (LAT_FRAC1_POS - LAT_SIGN_POS)] - '0';
if (offset < 0)
return offset - fractionalDigit;
return offset + fractionalDigit;
}
<file_sep>/src/firmware/ceedling
#!/bin/bash
THIS_DIR="$(dirname "$(readlink -f "$0")")";
pushd .;
cd "${THIS_DIR}";
ruby build/ceedling/vendor/ceedling/bin/ceedling $*;
CEEDLING_RESULT=$?;
popd;
exit ${CEEDLING_RESULT};
<file_sep>/src/firmware/src/Platform/Adc.h
#ifndef __CLUCK2SESAME_SRC_PLATFORM_ADC_H
#define __CLUCK2SESAME_SRC_PLATFORM_ADC_H
#include <stdint.h>
#define ADC_CHANNEL_ADCFVR 0b11111001
#define ADC_CHANNEL_CMPFVR 0b11111101
#define ADC_CHANNEL_TEMPERATURE 0b11110001
#define ADC_CHANNEL_DAC 0b11110101
#define ADC_CHANNEL_VSS 0b11101101
#define ADC_CHANNEL_RB1 0b00100101
struct AdcSample
{
uint8_t count;
uint8_t channel;
uint16_t result;
union
{
uint8_t all;
uint8_t any;
struct
{
unsigned int acquisitionTimeMultiple : 4;
unsigned int vrefIsFvr : 1;
};
} flags;
};
extern void adcInitialise(void);
extern void adcSample(struct AdcSample *sample);
#endif
<file_sep>/src/firmware/src/Ui/UiInput.c
#include <xc.h>
#include <stdint.h>
#include "../Platform/Event.h"
#include "../Platform/Buttons.h"
#include "Ui.h"
#define LEFT_BUTTON 0x02
#define RIGHT_BUTTON 0x01
static void uiInputIncrementScreenCharacter(void);
static void uiInputToggleScreenCharacter(void);
static void uiInputMoveCursorToNextOption(void);
static void uiInputOnPreEnter(void);
static void uiInputOnEnter(void);
const struct ButtonBehaviour uiInputIgnore = { };
const struct ButtonBehaviour uiInputIncrementRange =
{
.onPressed = &uiInputIncrementScreenCharacter
};
const struct ButtonBehaviour uiInputToggleRangeOfTwo =
{
.onPressed = &uiInputToggleScreenCharacter
};
const struct ButtonBehaviour uiInputMoveToNextOption =
{
.onPressed = &uiInputMoveCursorToNextOption
};
const struct ButtonBehaviour uiInputEntered =
{
.onPressed = &uiInputOnPreEnter,
.onReleased = &uiInputOnEnter
};
const struct ButtonsBehaviour uiInputIsUninitialised =
{
.left = &uiInputIgnore,
.right = &uiInputIgnore
};
const struct ButtonsBehaviour uiInputIsRange =
{
.left = &uiInputIncrementRange,
.right = &uiInputEntered
};
const struct ButtonsBehaviour uiInputIsRangeOfTwo =
{
.left = &uiInputToggleRangeOfTwo,
.right = &uiInputEntered
};
const struct ButtonsBehaviour uiInputIsOptions =
{
.left = &uiInputMoveToNextOption,
.right = &uiInputEntered
};
const struct ButtonsBehaviour uiInputIsStatusScreen =
{
.left = &uiInputIgnore,
.right = &uiInputEntered
};
void uiInputOnButtonsPressed(const struct Event *event)
{
const struct ButtonsPressed *pressed = (const struct ButtonsPressed *) event->args;
if (pressed->mask & LEFT_BUTTON)
uiState.flags.bits.isLeftButtonPressed = 1;
if (pressed->mask & RIGHT_BUTTON)
uiState.flags.bits.isRightButtonPressed = 1;
if (!uiState.flags.bits.isButtonPressPreventedFromTurningOnScreen)
{
if (!uiState.flags.bits.isScreenOn)
{
uiScreenOn();
uiState.flags.bits.isButtonPressTurningOnScreen = 1;
uiState.flags.bits.isScreenTimeoutDisabled = 1;
return;
}
uiState.flags.bits.isButtonPressTurningOnScreen = 0;
uiState.flags.bits.isScreenTimeoutDisabled = 1;
}
if ((pressed->mask & LEFT_BUTTON) && uiState.input.buttons->left->onPressed)
uiState.input.buttons->left->onPressed();
if ((pressed->mask & RIGHT_BUTTON) && uiState.input.buttons->right->onPressed)
uiState.input.buttons->right->onPressed();
}
void uiInputOnButtonsReleased(const struct Event *event)
{
const struct ButtonsReleased *released = (const struct ButtonsReleased *) event->args;
if (released->mask & LEFT_BUTTON)
{
uiState.flags.bits.isLeftButtonPressed = 0;
if (!uiState.flags.bits.isButtonPressTurningOnScreen && uiState.input.buttons->left->onReleased)
uiState.input.buttons->left->onReleased();
}
if (released->mask & RIGHT_BUTTON)
{
uiState.flags.bits.isRightButtonPressed = 0;
if (!uiState.flags.bits.isButtonPressTurningOnScreen && uiState.input.buttons->right->onReleased)
uiState.input.buttons->right->onReleased();
}
if (!uiState.flags.bits.isButtonPressPreventedFromTurningOnScreen && !uiState.flags.bits.isLeftButtonPressed && !uiState.flags.bits.isRightButtonPressed)
uiScreenStartTimeout();
}
static void uiInputIncrementScreenCharacter(void)
{
if (uiState.input.cursorPosition >= sizeof(uiState.screen))
return;
if (++uiState.screen[uiState.input.cursorPosition] > uiState.input.menu.range.max)
uiState.screen[uiState.input.cursorPosition] = uiState.input.menu.range.min;
uiScreenBlit();
}
static void uiInputToggleScreenCharacter(void)
{
if (uiState.input.cursorPosition >= sizeof(uiState.screen))
return;
if (uiState.screen[uiState.input.cursorPosition] == uiState.input.menu.range.max)
uiState.screen[uiState.input.cursorPosition] = uiState.input.menu.range.min;
else
uiState.screen[uiState.input.cursorPosition] = uiState.input.menu.range.max;
uiScreenBlit();
}
static void uiInputMoveCursorToNextOption(void)
{
if (uiState.input.cursorPosition >= sizeof(uiState.screen))
return;
uiState.screen[uiState.input.cursorPosition] = ' ';
if (++uiState.input.selectedOptionIndex >= sizeof(uiState.input.menu.options.cursorPositions))
uiState.input.selectedOptionIndex = 0;
uiState.input.cursorPosition = uiState.input.menu.options.cursorPositions[uiState.input.selectedOptionIndex];
if (uiState.input.cursorPosition >= sizeof(uiState.screen))
{
uiState.input.cursorPosition = uiState.input.menu.options.cursorPositions[0];
uiState.input.selectedOptionIndex = 0;
}
uiState.screen[uiState.input.cursorPosition] = '>';
uiScreenBlit();
}
static void uiInputOnPreEnter(void)
{
if (uiState.input.onPreEnter)
uiState.input.onPreEnter();
}
static void uiInputOnEnter(void)
{
if (uiState.input.onEnter)
uiState.input.onEnter();
}
<file_sep>/src/firmware/tests/Platform/Motor/__TestMotorOff.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/Motor.h"
#include "MotorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Motor/MotorInitialise.c")
TEST_FILE("Platform/Motor/MotorEnableDisable.c")
TEST_FILE("Platform/Motor/MotorOnOff.c")
void onBeforeTest(void)
{
motorFixtureSetUp();
motorInitialise();
}
void onAfterTest(void)
{
motorFixtureTearDown();
}
void test_motorOff_called_expectCcpLimitIsSameValue(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
uint8_t originalCcpr1h = CCPR1H;
uint8_t originalCcpr1l = CCPR1L;
motorOff();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1h, CCPR1H, "CCPR1H");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(originalCcpr1l, CCPR1L, "CCPR1L");
}
void test_motorOff_called_expectAllPwmOutputsAreDisabled(void)
{
ensureMotorFullyEnabled();
CWG1STR = anyByteWithMaskClear(STEERING_MASK);
uint8_t originalCwg1strWithClearSteering = CWG1STR;
motorOn(anyEncoderCount());
motorOff();
TEST_ASSERT_EQUAL_UINT8(originalCwg1strWithClearSteering, CWG1STR);
}
void test_motorOff_calledWhenMotorAlreadyOff_expectMotorStoppedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStoppedCalls);
}
void test_motorOff_called_expectMotorStoppedEventIsPublishedWithSameRequestedCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyEncoderCount();
motorOn(count);
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.requestedCount, "Count");
}
void test_motorOff_calledWhenTurningClockwise_expectMotorStoppedEventIsPublishedWithTmr1AsActualCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyClockwiseCount();
motorOn(count);
TMR1H = (uint8_t) ((count >> 8) & 0xff);
TMR1L = (uint8_t) ((count >> 0) & 0xff);
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.actualCount, "Count");
}
void test_motorOff_calledWhenTurningAntiClockwise_expectMotorStoppedEventIsPublishedWithTmr1AsActualCount(void)
{
ensureMotorFullyEnabled();
int16_t count = anyAntiClockwiseCount();
motorOn(count);
int16_t negatedCount = -count;
TMR1H = (uint8_t) ((negatedCount >> 8) & 0xff);
TMR1L = (uint8_t) ((negatedCount >> 0) & 0xff);
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_INT16_MESSAGE(count, onMotorStoppedArgs.actualCount, "Count");
}
void test_motorOff_calledWhenNoFaults_expectMotorStoppedEventIsPublishedWithClearFaults(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 0;
PIR2bits.C1IF = 0;
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, onMotorStoppedArgs.fault.all, "Fault");
}
void test_motorOff_calledWhenEncoderOverflowed_expectMotorStoppedEventIsPublishedWithEncoderOverflowFault(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedArgs.fault.encoderOverflow, "Fault");
}
void test_motorOff_calledWhenEncoderOverflowedAndAlreadyStopped_expectMotorStoppedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
CWG1STR &= ~STEERING_MASK;
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStoppedCalls);
}
void test_motorOff_calledWhenEncoderOverflowed_expectTimer1InterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
motorOff();
TEST_ASSERT_FALSE(PIR4bits.TMR1IF);
}
void test_motorOff_calledWhenEncoderOverflowedAndAlreadyOff_expectTimer1InterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR4bits.TMR1IF = 1;
CWG1STR &= ~STEERING_MASK;
motorOff();
TEST_ASSERT_FALSE(PIR4bits.TMR1IF);
}
void test_motorOff_calledWhenCurrentLimited_expectMotorStoppedEventIsPublishedWithCurrentLimitedFault(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedCalls, "Calls");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(1, onMotorStoppedArgs.fault.currentLimited, "Fault");
}
void test_motorOff_calledWhenCurrentLimitedAndAlreadyOff_expectMotorStoppedEventIsNotPublished(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
CWG1STR &= ~STEERING_MASK;
motorOff();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, onMotorStoppedCalls);
}
void test_motorOff_calledWhenCurrentLimited_expectCurrentSenseComparatorInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
motorOff();
TEST_ASSERT_FALSE(PIR2bits.C1IF);
}
void test_motorOff_calledWhenCurrentLimitedAndAlreadyOff_expectCurrentSenseComparatorInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR2bits.C1IF = 1;
CWG1STR &= ~STEERING_MASK;
motorOff();
TEST_ASSERT_FALSE(PIR2bits.C1IF);
}
void test_motorOff_called_expectCwgShutdownInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR7bits.CWG1IF = 1;
motorOff();
TEST_ASSERT_FALSE(PIR7bits.CWG1IF);
}
void test_motorOff_calledWhenAlreadyOff_expectCwgShutdownInterruptFlagIsCleared(void)
{
ensureMotorFullyEnabled();
motorOn(anyEncoderCount());
PIR7bits.CWG1IF = 1;
motorOff();
CWG1STR &= ~STEERING_MASK;
TEST_ASSERT_FALSE(PIR7bits.CWG1IF);
}
// TODO: motorOff() - PWM stops increasing (no more schedules)
// TODO: MOTOR_STOPPED when timeout - expect fault.encoderTimeout set
<file_sep>/src/firmware/tests/Door/TestDoorOnSunEventsChanged.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/Event.h"
#include "Platform/NvmSettings.h"
#include "ApplicationNvmSettings.h"
#include "Door.h"
#include "DoorFixture.h"
#include "../Fixture.h"
#include "../NonDeterminism.h"
#include "../NvmSettingsFixture.h"
TEST_FILE("Door/DoorInitialise.c")
TEST_FILE("Door/DoorCalibrate.c")
TEST_FILE("Door/DoorOnAborted.c")
TEST_FILE("Door/DoorOnOpenScheduleActioned.c")
TEST_FILE("Door/DoorOnCloseScheduleActioned.c")
TEST_FILE("Door/DoorOnMotorStopped.c")
TEST_FILE("Door/DoorOnMotorEnabled.c")
static void publishAnySunEventsChanged(void);
void onBeforeTest(void)
{
doorFixtureInitialise();
}
void onAfterTest(void)
{
doorFixtureShutdown();
}
void test_sunEventsChanged_onPublishedWhenDoorIsSunEventDriven_expectScheduleIsAddedForOpeningTimeOfSunrise(void)
{
stubNvmSettingsForSunEventDrivenModeWithOffsets(0, 0);
struct SunEventsChanged sunEvents;
stubAnySunEvents(&sunEvents);
struct FarSchedule expectedOpeningSchedule =
{
.time =
{
.hour = sunEvents.sunrise.hour,
.minute = sunEvents.sunrise.minute
},
.eventType = DOOR_OPEN_SCHEDULE_ACTIONED
};
publishSunEventsChanged(&sunEvents);
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 1);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedOpeningSchedule,
farSchedulerAddArgs[0]);
}
void test_sunEventsChanged_onPublishedWhenDoorIsSunEventDriven_expectPreviousScheduleIsRemovedBeforeAddingNewDoorOpeningTime(void)
{
stubNvmSettingsForSunEventDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 1, "Calls");
TEST_ASSERT_EQUAL(farSchedulerAddArgs[0], farSchedulerRemoveArgs[0]);
TEST_ASSERT_TRUE(farSchedulerRemoveSequence[0] < farSchedulerAddSequence[0]);
}
static void publishAnySunEventsChanged(void)
{
struct SunEventsChanged sunEvents;
stubAnySunEvents(&sunEvents);
publishSunEventsChanged(&sunEvents);
}
void test_sunEventsChanged_onPublishedWhenDoorIsSunEventDriven_expectScheduleIsAddedForClosingTimeOfSunset(void)
{
stubNvmSettingsForSunEventDrivenModeWithOffsets(0, 0);
struct SunEventsChanged sunEvents;
stubAnySunEvents(&sunEvents);
struct FarSchedule expectedClosingSchedule =
{
.time =
{
.hour = sunEvents.sunset.hour,
.minute = sunEvents.sunset.minute
},
.eventType = DOOR_CLOSE_SCHEDULE_ACTIONED
};
publishSunEventsChanged(&sunEvents);
dispatchAllEvents();
TEST_ASSERT_TRUE(farSchedulerAddCalls >= 2);
assertFarSchedulesAreEqualWithAnyNonNullArgs(
&expectedClosingSchedule,
farSchedulerAddArgs[1]);
}
void test_sunEventsChanged_onPublishedWhenDoorIsSunEventDriven_expectPreviousScheduleIsRemovedBeforeAddingNewDoorClosingTime(void)
{
stubNvmSettingsForSunEventDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 2, "Calls");
TEST_ASSERT_EQUAL(farSchedulerAddArgs[1], farSchedulerRemoveArgs[1]);
TEST_ASSERT_TRUE(farSchedulerRemoveSequence[1] < farSchedulerAddSequence[1]);
}
void test_sunEventsChanged_onPublishedWhenDoorIsManuallyDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForManuallyDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_sunEventsChanged_onPublishedWhenDoorIsManuallyDriven_expectSchedulesAreNotRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForManuallyDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerRemoveCalls);
}
void test_sunEventsChanged_onPublishedWhenDoorIsTimeDriven_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForTimeDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_sunEventsChanged_onPublishedWhenDoorIsTimeDriven_expectSchedulesAreNotRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForTimeDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerRemoveCalls);
}
void test_sunEventsChanged_onPublishedWhenDoorIsUnspecifiedMode_expectSchedulesAreNotAddedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForUnspecifiedMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerAddCalls);
}
void test_sunEventsChanged_onPublishedWhenDoorIsUnspecifiedMode_expectSchedulesAreNotRemovedForOpeningAndClosingTimes(void)
{
stubNvmSettingsForUnspecifiedMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, farSchedulerRemoveCalls);
}
void test_sunEventsChanged_onPublished_expectDoorOpeningSchedulePointerIsSharedAmongstModes(void)
{
stubNvmSettingsForTimeDrivenMode();
publishDateChanged();
dispatchAllEvents();
stubNvmSettingsForSunEventDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerAddCalls >= 4, "Add");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerAddArgs[0] == farSchedulerAddArgs[2], "Ptr Add");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 4, "Remove");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveArgs[0] == farSchedulerRemoveArgs[2], "Ptr Remove");
}
void test_sunEventsChanged_onPublished_expectDoorClosingSchedulePointerIsSharedAmongstModes(void)
{
stubNvmSettingsForTimeDrivenMode();
publishDateChanged();
dispatchAllEvents();
stubNvmSettingsForSunEventDrivenMode();
publishAnySunEventsChanged();
dispatchAllEvents();
TEST_ASSERT_TRUE_MESSAGE(farSchedulerAddCalls >= 4, "Add");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerAddArgs[1] == farSchedulerAddArgs[1], "Ptr Add");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveCalls >= 4, "Remove");
TEST_ASSERT_TRUE_MESSAGE(farSchedulerRemoveArgs[3] == farSchedulerRemoveArgs[3], "Ptr Remove");
}
<file_sep>/src/firmware/tests/Platform/PeriodicMonitor/TestPeriodicMonitor.c
#include <xc.h>
#include <stdint.h>
#include <unity.h>
#include "Platform/PeriodicMonitor.h"
#include "PeriodicMonitorFixture.h"
#include "../../Fixture.h"
#include "../../NonDeterminism.h"
TEST_FILE("Platform/Event.c")
TEST_FILE("Platform/Clock/ClockInitialise.c")
TEST_FILE("Platform/Clock/ClockGetSetNow.c")
TEST_FILE("Platform/PeriodicMonitor.c")
static void timeChanged_onPublishedNumberOfTimes_expectTimestampIs(uint8_t numberOfTimes, uint8_t expectedTimestamp);
static void publishTimeChangedAndDispatchToEventHandlers(void);
static uint8_t onAdcSampleExpectedPmd0;
static void mockAdcSampleForFixedVoltageReferenceModuleEnabledExpectation(struct AdcSample *sample);
static uint8_t onAdcSampleExpectedFvrcon;
static void mockAdcSampleForFvrconExpectation(struct AdcSample *sample);
static uint8_t spyAdcSampleForChannelsResults[3];
static void spyAdcSampleForChannels(struct AdcSample *sample);
void onBeforeTest(void)
{
periodicMonitorFixtureSetUp();
}
void onAfterTest(void)
{
periodicMonitorFixtureTearDown();
}
void test_timeChanged_onPublishedWithNonFourMinuteIntervalSchedule_expectMonitoredParamtersSampledEventIsNotPublished(void)
{
mockOnMonitoredParametersSampled();
struct Time now =
{
.hour = anyByteLessThan(24),
.second = anyByteLessThan(60)
};
for (uint8_t minute = 0; minute < 60; minute++)
{
uint8_t offset = minute % 4;
if (offset == 1)
continue;
now.minute = minute;
publishTimeChanged(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(0, monitoredParametersSampledCalls);
}
}
void test_timeChanged_onPublishedWithFourMinuteIntervalSchedule_expectMonitoredParamtersSampledEventIsPublished(void)
{
mockOnMonitoredParametersSampled();
struct Time now =
{
.hour = anyByteLessThan(24),
.second = anyByteLessThan(60)
};
for (uint8_t i = 1, minute = 1; minute < 60; minute += 4, i++)
{
now.minute = minute;
publishTimeChanged(&now);
dispatchAllEvents();
TEST_ASSERT_EQUAL_UINT8(i, monitoredParametersSampledCalls);
}
}
void test_timeChanged_onPublishedForFirstTime_expectTimestampIsZero(void)
{
timeChanged_onPublishedNumberOfTimes_expectTimestampIs(1, 0);
}
static void timeChanged_onPublishedNumberOfTimes_expectTimestampIs(uint8_t numberOfTimes, uint8_t expectedTimestamp)
{
mockOnMonitoredParametersSampled();
struct Time now =
{
.hour = anyByteLessThan(24),
.minute = 1,
.second = anyByteLessThan(60)
};
for (uint8_t i = 0; i < numberOfTimes; i++)
{
publishTimeChanged(&now);
TMR0L = anyByte();
dispatchAllEvents();
}
TEST_ASSERT_NOT_NULL(monitoredParametersSampled);
TEST_ASSERT_EQUAL_UINT8_MESSAGE(numberOfTimes, monitoredParametersSampledCalls, "CALLS");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(expectedTimestamp, monitoredParametersSampled->timestamp, "STAMP");
}
void test_timeChanged_onPublishedForSecondTime_expectTimestampIs240(void)
{
timeChanged_onPublishedNumberOfTimes_expectTimestampIs(2, 240);
}
void test_timeChanged_onPublishedForThirdTime_expectTimestampIs480Modulo256(void)
{
timeChanged_onPublishedNumberOfTimes_expectTimestampIs(3, 224);
}
void test_timeChanged_onPublishedForThirdTime_expectTimestampIs720Modulo256(void)
{
timeChanged_onPublishedNumberOfTimes_expectTimestampIs(4, 208);
}
void test_timeChanged_onPublishedForSeventeenthTime_expectTimestampRollsOverToZero(void)
{
timeChanged_onPublishedNumberOfTimes_expectTimestampIs(17, 0);
}
void test_timeChanged_onPublishedWhenRb0IsLow_expectIsVddRegulatedIsFalse(void)
{
mockOnMonitoredParametersSampled();
static const struct Time now = { .minute = 1 };
publishTimeChanged(&now);
ANSELB = 0;
TRISB = 0;
LATB = anyByteWithMaskClear(_PORTB_RB0_MASK);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(monitoredParametersSampled);
TEST_ASSERT_FALSE(monitoredParametersSampled->flags.isVddRegulated);
}
void test_timeChanged_onPublishedWhenRb0IsHigh_expectIsVddRegulatedIsTrue(void)
{
mockOnMonitoredParametersSampled();
static const struct Time now = { .minute = 1 };
publishTimeChanged(&now);
ANSELB = 0;
TRISB = 0;
LATB = anyByteWithMaskSet(_PORTB_RB0_MASK);
dispatchAllEvents();
TEST_ASSERT_NOT_NULL(monitoredParametersSampled);
TEST_ASSERT_TRUE(monitoredParametersSampled->flags.isVddRegulated);
}
void test_timeChanged_onPublished_expectFixedVoltageReferenceIsSampled(void)
{
mockOnMonitoredParametersSampled();
struct AdcSample sample =
{
.channel = ADC_CHANNEL_ADCFVR,
.count = 8,
.result = anyWord(),
.flags =
{
.vrefIsFvr = 0,
.acquisitionTimeMultiple = 11
}
};
stubAdcSampleFor(&sample);
publishTimeChangedAndDispatchToEventHandlers();
TEST_ASSERT_NOT_NULL(monitoredParametersSampled);
TEST_ASSERT_TRUE(adcSampleCalls >= 1);
TEST_ASSERT_EQUAL_UINT8(sample.result, monitoredParametersSampled->fvr);
}
static void publishTimeChangedAndDispatchToEventHandlers(void)
{
static const struct Time now = { .minute = 1 };
publishTimeChanged(&now);
dispatchAllEvents();
}
void test_timeChanged_onPublished_expectTemperatureSensorIsSampledUsingInternalFixedVoltageReference(void)
{
mockOnMonitoredParametersSampled();
struct AdcSample sample =
{
.channel = ADC_CHANNEL_TEMPERATURE,
.count = 8,
.result = anyWord(),
.flags =
{
.vrefIsFvr = 1,
.acquisitionTimeMultiple = 0
}
};
stubAdcSampleFor(&sample);
publishTimeChangedAndDispatchToEventHandlers();
TEST_ASSERT_NOT_NULL(monitoredParametersSampled);
TEST_ASSERT_TRUE(adcSampleCalls >= 1);
TEST_ASSERT_EQUAL_UINT8(sample.result, monitoredParametersSampled->temperature);
}
void test_timeChanged_onPublished_expectFixedVoltageReferenceModuleIsDisabledBeforeCompletion(void)
{
PMD0 = anyByteWithMaskClear(_PMD0_FVRMD_MASK);
uint8_t originalPmd0 = PMD0;
publishTimeChangedAndDispatchToEventHandlers();
TEST_ASSERT_EQUAL_UINT8(originalPmd0 | _PMD0_FVRMD_MASK, PMD0);
}
void test_timeChanged_onPublished_expectFixedVoltageReferenceModuleIsEnabledDuringSampling(void)
{
PMD0 = anyByteWithMaskSet(_PMD0_FVRMD_MASK);
onAdcSampleExpectedPmd0 = PMD0 & ~_PMD0_FVRMD_MASK;
onAdcSample = &mockAdcSampleForFixedVoltageReferenceModuleEnabledExpectation;
publishTimeChangedAndDispatchToEventHandlers();
}
static void mockAdcSampleForFixedVoltageReferenceModuleEnabledExpectation(struct AdcSample *sample)
{
TEST_ASSERT_EQUAL_UINT8(onAdcSampleExpectedPmd0, PMD0);
}
void test_timeChanged_onPublished_expectFixedVoltageReferenceIs2048mvAndTemperatureRangeIsHighDuringSampling(void)
{
PMD0 = anyByteWithMaskSet(_PMD0_FVRMD_MASK);
FVRCON = anyByte();
onAdcSampleExpectedFvrcon = _FVRCON_ADFVR1_MASK | _FVRCON_FVRRDY_MASK | _FVRCON_FVREN_MASK | _FVRCON_TSRNG_MASK | _FVRCON_TSEN_MASK;
onAdcSample = &mockAdcSampleForFvrconExpectation;
publishTimeChangedAndDispatchToEventHandlers();
}
static void mockAdcSampleForFvrconExpectation(struct AdcSample *sample)
{
TEST_ASSERT_EQUAL_UINT8(onAdcSampleExpectedFvrcon, FVRCON);
}
void test_timeChanged_onPublished_expectSamplingIsFixedVoltageReferenceThenTemperatureToAllowForStabilisationPeriods(void)
{
spyAdcSampleForChannelsResults[0] = ADC_CHANNEL_CMPFVR;
spyAdcSampleForChannelsResults[1] = ADC_CHANNEL_CMPFVR;
onAdcSample = &spyAdcSampleForChannels;
publishTimeChangedAndDispatchToEventHandlers();
TEST_ASSERT_EQUAL_UINT8_MESSAGE(ADC_CHANNEL_ADCFVR, spyAdcSampleForChannelsResults[0], "FVR");
TEST_ASSERT_EQUAL_UINT8_MESSAGE(ADC_CHANNEL_TEMPERATURE, spyAdcSampleForChannelsResults[1], "TEMP");
}
static void spyAdcSampleForChannels(struct AdcSample *sample)
{
if (sample && adcSampleCalls < sizeof(spyAdcSampleForChannelsResults))
spyAdcSampleForChannelsResults[adcSampleCalls] = sample->channel;
adcSampleCalls++;
}
| 049c419a7ccddacc472eb69179adf02aeee18f0b | [
"Markdown",
"Makefile",
"Python",
"Text",
"C",
"Shell"
] | 241 | C | pete-restall/Cluck2Sesame | 4a2e749d3e94178fb96501d92d3008cae0a07005 | f74f01d04ba36a0ec9e0f5a8f6f685dc08ea27a9 |
refs/heads/master | <repo_name>Marlonalves/NodeJsTranslateAndSentiment<file_sep>/index.js
var Sentiment = require('sentiment');
var translate = require('node-google-translate-skidz');
module.exports.translateUrl = function (req,res) {
translate({
text: req.query.texto,
source: 'es',
target: 'en'
}, function(result) {
res.send(result.translation);
});
}
module.exports.translateBody = function (req,res) {
translate({
text: req.body.texto,
source: req.body.linguaEntrada,
target: req.body.linguaSaida
}, function(result) {
var sentiment = new Sentiment();
var resultFinal = sentiment.analyze(result.translation, 'en');
var o = []
o.push(result.translation)
o.push((resultFinal))
res.send(JSON.stringify(o));
});
}
module.exports.sentimentText = function (req,res) {
var sentiment = new Sentiment();
var result = sentiment.analyze('dogs are amazing and cute and nice', 'en');
res.send(result)
}
module.exports.log = function (msg) {
console.log(msg);
};
<file_sep>/app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var index = require('./index.js');
app.use(bodyParser.json());
app.get('/translate', function(req, res) { index.translateUrl(req,res)});
app.get('/sentiment', function(req, res) { index.sentimentText(req,res)});
app.post('/translate', function(req, res) {
index.translateBody(req,res)
//res.send('ts')
});
app.listen(8000, function() {
console.log('Servidor rodando na porta 8000.');
}); | 6cb5a03539761ac83536a501f5c0e3292fda5b33 | [
"JavaScript"
] | 2 | JavaScript | Marlonalves/NodeJsTranslateAndSentiment | f508a9c8f994e7dfaed3f63ce4bd0aee70bb9c6a | b5ce99cfed6e8b1decf72eca51810e9e0e1d44ed |
refs/heads/master | <file_sep>/**
* @author yangbin
* @date 2019/8/26
* @Description: read opts col/row/file
*/
const fs = require('fs');
const chalk = require('chalk');
const sourceMap = require('source-map');
let sourcesPathMap = {}
let resolvePath = function (filePath) {
return filePath.replace(/\.[\.\/]+/g, "");
}
const readFile = function (file) {
return new Promise(function (resolve, reject) {
fs.exists(file, function (exist) {
if (exist) {
fs.readFile(file, {encoding: 'utf-8'}, function (error, data) {
if (error) {
console.log(chalk.red(err));
return reject(error);
}
let fileContent = data.toString();
let fileObj = JSON.parse(fileContent);
let sources = fileObj['sources'];
sources.map(item => {
sourcesPathMap[resolvePath(item)] = item
})
resolve({fileContent, fileObj, sources});
});
} else {
console.log(chalk.red('filepath is error'));
return reject(error);
}
});
});
};
// 读取map文件
async function readMapFile (file, line, column) {
const mapFile = await readFile(file);
const consumer = await new sourceMap.SourceMapConsumer(mapFile.fileContent);
const rst = consumer.originalPositionFor({
line: line,
column: column
});
let originSource = sourcesPathMap[rst.source];
let sourcesContent = mapFile.fileObj.sourcesContent[mapFile.sources.indexOf(originSource)];
// 源码组装成数组,方便console.log输出
let lines = sourcesContent.split('\n')
lines = lines.map(item => {
return item+'\n'
})
rst.lines = lines
consumer.destroy()
return rst
}
module.exports = readMapFile
<file_sep>#!/usr/bin/env node
const chalk = require('chalk')
const program = require('commander')
const pkg = require('../package')
const readMapFile = require('../lib/index')
// 版本
program
.version(pkg.version, '-v, --version')
.description(chalk.yellow('Start restoring error codes...'))
.usage('[options]')
// 参数介绍
program
.option('-f, --source-file', 'The file path of source map')
.option('-l, --line', 'The line number of pros error')
.option('-c, --column', 'The column number of pros error')
// 帮组
program.on('--help', () => {
console.log()
console.log(` Run ${chalk.cyan(`sm --help`)} for detailed usage of given command.`)
console.log()
})
// 执行参数
program.parse(process.argv)
// 命令参数缺一不可
const optionsLen = program.args.length
if(optionsLen != 3){
console.log(chalk.red('Please check the options'))
program.help()
return
}
// 获取命令行文件路径,行,列,并输入源码信息
const file = program.args[0]
const line = Number(program.args[1])
const column = Number(program.args[2])
readMapFile(file, line, column).then(({source, line, column, name, lines}) => {
// ~~~~~~~~~~~~~~~ 命令行输出
console.log(chalk.blue('★') + chalk.greenBright('sourceFilePath') + ': ' + chalk.yellowBright(source));
console.log(chalk.blue('★') + chalk.greenBright('line') + ': ' + chalk.yellowBright(line));
console.log(chalk.blue('★') + chalk.greenBright('column') + ': ' + chalk.yellowBright(column));
console.log(chalk.blue('★') + chalk.greenBright('name') + ': ' + chalk.yellowBright(name));
console.log('--------start 错误代码--------')
console.log(
chalk.cyanBright(lines.slice((line-5 < 0) ? 0 : (line-5), line-1).join('')) +
chalk.red('*' + lines[line-1]) +
chalk.cyanBright(lines.slice(line, line+5).join(''))
)
console.log('--------end 错误代码--------')
}).catch(err => {
console.log(chalk.red(err))
program.help()
})
<file_sep># hyapp-sourcemap
a tools of sourceMap
``` html
Usage: sm [options]
option:
* '-f, --source-file', 'The file path of source map'
* '-l, --line', 'The line number of pros error'
* '-c, --column', 'The column number of pros error'
* '-h, --help'
```
``` javascript
example:
sm -f ./demo/dist/app.min.js.map -l 1 -c 1023
output:
★sourceFilePath: webpack:///main.js
★line: 8
★column: 14
★name: aaa
--------start 错误代码--------
function test2 () {
console.log('test2')
}
function testError () {
* console.log(aaa)
}
function test3 () {
console.log('test3')
}
function test4 () {
--------end 错误代码--------
```
<file_sep>/**
* @author yangbin
* @date 2019/8/27
* @Description: webpack打包配置
*/
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: {
app: './main.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].min.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
},
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
sourceMap: true,
}),
],
},
devtool: '#source-map'
}
<file_sep>function test1 () {
console.log('test1')
}
function test2 () {
console.log('test2')
}
function testError () {
console.log(aaa)
}
function test3 () {
console.log('test3')
}
function test4 () {
console.log('test4')
}
test1()
test2()
test3()
test4()
testError()
| 33edf5e8dc8a702120911f26f11b486dae12f5ac | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | torresyb/hyapp-sourcemap | 45b9bb3d608217d9ce9979a4a6fc5c08dc455fa1 | ecf504943c360df7f576a1abc4c5f7904bb3ebcd |
refs/heads/master | <repo_name>ziyadrahman/noQAdmin<file_sep>/app/src/main/java/com/item.java
package com;
public class item {
private String timeSlot;
private String uid;
public item() {
}
public item(String timeSlot, String uid) {
this.timeSlot = timeSlot;
this.uid = uid;
}
public String getTimeSlot() {
return timeSlot;
}
public String getUid() {
return uid;
}
}
| 430585d291a576c1e083239bd731f651eaa5c8c4 | [
"Java"
] | 1 | Java | ziyadrahman/noQAdmin | 5b6c4c3fb112255f7c2e2bc92395ef4c4add93c1 | cb75324a7eb14dd02031f745a22b6e6ff818dfa6 |
refs/heads/gh-pages | <repo_name>Wynncraft/WynncraftFaces<file_sep>/wall.js
/**
* @copyright Wynncraft 2013, 2014
* @author <NAME> <<EMAIL>>
*/
$(document).ready(function() {
// Json Fetch
$.getJSON(
'http://api.wynncraft.com/public_api.php?action=onlinePlayers',
function(data) {
$.each(data, function(key, obj) {
var server = key;
$.each(obj, function(key, obj) {
var player = obj;
// Check if player defined
if (player.length !== 0 &&
server !== "request") {
$('<img/>', {
id: player,
src: 'http://api.wynncraft.com/avatar/' +
player +
'/64.png',
"data-toggle": 'tooltip',
"data-original-title": player +
' online on server ' +
server,
"data-placement": "top"
}).appendTo('#online');
}
});
});
// Set tooltips
$('[data-toggle=tooltip]').tooltip();
});
});
<file_sep>/README.md
WynncraftFaces
==============
Demonstrating use of the status API fetch
## Uses the Wynncraft API
This project uses the Wynncraft public web-API, more information can be found at http://docs.wynncraft.com/.
| 2a6fa2829d3986867cecc71d5efb06a10d7e1ef0 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Wynncraft/WynncraftFaces | 6778ae09b500631e2ce0f6915d98ba7f6eeb79db | a8472bc6c2bed321055480255d8d1d802c37c11f |
refs/heads/master | <repo_name>xyder/gm-scripts<file_sep>/scripts/Xdr_Imdb_Redirector.user.js
// ==UserScript==
// @name Xdr Imdb Redirector
// @namespace sncco.xdr.gen.imdb.redirect
// @description Removes some get params and redirects to a clean url.
// @require ../libraries/utils.js
// @include *://www.imdb.com/*
// @version 1.0.1
// @grant unsafeWindow
// @credits Xyder
// ==/UserScript==
(function(){
(new XUtils()).redirectPage(window, document, [], true);
})();
<file_sep>/README.md
# gm-scripts
Repository for Greasemonkey scripts.
## Scripts
###### *Xdr Imdb Redirector*
Redirects any imdb page to a version without the url parameters (the ones after the ?).
###### *Xdr Steam Redirector*
Redirects any steam page (from _**store.steampowered.com**_ and _**steamcommunity.com**_) to a version without the url parameters (the ones after the ?). It will keep the '*id*' parameter if exists.
## How to use
Click the name of a file in the Scripts directory and then click the **Raw** button. If you have Greasemonkey installed, a pop-up to install the script will appear.
<br>
_**Note:**_ *All scripts are provided as-is. Anything is permitted. Install at your own risk.*
<file_sep>/libraries/utils.js
/*
Author: Xyder
Version: 1.0.1
*/
function XUtils(){
var self = this;
// if isWhitelist is true it will delete any parameters not in prefixes list
// else it will delete any parameters in prefixes list (considered a blacklist)
self.removeParamsFromUrl = function(prefixes, url, isWhitelist){
var parts = url.split('?');
//if we found at least one parameter after '?'
if(parts.length >= 2){
var urlbase = parts.shift();
//check if any prefixes were specified
if(prefixes == undefined || prefixes.length < 1){
if(isWhitelist){
//delete all params because the whitelist contains no elements
return urlbase;
} else {
//keep all params because the blacklist contains no elements
return url;
}
} else {
var params = parts.join('?').split(/[&;]/g);
var eprefixes = new Array();
//prepare prefixes
for(var i = prefixes.length; i-- > 0;){
eprefixes.push(encodeURIComponent(prefixes[i]) + '=');
}
//cycle parameters
for(var i = params.length; i-- > 0;){
//cycle prefixes
for(var j = eprefixes.length; j-- > 0;){
//check if prefix matches
if(params[i].lastIndexOf(eprefixes[j], 0) !== -1){
if(!isWhitelist){
//found a parameter which is blacklisted
params.splice(i, 1);
break;
}
} else {
if(isWhitelist){
//found a parameter which is not whitelisted
params.splice(i, 1);
break;
}
}
}
}
console.log(params.length);
if(params.length > 0){
return urlbase + '?' + params.join('&');
} else {
return urlbase;
}
}
} else {
//no params found, return url unchanged
return url;
}
}
// function that applies filter to an url parameters and redirects the page to the new url if necessary
self.redirectPage = function(window, document, prefixes, isWhitelist){
var oldUrl = document.location.href;
var newUrl = self.removeParamsFromUrl(prefixes,oldUrl, isWhitelist);
if(oldUrl != newUrl){
window.history.pushState('', document.title, newUrl);
}
}
} | 677a7c84d72ca93215512e7bdd655071a5e011cf | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | xyder/gm-scripts | 83c9ceb7a61f5f400760cd0574835300638c7437 | 131a270e00ee51df1be50e3e68eb5d52344d8d12 |
refs/heads/master | <repo_name>nyanpasu64/corrscope-icon<file_sep>/README.txt
Programmatically generated icons for https://github.com/jimbo1qaz/corrscope.
<file_sep>/icon.py
from dataclasses import dataclass
import numpy as np
from matplotlib.axes import Axes
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.cm import get_cmap
from matplotlib.figure import Figure
cmap = get_cmap("tab10")
order = [0, 3, 2, 1]
cmap = [cmap(x) for x in order].__getitem__
@dataclass
class Config:
dim: int
line_width: float
nline: int
def main():
cfgs = [
#
Config(256, line_width=4, nline=3),
Config(128, line_width=3, nline=3),
Config(96, line_width=2.5, nline=3),
Config(48, line_width=2, nline=3),
Config(32, line_width=2, nline=2),
Config(16, line_width=1, nline=2),
]
for cfg in cfgs:
do_it(cfg)
def do_it(cfg):
DPI = 96
fig = Figure()
FigureCanvasAgg(fig)
ax: Axes = fig.subplots(
1,
1,
subplot_kw=dict(xticks=[], yticks=[]),
gridspec_kw=dict(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0),
)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.set_axis_off()
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
fig.set_dpi(DPI)
fig.set_size_inches(cfg.dim / DPI, cfg.dim / DPI)
# params
tau = 2 * np.pi
NPOINTS = 1000
XMAX = 1
FREQ = 1.3
def lerp(x, y, a: float):
return x * (1 - a) + y * a
def sintau(x):
return np.sin(tau * x)
def costau(x):
return np.cos(tau * x)
gauss = lambda xs, W: np.exp(-(xs / W) ** 2)
cos_win = lambda xs: costau(xs / 4)
def win(xs):
assert xs[0] == -1
assert xs[-1] == 1
W = 0.6
e = 1
return gauss(xs, W) * cos_win(xs) ** e
# plot
xs = np.linspace(-XMAX, XMAX, NPOINTS)
def sinusoid(dx, freq=1, yscale=1):
# sintau
# x: compress=freq, shift=dx
# y: mul=yscale
return lambda xs: sintau((xs - dx) * freq) * yscale
def plot_sinusoid(dx, freq, yscale, alpha, color=None):
func = sinusoid(dx, freq, yscale)
ax.plot(
xs, func(xs) * win(xs), alpha=alpha, color=color, linewidth=cfg.line_width
)
top = "narrow"
blue = "narrow"
top_blue = top == blue
if top_blue:
i = cfg.nline - 1
di = -1
else:
i = 0
di = 1
freqs = np.geomspace(0.2, 1, cfg.nline)
if top == "wide":
freqs = freqs[::-1]
e = 0
for freq in freqs:
plot_sinusoid(0, freq=freq, yscale=freq ** e, alpha=1, color=cmap(i))
i += di
fig.savefig(f"{cfg.dim}.png", transparent=True)
if __name__ == "__main__":
main()
| 49df4ef857f700c9c7c984f4d8d555f0a2801a3b | [
"Python",
"Text"
] | 2 | Text | nyanpasu64/corrscope-icon | 915ed1ea67e1c07e705e55e39eee4fb1a70ccd10 | ab1802f0739b1ea78f9f278b1f42464874b07bf5 |
refs/heads/main | <repo_name>niyalimukherjee/Python_projects<file_sep>/groovingmonkeyproblem.cpp
//C++ implementation of groovingmonkeyproblem by niyalimukherjee
#include"bits/stdc++.h"
using namespace std;
int main()
{
int t,N;
cin>>t;
cin>>N;
int monkeys[N];
for(int i=0;i<N;i++)
{
cin>>monkeys[i];
}
int b[N];
int c=0;
for(int i=0;i<N;i++)
{
b[(i+1)%N]=monkeys[i];
c++;
if(b[i]==monkeys[i])
break;
}
cout<<c<<endl;
}
| 12660fcd0b0f8ff660e152267142e2c02b593c6b | [
"C++"
] | 1 | C++ | niyalimukherjee/Python_projects | 072a939bc5f47d080f761ecd1efa69132de3ec99 | fbaf4fab8cf8cb2f5aa9ac78d7d646199fdef155 |
refs/heads/master | <repo_name>codacy-badger/lokra-auth-service<file_sep>/src/main/java/org/lokra/platform/auth/token/service/RestTokenService.java
package org.lokra.platform.auth.token.service;
import org.lokra.platform.token.client.TokenClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* @author <NAME>
*/
@Service
public class RestTokenService implements ClientDetailsService, TokenStore{
private final TokenClient tokenClient;
@Autowired
public RestTokenService(TokenClient tokenClient) {
this.tokenClient = tokenClient;
}
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
return tokenClient.loadClientDetailsByClientId(clientId);
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
return null;
}
@Override
public OAuth2Authentication readAuthentication(String token) {
return null;
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
return null;
}
@Override
public void removeAccessToken(OAuth2AccessToken token) {
}
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
}
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
return null;
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return null;
}
@Override
public void removeRefreshToken(OAuth2RefreshToken token) {
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
return null;
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
return null;
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
return null;
}
}<file_sep>/src/main/java/org/lokra/platform/auth/configuration/WebProperties.java
package org.lokra.platform.auth.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Web配置
*
* @author <NAME>
*/
@ConfigurationProperties(prefix = "lokra.auth.web")
public class WebProperties extends WebMvcConfigurerAdapter {
}
<file_sep>/src/main/java/org/lokra/platform/auth/AuthorizationServiceApplication.java
package org.lokra.platform.auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author <NAME>
*/
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableFeignClients(basePackages = {
"org.lokra.platform.user.base.client",
"org.lokra.platform.token.client"
})
@EnableSwagger2
@Import({
springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class
})
public class AuthorizationServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServiceApplication.class, args);
}
}
<file_sep>/src/main/java/org/lokra/platform/auth/configuration/OAuth2Properties.java
package org.lokra.platform.auth.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author <NAME>
*/
@ConfigurationProperties(prefix = "lokra.auth.oauth2")
public class OAuth2Properties {
private Jwt jwt;
private TokenStore tokenStore;
private String tokenKeyAccess;
private String checkTokenAccess;
public TokenStore getTokenStore() {
return tokenStore;
}
public void setTokenStore(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
public Jwt getJwt() {
return jwt;
}
public void setJwt(Jwt jwt) {
this.jwt = jwt;
}
public String getTokenKeyAccess() {
return tokenKeyAccess;
}
public void setTokenKeyAccess(String tokenKeyAccess) {
this.tokenKeyAccess = tokenKeyAccess;
}
public String getCheckTokenAccess() {
return checkTokenAccess;
}
public void setCheckTokenAccess(String checkTokenAccess) {
this.checkTokenAccess = checkTokenAccess;
}
public static enum TokenStore {
REST,
REDIS,
IN_MEMORY,
JWT
}
public static class Jwt {
private String password;
private String resource;
private String keyPair;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getKeyPair() {
return keyPair;
}
public void setKeyPair(String keyPair) {
this.keyPair = keyPair;
}
}
}<file_sep>/src/main/java/org/lokra/platform/auth/authorize/controller/AuthorizeController.java
package org.lokra.platform.auth.authorize.controller;
import org.lokra.platform.auth.configuration.AuthorizationServiceProperties;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.security.Principal;
/**
* @author <NAME>
*/
@Controller
@SessionAttributes("authorizationRequest")
public class AuthorizeController {
/**
* Login.
*
* @return html view.
*/
@RequestMapping(value = AuthorizationServiceProperties.LOGIN_PAGE_URL, method = RequestMethod.GET)
public String login() {
return "login";
}
/**
* Logout.
*
* @return html view.
*/
@RequestMapping(value = AuthorizationServiceProperties.LOGOUT_PAGE_URL, method = RequestMethod.GET)
public String logout() {
return "logout";
}
/**
* Confirm access.
*
* @param model Model.
* @param authorizationRequest Authorization request.
* @return html view.
*/
@RequestMapping(value = AuthorizationServiceProperties.CONFIRM_ACCESS_URL, method = {RequestMethod.GET})
public String confirmAccess(Model model, AuthorizationRequest authorizationRequest) {
model.addAttribute("authorizationRequest", authorizationRequest);
return "oauth/confirm_access";
}
/**
* Get user.
*
* @param user Fetch principal user by access token.
* @return Principal user.
*/
@RequestMapping(value = AuthorizationServiceProperties.USER_INFO_URL, method = RequestMethod.GET)
@ResponseBody
public Principal getUser(Principal user) {
return user;
}
}
<file_sep>/src/main/java/org/lokra/platform/auth/configuration/SecurityProperties.java
package org.lokra.platform.auth.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
*/
@ConfigurationProperties(prefix = "lokra.auth.security")
public class SecurityProperties {
private int maximumSessions = 1;
private boolean maxSessionsPreventsLogin = false;
private List<String> ignored = new ArrayList<>();
public int getMaximumSessions() {
return maximumSessions;
}
public void setMaximumSessions(int maximumSessions) {
this.maximumSessions = maximumSessions;
}
public boolean isMaxSessionsPreventsLogin() {
return maxSessionsPreventsLogin;
}
public void setMaxSessionsPreventsLogin(boolean maxSessionsPreventsLogin) {
this.maxSessionsPreventsLogin = maxSessionsPreventsLogin;
}
public List<String> getIgnored() {
return ignored;
}
public void setIgnored(List<String> ignored) {
this.ignored = ignored;
}
}<file_sep>/settings.gradle
rootProject.name = 'lokra-auth-service' | 6c68309b385157f89a66eabc788bd89ca2e25aa3 | [
"Java",
"Gradle"
] | 7 | Java | codacy-badger/lokra-auth-service | aee17c5d81db18d418fdc816282cf52fe40465e5 | 1c68ce308b30c84f90ee35e2c058d0abac8959c7 |
refs/heads/master | <file_sep>package arpeggio;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtils
{
public static KeyPair generateNewKeyPair() {
KeyPairGenerator keyPairGen;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
return null;
}
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
}
public static PublicKey generatePublicKeyFromBytes(byte[] pubKeyBytes) throws CryptoException {
KeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
try {
return KeyFactory.getInstance("RSA").generatePublic(pubKeySpec);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new CryptoException(e);
}
}
public static PrivateKey readPrivateKeyFromFile(String filename) throws CryptoException, IOException {
try{
byte[] privKeyBytes = readFile(filename);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
return keyFactory.generatePrivate(ks);
}
catch (NoSuchAlgorithmException e) {
return null;
}
catch (InvalidKeySpecException e) {
System.out.println("Invalid Key Spec");
return null;
}
}
public static void writePrivateKeyToFile(String filename, PrivateKey key) throws CryptoException {
byte[] privKeyBytes = key.getEncoded();
EncodedKeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
try {
writeFile(filename, ks.getEncoded());
} catch (IOException e) {
throw new CryptoException(e);
}
}
public static PublicKey readPublicKeyFromFile(String filename) throws CryptoException, IOException {
byte[] pubKeyBytes;
pubKeyBytes = readFile(filename);
return generatePublicKeyFromBytes(pubKeyBytes);
}
public static void writePublicKeyToFile(String filename, PublicKey key) throws CryptoException {
byte[] pubKeyBytes = key.getEncoded();
EncodedKeySpec ks = new X509EncodedKeySpec(pubKeyBytes);
try {
writeFile(filename, ks.getEncoded());
} catch (IOException e) {
throw new CryptoException(e);
}
}
public static byte[] readFile(String filename) throws IOException {
FileInputStream in = null;
File file = new File(filename);
byte[] contents = null;
try {
in = new FileInputStream(file);
contents = new byte[(int)file.length()];
in.read(contents);
}
finally {
if (in != null) {
in.close();
}
}
return contents;
}
public static void writeFile(String filename, byte[] contents)
throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
out.write(contents);
}
finally {
if (out != null) {
out.close();
}
}
}
public static Message encryptString(PublicKey pubKey, String input) throws CryptoException, UnsupportedEncodingException {
return encrypt(pubKey, input.getBytes("UTF-8"));
}
public static Message encryptObject(PublicKey pubKey, Serializable object) throws CryptoException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream ois;
try {
ois = new ObjectOutputStream(baos);
ois.writeObject(object);
ois.close();
baos.close();
} catch (IOException e) {
throw new CryptoException(e);
}
return encrypt(pubKey, baos.toByteArray());
}
public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException
{
Message message = new Message();
message.pubKey = pubKey.getEncoded();
KeyGenerator keyGen;
try {
keyGen = KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
throw new CryptoException(e);
}
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
try {
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded());
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
AlgorithmParameters params = aesCipher.getParameters();
message.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
message.ciphertext = aesCipher.doFinal(input);
}
catch (NoSuchAlgorithmException |
NoSuchPaddingException |
InvalidKeyException |
IllegalBlockSizeException |
BadPaddingException |
InvalidParameterSpecException e) {
throw new CryptoException(e);
}
return message;
}
public static Serializable decryptObject(PrivateKey privKey, Message message) throws CryptoException {
byte[] messageBytes = decrypt(privKey, message);
ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(bais);
Object o = ois.readObject();
ois.close();
bais.close();
return (Serializable) o;
} catch (IOException | ClassNotFoundException e) {
throw new CryptoException(e);
}
}
public static String decryptString(PrivateKey privKey, Message message) throws CryptoException {
byte[] messageBytes = decrypt(privKey, message);
String text;
try {
text = new String(messageBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CryptoException(e);
}
return text;
}
public static byte[] decrypt(PrivateKey privKey, Message message) throws CryptoException
{
try {
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] secretKeyBytes = rsaCipher.doFinal(message.sessionKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
KeySpec ks = new SecretKeySpec(secretKeyBytes, "AES");
SecretKey secretKey = keyFactory.generateSecret(ks);
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(message.iv));
byte[] messageBytes = aesCipher.doFinal(message.ciphertext);
return messageBytes;
}
catch (NoSuchAlgorithmException |
NoSuchPaddingException |
InvalidKeyException |
IllegalBlockSizeException |
BadPaddingException |
InvalidKeySpecException |
InvalidAlgorithmParameterException e) {
throw new CryptoException(e);
}
}
}
<file_sep>arpeggio
========
Peer to peer messaging service built on top of Chord
<file_sep>package arpeggio;
import java.security.PublicKey;
import java.util.Arrays;
import de.uniba.wiai.lspi.chord.service.Key;
public class HashKey implements Key {
private byte[] key;
public HashKey(byte[] key) {
this.key = key;
}
public HashKey(PublicKey pkey) {
this.key = pkey.getEncoded();
}
@Override
public boolean equals(Object o) {
if (o instanceof HashKey) {
return Arrays.equals(((HashKey) o).key, key);
}
return false;
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public byte[] getBytes() {
return key;
}
}
<file_sep>package arpeggio;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.Set;
import de.uniba.wiai.lspi.chord.data.URL;
import de.uniba.wiai.lspi.chord.service.Chord;
import de.uniba.wiai.lspi.chord.service.ServiceException;
import de.uniba.wiai.lspi.chord.service.impl.ChordImpl;
public class Server implements Runnable {
private Socket socket;
private Chord chord;
public Server(Chord chord, Socket socket) {
this.socket = socket;
this.chord = chord;
}
@Override
public void run() {
try {
Request request = readRequest();
writeResponse(request.handle(chord));
}
catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
}
catch (ClassNotFoundException e) {
System.err.println("Deserialization error: " + e.getMessage());
}
catch (ServiceException e) {
System.err.println("Chord Error: " + e.getMessage());
} catch (CryptoException e) {
System.err.println("Crypto Error: " + e.getMessage());
}
finally {
try {
socket.close();
} catch (IOException e) {
System.err.println("Error closing socket");
}
}
}
public Request readRequest() throws IOException, ClassNotFoundException {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(socket.getInputStream());
return (Request) ois.readObject();
}
finally {
if (ois != null) {
ois.close();
}
}
}
public void writeResponse(Response response) throws IOException {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(response);
}
finally {
if (oos != null) {
oos.close();
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
int arpeggioPort = Integer.parseInt(args[0]);
String localHost = args[1];
int localPort = Integer.parseInt(args[2]);
String bootstrapHost = null;
int bootstrapPort = 0;
boolean existingChord = false;
String protocol = URL.KNOWN_PROTOCOLS.get(URL.SOCKET_PROTOCOL);
if (args.length >= 5) {
existingChord = true;
bootstrapHost = args[3];
bootstrapPort = Integer.parseInt(args[4]);
}
de.uniba.wiai.lspi.chord.service.PropertiesLoader.loadPropertyFile();
Chord chord = new ChordImpl();
ServerSocket serverSocket = null;
URL localURL = new URL(protocol + "://" + localHost + ":" + localPort + "/");
try {
if (existingChord) {
URL bootstrapURL = new URL(protocol + "://" + bootstrapHost + ":" + bootstrapPort + "/");
chord.join(localURL, bootstrapURL);
/*chord.insert(new HashKey(new byte[] {0x00}), "HAI");
Set<Serializable> test = chord.retrieve(new HashKey(new byte[] {0x00}));
for (Serializable iter : test) {
System.out.println((String) iter);
}*/
} else {
chord.create(localURL);
/*while(true) {
Set<Serializable> test = chord.retrieve(new HashKey(new byte[] {0x00}));
for (Serializable iter : test) {
System.out.println((String) iter);
}
Thread.sleep(1000);
}*/
}
serverSocket = new ServerSocket(arpeggioPort);
(new Thread(new Server(chord, serverSocket.accept()))).start();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (serverSocket != null) {
serverSocket.close();
}
//chord.leave();
}
}
}
<file_sep>package arpeggio;
import java.security.PublicKey;
import de.uniba.wiai.lspi.chord.service.Chord;
import de.uniba.wiai.lspi.chord.service.Key;
import de.uniba.wiai.lspi.chord.service.ServiceException;
public class InboxRequest extends Request {
private byte[] pubKey;
public InboxRequest(byte[] pubKey) {
this.pubKey = pubKey;
}
@Override
public Response handle(Chord chord) throws ServiceException, CryptoException {
Key inboxKey = new HashKey(pubKey);
Inbox inbox = fetchInbox(chord, inboxKey);
PublicKey publicKey = CryptoUtils.generatePublicKeyFromBytes(pubKey);
Message message = CryptoUtils.encryptObject(publicKey, inbox);
return new Response(message);
}
}
<file_sep>package arpeggio;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import de.uniba.wiai.lspi.chord.service.Chord;
import de.uniba.wiai.lspi.chord.service.Key;
import de.uniba.wiai.lspi.chord.service.ServiceException;
public class ArpeggioClient {
private static String DEFAULT_PUB_KEY_FILENAME = "pubkey.key";
private static String DEFAULT_PRIV_KEY_FILENAME = "privkey.key";
private Chord chord;
private KeyPair cryptoKey;
public ArpeggioClient(Chord chord, KeyPair keyPair) {
this.chord = chord;
this.cryptoKey = keyPair;
}
public void sendMessage(PublicKey destination, String message) {
Message encMsg;
try {
encMsg = CryptoUtils.encryptString(destination, message);
chord.append(new HashKey(destination), encMsg);
} catch (CryptoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// should never happen, drop silently
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public List<String> fetchMessages() {
List<String> msgList = new ArrayList<String>();
try {
Key inboxKey = new HashKey(cryptoKey.getPublic());
List<Key> msgKeyList = null;
Set<Serializable> stuff = chord.retrieve(inboxKey);
for (Object o : stuff) {
if (o instanceof List) {
msgKeyList = (List<Key>) o;
}
}
if (msgKeyList == null) {
return msgList;
}
for (Key k : msgKeyList) {
for(Object o : chord.retrieve(k)) {
if (o instanceof Message) {
Message encMsg = (Message) o;
String plainMsg = CryptoUtils.decryptString(cryptoKey.getPrivate(), encMsg);
msgList.add(plainMsg);
}
}
}
} catch (CryptoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgList;
}
public static void main(String[] args) throws IOException {
String serverHost = args[0];
int serverPort = Integer.parseInt(args[1]);
String pubKeyFilename = DEFAULT_PUB_KEY_FILENAME;
String privKeyFilename = DEFAULT_PRIV_KEY_FILENAME;
if (args.length >= 4) {
pubKeyFilename = args[2];
privKeyFilename = args[3];
}
PublicKey pubKey = null;
PrivateKey privKey = null;
try {
pubKey = CryptoUtils.readPublicKeyFromFile(pubKeyFilename);
privKey = CryptoUtils.readPrivateKeyFromFile(privKeyFilename);
} catch (CryptoException e) {
System.err.println("Loading crypto keys from file failed. Generating new keypair");
}
KeyPair keyPair = null;
if (pubKey != null && privKey != null) {
keyPair = new KeyPair(pubKey, privKey);
} else {
keyPair = CryptoUtils.generateNewKeyPair();
//TODO: ask user to save keys to hard drive
}
//de.uniba.wiai.lspi.chord.service.PropertiesLoader.loadPropertyFile();
//Chord chord = new ChordImpl();
//ArpeggioClient client = new ArpeggioClient(chord, keyPair);
}
}
<file_sep>package de.uniba.wiai.lspi.chord.console.command;
import java.io.PrintStream;
import java.security.KeyPair;
import arpeggio.CryptoException;
import arpeggio.CryptoUtils;
import de.uniba.wiai.lspi.util.console.Command;
import de.uniba.wiai.lspi.util.console.ConsoleException;
public class CreateUser extends Command {
public static final String COMMAND_NAME = "createUser";
protected static final String NAME_PARAM = "name";
public CreateUser(Object[] toCommand, PrintStream out) {
super(toCommand, out);
}
@Override
public void exec() throws ConsoleException {
if (!this.parameters.containsKey(NAME_PARAM)){
throw new ConsoleException("Not enough parameters. Provide at "
+ "least one node name with help of '" + NAME_PARAM
+ "' parameter.");
}
String name = this.parameters.get(NAME_PARAM);
KeyPair keyPair = CryptoUtils.generateNewKeyPair();
try {
CryptoUtils.writePublicKeyToFile(name + ".pub", keyPair.getPublic());
CryptoUtils.writePrivateKeyToFile(name + ".priv", keyPair.getPrivate());
} catch (CryptoException e) {
throw new ConsoleException("Your crypto has an error");
}
this.out.println("User has been created with name " + name);
}
@Override
public void printOutHelp() {
this.out
.println("This command creates a new user and a key pair for this user.");
this.out
.println("The keypair will be saved to files <name>.pub and <name>.priv.");
this.out.println("Required parameters: ");
this.out.println("\t" + NAME_PARAM
+ ": The name of the user, should be unique.");
this.out.println();
}
@Override
public String getCommandName() {
return COMMAND_NAME;
}
}
<file_sep>package arpeggio;
import java.io.Serializable;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import de.uniba.wiai.lspi.chord.service.Key;
public class Inbox implements Serializable{
private static final long serialVersionUID = 1L;
private byte[] pubKey;
public List<Key> messageKeys;
public Inbox(Key key) {
messageKeys = new ArrayList<Key>();
this.pubKey = key.getBytes();
}
public Key key() {
return new HashKey(pubKey);
}
public void appendMessage(Message message) {
messageKeys.add(message.key());
}
public boolean destinationMatches(byte[] pubKey) {
return Arrays.equals(this.pubKey, pubKey);
}
}
<file_sep>package arpeggio;
import java.io.Serializable;
import de.uniba.wiai.lspi.chord.service.Chord;
import de.uniba.wiai.lspi.chord.service.Key;
import de.uniba.wiai.lspi.chord.service.ServiceException;
public abstract class Request {
public abstract Response handle(Chord chord) throws ServiceException, CryptoException;
public Inbox fetchInbox(Chord chord, Key inboxKey) throws ServiceException {
for (Serializable file : chord.retrieve(inboxKey)) {
if (file instanceof Inbox) {
Inbox inbox = (Inbox) file;
if (inbox.key().equals(inboxKey)) {
return inbox;
}
}
}
// If it got here, inbox doesn't exist yet. Create one.
return createInbox(chord, inboxKey);
}
public Inbox createInbox(Chord chord, Key inboxKey) throws ServiceException {
Inbox inbox = new Inbox(inboxKey);
chord.insert(inboxKey, inbox);
return inbox;
}
}
<file_sep>package arpeggio;
import java.security.KeyPair;
import java.security.PublicKey;
import de.uniba.wiai.lspi.chord.service.Key;
public class PublicKeyAsChordKey implements Key {
PublicKey pubKey;
public PublicKeyAsChordKey(PublicKey pubKey) {
this.pubKey = pubKey;
}
public PublicKeyAsChordKey(KeyPair keyPair) {
this.pubKey = keyPair.getPublic();
}
@Override
public boolean equals(Object o) {
if (o instanceof PublicKeyAsChordKey) {
return ((PublicKeyAsChordKey) o).pubKey.equals(this.pubKey);
}
return false;
}
@Override
public int hashCode() {
return pubKey.hashCode();
}
@Override
public byte[] getBytes() {
return pubKey.getEncoded();
}
}
| 9096202ea1523cdbcbfd6c3ac5f7c4080ce8113b | [
"Markdown",
"Java"
] | 10 | Java | jimpo/arpeggio | 4c5e3497a72c63c626f1c87a5751dab5e5357ddf | ac122e4e577775c70b0db7d5edcbc848da7e1a1f |
refs/heads/master | <repo_name>julianh65/topdown-shooter<file_sep>/Game/Assets/Scripts/Combat/bulletTakeDamage.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletTakeDamage : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
health healthRef = collision.gameObject.GetComponent<health>();
healthRef.takeDamage(3f);
Destroy(gameObject);
}
}
<file_sep>/README.md
# Top Down Shooter Survival
A topdown shooter survival game
<file_sep>/Game/Assets/Scripts/Enemy AI/basicFollow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class basicFollow : MonoBehaviour
{
public float speed;
public GameObject targetGameObject;
private Transform target;
public Rigidbody2D rb;
private Vector2 movement;
private void Start()
{
target = targetGameObject.GetComponent<Transform>();
rb = this.GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Vector3 direction = target.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
movement = direction;
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2) transform.position + (direction * speed * Time.fixedDeltaTime));
}
}<file_sep>/Game/Assets/Scripts/Agents Common/health.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class health : MonoBehaviour
{
public float healthAmount;
public void takeDamage(float damageAmount)
{
healthAmount -= damageAmount;
Debug.Log("Taken " + damageAmount + "damage");
Debug.Log(healthAmount);
}
public static void heal(float healAmount)
{
healAmount += healAmount;
}
public void onDeath()
{
Debug.Log("Dying");
Destroy(gameObject);
}
public void Update()
{
if(healthAmount < 0)
{
onDeath();
}
}
}
| be26df8760b54399682d3ae6ac582c2ef5cdf518 | [
"Markdown",
"C#"
] | 4 | C# | julianh65/topdown-shooter | c6005282c0ede1ddbfe8601f07360704ee783559 | 51554bf0218304273ffa714ce5f3fb55e80e6542 |
refs/heads/master | <file_sep>import { NAV_RESPONSIVE, NAV_ACTIVATE, ROUTE_CHANGED } from '../actions/nav';
const initialState = {
responsive: 'multiple',
active: true,
items: [
{ path: '/', label: 'Notes' },
{ path: '/calendar', label: 'Calendar' },
{ path: '/archive', label: 'Archive' },
],
};
export default function nav(state = initialState, action) {
switch (action.type) {
case NAV_RESPONSIVE:
if (action.responsive === 'single' && state.active) {
return { ...state, responsive: action.responsive, active: false };
}
if (action.responsive === 'multiple') {
return { ...state, responsive: action.responsive, active: true };
}
return { ...state, responsive: action.responsive };
case NAV_ACTIVATE:
return { ...state, active: action.active };
case ROUTE_CHANGED:
if (state.responsive === 'single' && state.active) {
return { ...state, active: false };
}
return state;
default:
return state;
}
}
<file_sep>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Notes from './Notes/Notes';
import NoteEdit from './Notes/NoteEdit';
import NoteAdd from './Notes/NoteAdd';
import Note from './Notes/Note';
import Calendar from './Calendar/Calendar';
import Archive from './Archive/Archive';
class DisplayPanel extends React.Component {
render() {
return (
<Switch>
<Route exact path="/" component={Notes} />
<Route exact path="/add" component={NoteAdd} />
<Route exact path="/note/*" component={Note} />
<Route exact path="/edit/*" component={NoteEdit} />
<Route exact path="/calendar" component={Calendar} />
<Route exact path="/archive*" component={Archive} />
</Switch>
);
}
}
export default DisplayPanel;
<file_sep>import React, { Component } from 'react';
import Article from 'grommet/components/Article';
import Header from 'grommet/components/Header';
import Heading from 'grommet/components/Heading';
import Form from 'grommet/components/Form';
import Footer from 'grommet/components/Footer';
import FormFields from 'grommet/components/FormFields';
import FormField from 'grommet/components/FormField';
import Button from 'grommet/components/Button';
import CloseIcon from 'grommet/components/icons/base/Close';
import Anchor from 'grommet/components/Anchor';
import DateTime from 'grommet/components/DateTime'
import { connect } from 'react-redux';
import {withRouter} from "react-router-dom";
import { addNote } from '../../actions/note'
class NoteAdd extends Component {
constructor (props) {
super(props);
this._onSubmit = this._onSubmit.bind(this);
this.state = {
removing: false,
note: {id: 69, title: 'Sample', category: 'Sample Category', content: 'Sample sample sample', date: '7/5/2018 2:00 am', color: ''}
};
}
_onSubmit (event) {
event.preventDefault();
let note = this.state.note;
this.props.dispatch(addNote(note));
this.props.history.push('/');
}
_change (propertyName) {
return (event) => {
let note = { ...this.state.note };
note[propertyName] = event.target.value;
this.setState({ note: note });
};
}
render () {
let { note } = this.state;
return (
<Article align="center" pad={{horizontal: 'medium'}} primary={true}>
<Form onSubmit={this._onSubmit}>
<Header note="large" justify="between" pad="none">
<Heading tag="h2" margin="none" strong={true}>
{'Add Note'}
</Heading>
<Anchor icon={<CloseIcon />} path="/"
a11yTitle={`Close Add Note Form`} />
</Header>
<FormFields>
<fieldset>
<FormField label="Title" htmlFor="title">
<input id="title" name="title" type="text"
value={note.title || ''} onChange={this._change('title')} />
</FormField>
<FormField label="Category" htmlFor="category">
<input id="category" name="category" type="text"
value={note.category || ''} onChange={this._change('category')} />
</FormField>
<FormField label="Content" htmlFor="content">
<input id="content" name="content" type="text"
value={note.content || ''} onChange={this._change('content')} />
</FormField>
<FormField label="Date" htmlFor="date">
<DateTime id="date" name="date"
value={note.date || ''} onChange={this._change('date')} />
</FormField>
</fieldset>
</FormFields>
<Footer pad={{vertical: 'medium'}} justify="between">
<Button type="submit" primary={true} label='Done'
onClick={this._onSubmit} />
</Footer>
</Form>
</Article>
);
}
}
const mapStateToProps = state => ({ notes: state.note.notes });
export default withRouter(connect(mapStateToProps)(NoteAdd));<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import LayerForm from 'grommet-templates/components/LayerForm';
import Paragraph from 'grommet/components/Paragraph';
import {withRouter} from "react-router-dom";
import { deleteNote } from '../../actions/note'
class NoteRemove extends Component {
constructor () {
super();
this._onRemove = this._onRemove.bind(this);
}
_onRemove () {
this.props.dispatch(deleteNote(this.props.note));
this.props.history.push('/');
}
render () {
let note = this.props.note;
return (
<LayerForm title="Remove Note" submitLabel="Yes, Remove"
compact={true}
onClose={this.props.onClose} onSubmit={this._onRemove}>
<fieldset>
<Paragraph>Are you sure you want to remove {note.name}?</Paragraph>
</fieldset>
</LayerForm>
);
}
}
const mapStateToProps = state => ({ notes: state.note.notes });
export default withRouter(connect(mapStateToProps)(NoteRemove));
<file_sep># Notes App
To get started,
1. Install the dependencies: npm install
3. Start the app server: npm run dist
This should launch your app at http://localhost:3000/
In order to run in development mode:
1. Start the data server: npm run dataServer
2. Start the webpack dev server: npm run dev
This should launch your app at http://localhost:9000/<file_sep>import {ADD_NOTE, CHANGE_NOTE, DELETE_NOTE} from '../actions/note';
const colors = ['accent-2', 'neutral-1', 'neutral-1-a', 'neutral-2', 'neutral-2-a', 'neutral-3', 'neutral-3-a', 'neutral-4', 'neutral-4a', 'grey-1', 'grey-2', 'grey-3-a'];
const colorsTaken = ['accent-1', 'brand'];
const initialState = {
notes: [
{id: 1, title: 'Groceries', category:'Everyday', content: 'warzywka i inne', date: '7/5/2018 2:00 am', color:'accent-1'},
{id: 2, title: 'Algebra - wyzsza', category:'Math stuff', content: 'postac macierzowa bramki CNOT', date: '7/5/2018 2:00 am', color:'brand'},
{id: 3, title: 'MWIP - kwantowe swiry', category: 'Math stuff', content: 'bramki pauliego', date: '7/5/2018 2:00 am', color:'brand'}
]
};
export default function nav(state = initialState, action) {
switch (action.type) {
case ADD_NOTE:
let note = action.payload;
note.id = state.notes[state.notes.length-1].id + 1;
for (let i = 0; i < state.notes.length; i++) {
if (state.notes[i].category == note.category) {
note.color = state.notes[i].color;
break;
}
}
if (note.color == '') {
let seed = Math.floor(Math.random() * colors.length);
let newColor = colors[seed];
colors.splice(seed, 1);
colorsTaken.push(newColor);
note.color = newColor;
}
state.notes.push(note);
return state;
case CHANGE_NOTE:
state.notes = state.notes.map(function(item) { return item.id == action.payload.id ? action.payload : item; });
return state;
case DELETE_NOTE:
state.notes = state.notes.filter(item => item !== action.payload);
return state;
default:
return state;
}
} | 4f3363108c6495eed65c51522a46cb779e6cb2bf | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | KonradOnieszczuk/NotesApp | db07228531da890fef47a2298c915fe3ae936859 | 53e88e191bb160d42fb4cfe71b20bd3e88818951 |
refs/heads/master | <repo_name>vvondra/NewsletterServer<file_sep>/NewsletterServer/NewsletterService.svc.cs
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Objects;
using System.Threading;
using NewsletterServer.User;
using System.Web.Services.Protocols;
namespace NewsletterServer
{
/// <summary>
/// Service providing all communication with newsletter service
/// </summary>
public class NewsletterService : IAuthService, ISubscriberService, IMessageService
{
/// <summary>
/// Creates mappings from ADO entities to Data Transfer Objects
/// Hides internal entity objects
/// </summary>
static void CreateMappings()
{
AutoMapper.Mapper.CreateMap<Subscriber, DataTransferObject.SubscriberDto>();
AutoMapper.Mapper.CreateMap<Message, DataTransferObject.MessageDto>();
}
/// <inheritdoc />
public string GetAuthKey(string username, string password)
{
try {
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var newsletter = new ObjectParameter("ret", typeof(Int32));
context.GetUserNewsletter(username, password, newsletter);
var newsletterId = Int32.Parse(newsletter.Value.ToString());
if (newsletterId > 0) {
return sessions.CreateSession(username);
}
return String.Empty;
}
} catch (Exception e) {
return String.Empty;
}
}
/// <inheritdoc />
public List<DataTransferObject.SubscriberDto> GetSubscribers(string authKey)
{
if (!IsAuthenticatedKey(authKey)) {
return null;
}
// Fetch all subscribers for authed user
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var newsletterId = sessions.GetSession(authKey).NewsletterId;
var subscriberQuery = from s in context.Subscribers
where s.newsletter == newsletterId
select s;
var subscribers = new List<DataTransferObject.SubscriberDto>();
CreateMappings();
foreach (var subscriber in subscriberQuery) {
var mapped = AutoMapper.Mapper.Map<Subscriber, DataTransferObject.SubscriberDto>(subscriber);
subscribers.Add(mapped);
}
return subscribers;
}
}
/// <inheritdoc />
public int AddSubscriber(string authKey, DataTransferObject.SubscriberDto s)
{
if (!IsAuthenticatedKey(authKey)) {
return 0;
}
using (var context = new NewsletterEntities()) {
var subscriber = new Subscriber();
var sessions = new SessionManager(context);
subscriber.name = s.Name;
subscriber.contact = s.Contact;
subscriber.newsletter = sessions.GetSession(authKey).NewsletterId;
context.Subscribers.AddObject(subscriber);
context.SaveChanges();
return subscriber.id;
}
}
/// <inheritdoc />
public void UpdateSubscriber(string authKey, DataTransferObject.SubscriberDto sub)
{
if (!IsAuthenticatedKey(authKey)) {
return;
}
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var newsletterId = sessions.GetSession(authKey).NewsletterId;
var subscriberQuery = from s in context.Subscribers
where s.newsletter == newsletterId && s.id == sub.Id
select s;
foreach (var row in subscriberQuery) {
row.name = sub.Name;
row.contact = sub.Contact;
}
context.SaveChanges();
}
}
/// <inheritdoc />
public void DeleteSubscriber(string authKey, int id)
{
if (!IsAuthenticatedKey(authKey)) {
return;
}
// Create a message entity and store it
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var newsletterId = sessions.GetSession(authKey).NewsletterId;
var subscriberQuery = from s in context.Subscribers
where s.newsletter == newsletterId && s.id == id
select s;
foreach (var row in subscriberQuery) {
context.Subscribers.DeleteObject(row);
}
// Persist changes
context.SaveChanges();
}
}
/// <inheritdoc />
public bool QueueMessage(string subject, string body, string clean_body, string authKey)
{
if (!IsAuthenticatedKey(authKey)) {
return false;
}
// Create a message entity and store it
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var message = new Message();
message.status = 3; // TODO DeliveryServer.TransferAgent.Message.StatusWaiting;
message.text = body;
message.clean_text = clean_body;
message.subject = subject;
message.newsletter = sessions.GetSession(authKey).NewsletterId;
message.date = DateTime.Now;
context.Messages.AddObject(message);
// Persist changes
context.SaveChanges();
}
return true;
}
/// <inheritdoc />
public List<NewsletterServer.DataTransferObject.MessageDto> GetMessageList(string authKey)
{
if (!IsAuthenticatedKey(authKey)) {
return null;
}
// Fetch all subscribers for authed user
using (var context = new NewsletterEntities()) {
var sessions = new SessionManager(context);
var newsletterId = sessions.GetSession(authKey).NewsletterId;
var msgQuery = from m in context.Messages
where m.newsletter == newsletterId
select m;
var msgs = new List<DataTransferObject.MessageDto>();
CreateMappings();
foreach (var msg in msgQuery) {
var mapped = AutoMapper.Mapper.Map<Message, DataTransferObject.MessageDto>(msg);
switch (msg.status) {
case 0:
mapped.Status = "Done";
break;
case 1:
mapped.Status = "Canceled";
break;
case 3:
mapped.Status = "Queued";
break;
}
var queueCountQuery = from s in msg.Subscribers select s;
mapped.WaitingToBeSent = queueCountQuery.Count();
msgs.Add(mapped);
}
return msgs;
}
}
/// <summary>
/// Checks whether the user is correctly authenticated
/// </summary>
/// <param name="authKey">authentication key</param>
/// <returns>true when authenticated</returns>
bool IsAuthenticatedKey(string authKey)
{
var sessions = new SessionManager(new NewsletterEntities());
// Check authentication
if (!sessions.IsAuthenticated(authKey)) {
return false;
}
// Revalidate user
sessions.BumpSession(authKey);
return true;
}
}
}
<file_sep>/NewsletterServer/DataTransferObject/SubscriberDto.cs
using System;
using System.Web;
using System.Runtime.Serialization;
namespace NewsletterServer.DataTransferObject
{
/// <summary>
/// Data Transfer Object for subscribers, hides entity code
/// </summary>
[DataContract]
[Serializable]
public class SubscriberDto
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Contact { get; set; }
[DataMember]
public bool IsSubscribed { get; set; }
}
}<file_sep>/NewsletterServer/User/UserSession.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NewsletterServer.User
{
/// <summary>
/// Container for user session
/// </summary>
public class UserSession
{
public string Username { get; set; }
public int NewsletterId { get; set; }
public string AuthenticationKey { get; set; }
public DateTime TimeAuthenticated { get; set; }
}
}<file_sep>/DeliveryServer/Server.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DeliveryServer
{
/// <summary>
/// Maintains a delivery thread in the background to send queued messages
/// </summary>
class Server
{
static void Main(string[] args)
{
// Start sending in background
var deliveryThread = SpawnDeliveryAgent(
new TransferAgent.SmtpTransferAgent(),
new TransferAgent.EntityMessageProvider(new NewsletterServer.NewsletterEntities())
);
deliveryThread.Join();
}
/// <summary>
/// Creates a thread that runs the delivey process
/// </summary>
/// <param name="mta">message transer agent to take care of sending</param>
/// <param name="provider">message provider</param>
/// <returns>spawned thread</returns>
static Thread SpawnDeliveryAgent(TransferAgent.MessageTransferAgent mta, TransferAgent.MessageProvider provider)
{
var messenger = new TransferAgent.RoundRobinMessenger(mta, provider);
var t = new Thread(() => messenger.Deliver());
t.Start();
// We do not want the delivery thread to stop the termination of the application
t.IsBackground = true;
return t;
}
}
}
<file_sep>/ClientSide/ViewModel/Workspace/StatusViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using ClientSide.Properties;
using ClientSide.Model;
using Smith.WPF.HtmlEditor;
namespace ClientSide.ViewModel.Workspace
{
class StatusViewModel : ViewModelBase
{
public StatusViewModel(MessageService service)
{
if (service == null) {
throw new ArgumentException("Need working message service");
}
_msgService = service;
DisplayName = Resources.Status_DisplayName;
}
#region Private fields
MessageService _msgService;
ObservableCollection<Message> _messages;
RelayCommand _refreshCommand;
#endregion Private fields
#region Presentation properties
public ObservableCollection<Message> Messages
{
get
{
if (_messages == null) {
LoadMessages();
}
return _messages;
}
set
{
_messages = value;
base.OnPropertyChanged("Messages");
}
}
public ICommand RefreshCommand
{
get
{
if (_refreshCommand == null) {
_refreshCommand = new RelayCommand(
param => this.LoadMessages(),
param => true
);
}
return _refreshCommand;
}
}
#endregion Presentation properties
public void LoadMessages()
{
Messages = new ObservableCollection<Message>(_msgService.GetMessageList());
}
public void OnMessageSent(object sender, MessageSentEventArgs args)
{
LoadMessages();
}
}
}
<file_sep>/NewsletterServer/User/SessionManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NewsletterServer.User
{
/// <summary>
/// Manages active session with the service
/// </summary>
public class SessionManager
{
/// <summary>
/// Entity object context
/// </summary>
NewsletterEntities context;
/// <summary>
/// How long a session lasts without refreshing (default two hours)
/// </summary>
public TimeSpan SessionTimeout = new TimeSpan(2, 0, 0);
public SessionManager(NewsletterEntities context)
{
this.context = context;
}
/// <summary>
/// Creates a user session object and registers it in the manager
/// </summary>
/// <param name="username">username</param>
/// <return>generated authentication key</return>
internal string CreateSession(string username)
{
var authKey = GenerateAuthKey();
var userIdQuery = from u in context.Users
where u.username == username
select u.id;
int user_id = userIdQuery.FirstOrDefault();
var userQuery = from s in context.Sessions
where user_id == s.user_id
select s;
var session = userQuery.FirstOrDefault();
if (session != null && IsAuthenticated(session.auth_key)) {
BumpSession(session.auth_key);
return session.auth_key;
}
context.Sessions.AddObject(Sessions.CreateSessions(user_id, authKey, DateTime.Now));
context.SaveChanges();
return authKey;
}
internal UserSession GetSession(string authKey)
{
var sessionQuery = from s in context.Sessions
join u in context.Users on s.user_id equals u.id
select new UserSession() { Username = u.username, NewsletterId = u.newsletter, AuthenticationKey = s.auth_key, TimeAuthenticated = s.time };
return sessionQuery.FirstOrDefault();
}
/// <summary>
/// Removes sessions older than set timeout
/// </summary>
internal void PruneSessions()
{
var timeOutDate = DateTime.Now.Subtract(SessionTimeout);
var oldSessionQuery = from s in context.Sessions
where s.time < timeOutDate
select s;
foreach (var session in oldSessionQuery) {
context.DeleteObject(session);
}
context.SaveChanges();
}
/// <summary>
/// Checks whether the user has an active session
/// </summary>
/// <param name="authKey">authentication key user has been authenticated with</param>
/// <returns></returns>
internal bool IsAuthenticated(string authKey)
{
PruneSessions();
return GetSession(authKey) != null;
}
/// <summary>
/// Bumps the specified session last modified time
/// Does nothing if session does not exist
/// </summary>
/// <param name="authKey">authentication key user has been authenticated with</param>
internal void BumpSession(string authKey) {
var sessionQuery = from s in context.Sessions
where s.auth_key == authKey
select s;
var session = sessionQuery.FirstOrDefault();
session.time = DateTime.Now;
context.SaveChanges();
}
/// <summary>
/// Generates a unique authentication key
/// </summary>
/// <returns>authentication key</returns>
string GenerateAuthKey()
{
Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");
return GuidString;
}
}
}<file_sep>/ClientSide/ViewModel/Workspace/SubscriberViewModel.cs
using System;
using System.ComponentModel;
using System.Windows.Input;
using ClientSide.Model;
using ClientSide.Properties;
using NewsletterServer;
namespace ClientSide.ViewModel.Workspace
{
/// <summary>
/// A UI-friendly wrapper for a Subscriber object.
/// </summary>
public class SubscriberViewModel : ViewModelBase, IDataErrorInfo
{
#region Fields
readonly Subscriber _subscriber;
readonly SubscriberService _subscriberService;
bool _isSelected;
RelayCommand _saveCommand;
RelayCommand _deleteCommand;
#endregion // Fields
#region Constructor
public SubscriberViewModel(Subscriber subscriber, SubscriberService subscriberService)
{
if (subscriber == null)
throw new ArgumentNullException("subscriber");
if (subscriberService == null)
throw new ArgumentNullException("subscriberService");
_subscriber = subscriber;
_subscriberService = subscriberService;
}
#endregion // Constructor
#region Subscriber Properties
public string Email
{
get { return _subscriber.Email; }
set
{
if (value == _subscriber.Email)
return;
_subscriber.Email = value;
base.OnPropertyChanged("Email");
}
}
public string Name
{
get { return _subscriber.Name; }
set
{
if (value == _subscriber.Name)
return;
_subscriber.Name = value;
base.OnPropertyChanged("Name");
}
}
public bool IsSubscribed
{
get { return _subscriber.IsSubscribed; }
}
#endregion // Subscriber Properties
#region Presentation Properties
public Subscriber Subscriber
{
get { return _subscriber; }
}
/// <summary>
/// Returns true if this subscriber was created by the user and it has not yet
/// been saved to the subscriber repository.
/// </summary>
public bool IsNewSubscriber
{
get { return _subscriber.Id == 0; }
}
public override string DisplayName
{
get
{
if (IsNewSubscriber) {
return "register new subscriber";
}
return "edit subscriber " + _subscriber.Name;
}
protected set
{
}
}
/// <summary>
/// Text for the save button below subscriber form
/// </summary>
public string SaveButtonText
{
get {
if (IsNewSubscriber) {
return "Add";
}
return "Save";
}
}
/// <summary>
/// Gets/sets whether this customer is selected in the UI.
/// </summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (value == _isSelected)
return;
_isSelected = value;
base.OnPropertyChanged("IsSelected");
}
}
/// <summary>
/// Returns a command that saves the customer.
/// </summary>
public ICommand SaveCommand
{
get
{
if (_saveCommand == null) {
_saveCommand = new RelayCommand(
param => this.Save(),
param => this.CanSave
);
}
return _saveCommand;
}
}
/// <summary>
/// Returns a command that deletes the customer.
/// </summary>
public ICommand DeleteCommand
{
get
{
if (_deleteCommand == null) {
_deleteCommand = new RelayCommand(
param => this.Delete(),
param => !this.IsNewSubscriber
);
}
return _deleteCommand;
}
}
#endregion // Presentation Properties
#region Public Methods
/// <summary>
/// Saves the subscriber to the repository. This method is invoked by the SaveCommand.
/// </summary>
public void Save()
{
if (!_subscriber.IsValid)
throw new InvalidOperationException(Resources.SubscriberViewModel_Exception_CannotSave);
if (this.IsNewSubscriber) {
_subscriberService.SaveSubscriber(_subscriber);
}
base.OnPropertyChanged("IsNewSubscriber");
base.OnPropertyChanged("DisplayName");
}
/// <summary>
/// Deletes subscriber from repository
/// </summary>
public void Delete()
{
_subscriberService.DeleteSubscriber(_subscriber);
}
#endregion // Public Methods
#region Private Helpers
/// <summary>
/// Returns true if the subscriber is valid and can be saved.
/// </summary>
bool CanSave
{
get { return _subscriber.IsValid; }
}
#endregion // Private Helpers
#region IDataErrorInfo Members
string IDataErrorInfo.Error
{
get { return (_subscriber as IDataErrorInfo).Error; }
}
string IDataErrorInfo.this[string propertyName]
{
get
{
string error = null;
error = (_subscriber as IDataErrorInfo)[propertyName];
// Dirty the commands registered with CommandManager,
// such as our Save command, so that they are queried
// to see if they can execute now.
CommandManager.InvalidateRequerySuggested();
return error;
}
}
#endregion // IDataErrorInfo Members
}
}<file_sep>/ClientSide/UI/BooleanToVisibilityConverter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace ClientSide.UI
{
public sealed class BooleanToVisibilityConverter : BooleanConverter<Visibility>
{
public BooleanToVisibilityConverter() :
base(Visibility.Visible, Visibility.Collapsed) { }
}
}
<file_sep>/ClientSide/ViewModel/Workspace/ComposeViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using ClientSide.Properties;
using ClientSide.Model;
using Smith.WPF.HtmlEditor;
namespace ClientSide.ViewModel.Workspace
{
class ComposeViewModel : ViewModelBase
{
public ComposeViewModel(MessageService service)
{
if (service == null) {
throw new ArgumentException("Need working message service");
}
_msgService = service;
DisplayName = Resources.Compose_DisplayName;
Editor = new HtmlEditor();
}
#region Private fields
string _subject = String.Empty;
HtmlEditor _editor;
RelayCommand _sendCommand;
MessageService _msgService;
#endregion Private fields
#region Presentation properites
/// <summary>
/// Message subject
/// </summary>
public string Subject
{
get { return _subject; }
set
{
_subject = value;
base.OnPropertyChanged("Subject");
}
}
/// <summary>
/// HTML editor
/// </summary>
public HtmlEditor Editor
{
get { return _editor; }
set {
_editor = value;
base.OnPropertyChanged("Editor");
}
}
#endregion Presentation properties
/// <summary>
/// Returns a command that sends the message
/// </summary>
public ICommand SendCommand
{
get
{
if (_sendCommand == null) {
_sendCommand = new RelayCommand(
param => this.Send(),
param => this.CanSend
);
}
return _sendCommand;
}
}
void Send()
{
_msgService.QueueMessage(Subject, Editor.ContentHtml, Editor.ContentText);
Subject = String.Empty;
Editor.ContentHtml = String.Empty;
}
/// <summary>
/// Checks whether the message can be sent
/// Checks for an empty message are implemented
/// </summary>
/// <returns>true when message is filled out and can be sent</returns>
public bool CanSend
{
get
{
return Subject.Trim() != String.Empty && Editor != null && Editor.WordCount > 0;
}
}
}
}
<file_sep>/ClientSide/ViewModel/Workspace/SubscriberListViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using ClientSide.Properties;
using ClientSide.Model;
namespace ClientSide.ViewModel.Workspace
{
public class SubscriberListViewModel : ViewModelBase
{
public SubscriberListViewModel(SubscriberService service)
{
DisplayName = Resources.SubscriberList_DisplayName;
if (service == null) {
throw new ArgumentNullException("Invalid service");
}
_subscriberService = service;
_subscriberService.SubscriberAdded += this.OnSubscriberAddedToRepository;
_subscriberService.SubscriberDeleted += this.OnSubscriberDeletedFromRepository;
LoadSubscribers();
}
#region Fields
readonly SubscriberService _subscriberService;
ViewModelBase _subscriberPane;
#endregion // Fields
void LoadSubscribers()
{
var subs = _subscriberService.GetSubscribers();
List<SubscriberViewModel> all =
(from cust in subs
select new SubscriberViewModel(cust, _subscriberService)).ToList();
foreach (SubscriberViewModel cvm in all)
cvm.PropertyChanged += this.OnSubscriberViewModelPropertyChanged;
this.AllSubscribers = new ObservableCollection<SubscriberViewModel>(all);
this.AllSubscribers.CollectionChanged += this.OnCollectionChanged;
}
/// <summary>
/// Returns a collection of all the SubscriberViewModel objects.
/// </summary>
public ObservableCollection<SubscriberViewModel> AllSubscribers { get; private set; }
/// <summary>
/// Holds the viewmodel for the right hand side subscriber editing pane
/// </summary>
public ViewModelBase SubscriberPane
{
get
{
if (_subscriberPane == null) {
_subscriberPane = new SubscriberViewModel(Subscriber.CreateNewSubscriber(), _subscriberService);
}
return _subscriberPane;
}
set
{
_subscriberPane = value;
base.OnPropertyChanged("SubscriberPane");
}
}
protected override void OnDispose()
{
foreach (SubscriberViewModel custVM in this.AllSubscribers)
custVM.Dispose();
this.AllSubscribers.Clear();
this.AllSubscribers.CollectionChanged -= this.OnCollectionChanged;
_subscriberService.SubscriberAdded -= this.OnSubscriberAddedToRepository;
}
#region Event Handling Methods
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Count != 0)
foreach (SubscriberViewModel svm in e.NewItems)
svm.PropertyChanged += this.OnSubscriberViewModelPropertyChanged;
if (e.OldItems != null && e.OldItems.Count != 0)
foreach (SubscriberViewModel svm in e.OldItems)
svm.PropertyChanged -= this.OnSubscriberViewModelPropertyChanged;
}
void OnSubscriberViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
string IsSelected = "IsSelected";
// When a subscriber row is selected, set the user form to the selected user
if (sender is SubscriberViewModel) {
SubscriberPane = sender as SubscriberViewModel;
}
// Make sure that the property name we're referencing is valid.
// This is a debugging technique, and does not execute in a Release build.
(sender as SubscriberViewModel).VerifyPropertyName(IsSelected);
}
void OnSubscriberAddedToRepository(object sender, SubscriberChangedEventArgs e)
{
var viewModel = new SubscriberViewModel(e.Subscriber, _subscriberService);
this.AllSubscribers.Add(viewModel);
}
void OnSubscriberDeletedFromRepository(object sender, SubscriberChangedEventArgs e)
{
SubscriberPane = new SubscriberViewModel(Subscriber.CreateNewSubscriber(), _subscriberService);
for (int i = 0; i < this.AllSubscribers.Count; i++) {
if (this.AllSubscribers[i].Subscriber == e.Subscriber) {
this.AllSubscribers.RemoveAt(i);
}
}
}
#endregion // Event Handling Methods
}
}
<file_sep>/ClientSide/View/LoginView.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
using System.ServiceModel;
using MahApps.Metro.Controls;
namespace ClientSide.View
{
/// <summary>
/// Interaction logic for LoginWindow.xaml
/// </summary>
public partial class LoginView : System.Windows.Controls.UserControl
{
public LoginView()
{
InitializeComponent();
}
}
}
<file_sep>/ClientSide/Model/MessageService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsletterServer.DataTransferObject;
using ClientSide.ViewModel.Workspace;
namespace ClientSide.Model
{
public class MessageService : IDisposable
{
/// <summary>
/// Called when a message is sent
/// </summary>
public EventHandler<MessageSentEventArgs> MessageSent;
/// <summary>
/// Creates a service through which messages can be sent to server
/// </summary>
/// <param name="key">service authentication key</param>
public MessageService(string key)
{
client = new MessageServiceClient();
if (key == String.Empty) {
throw new ArgumentException("Service needs valid authentication key");
}
authKey = key;
}
#region private fields
/// <summary>
/// Message client
/// </summary>
MessageServiceClient client;
/// <summary>
/// Service authentication key
/// </summary>
string authKey;
#endregion
/// <summary>
/// Queues a message in the server
/// </summary>
/// <param name="subject">message subject</param>
/// <param name="body">message body</param>
/// <param name="clean_body">message body without HTML</param>
public void QueueMessage(string subject, string body, string clean_body)
{
client.QueueMessage(subject, body, clean_body, authKey);
if (MessageSent != null) {
MessageSent(this, new MessageSentEventArgs());
}
}
/// <summary>
/// Returns a list of messages from the server
/// </summary>
/// <returns>list of messages for authenticated newsletter</returns>
public List<Message> GetMessageList()
{
var msgs = client.GetMessageList(authKey);
var msgList = new List<Message>();
foreach (var msg in msgs) {
var msgItem = new Message();
msgItem.Id = msg.Id;
msgItem.Text = msg.Text;
msgItem.Date = msg.Date;
msgItem.Status = msg.Status;
msgItem.Subject = msg.Subject;
msgItem.WaitingToBeSent = msg.WaitingToBeSent;
msgList.Add(msgItem);
}
return msgList;
}
/// <summary>
/// Close connection on disposal
/// </summary>
public void Dispose()
{
client.Close();
}
}
}
<file_sep>/NewsletterServer/Services/IMessageService.cs
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace NewsletterServer
{
/// <summary>
/// Endpoint for message related features
/// </summary>
[ServiceContract]
interface IMessageService
{
/// <summary>
/// Queues message in the sending queue common for all newsletters
/// </summary>
/// <param name="subject">Subject of the message</param>
/// <param name="body">Content of the message (with HTML or other markup)</param>
/// <param name="clean_body">Content of the message without any markup</param>
/// <returns>Return true when queueing was successful</returns>
[OperationContract]
bool QueueMessage(string subject, string body, string clean_body, string authKey);
/// <summary>
/// Returns list of messages
/// </summary>
/// <param name="authKey">authentication key</param>
/// <returns>list of messages sent by newsletter</returns>
[OperationContract]
List<NewsletterServer.DataTransferObject.MessageDto> GetMessageList(string authKey);
}
}
<file_sep>/DeliveryServer/TransferAgent/EntityMessageProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using NewsletterServer;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// Message provider implementation using Entity Framework
/// </summary>
internal class EntityMessageProvider : MessageProvider
{
/// <summary>
/// Object context to access database
/// </summary>
NewsletterEntities context;
/// <summary>
/// Creates new database message provider
/// </summary>
/// <param name="objectContext">object context for entities</param>
internal EntityMessageProvider(NewsletterEntities objectContext)
{
context = objectContext;
}
/// <summary>
/// Loads message from the database
/// </summary>
/// <returns>list of messages waiting to be sent</returns>
internal override List<DeliveryServer.TransferAgent.Message> GetUndeliveredMessages()
{
var msgQuery = from m in context.Messages
where m.status == Message.StatusWaiting
select m;
var messages = new List<DeliveryServer.TransferAgent.Message>();
foreach (var msg in msgQuery) {
messages.Add(new DeliveryServer.TransferAgent.Message(msg, context));
}
return messages;
}
}
}<file_sep>/ClientSide/ViewModel/LoginViewModel.cs
using System;
using System.Security;
using System.Windows;
using System.Windows.Input;
using System.ServiceModel;
using System.ComponentModel;
using MahApps.Metro.Controls;
using ClientSide.Model;
namespace ClientSide.ViewModel
{
public class LoginViewModel : ViewModelBase
{
/// <summary>
/// Called upon successful login
/// </summary>
internal event EventHandler LoginSuccessful;
ICommand _loginCommand;
/// <summary>
/// Credential container
/// </summary>
readonly Credentials _credentials;
bool _isProcessingLogin = false;
#region Fields
public string Username
{
get { return _credentials.Username; }
set
{
if (value == _credentials.Username)
return;
_credentials.Username = value;
base.OnPropertyChanged("Username");
}
}
public string Password
{
get { return _credentials.Password; }
set
{
if (value == _credentials.Password)
return;
_credentials.Password = value;
base.OnPropertyChanged("Password");
}
}
/// <summary>
/// Determines wheter the viewmodel is currenctly processing the login credentials
/// </summary>
public bool IsProcessingLogin
{
get { return _isProcessingLogin; }
set
{
_isProcessingLogin = value;
base.OnPropertyChanged("IsProcessingLogin");
}
}
#endregion Fields
public LoginViewModel()
{
_credentials = new Credentials();
base.DisplayName = "Newsletter Composer - Log In";
}
public ICommand LoginCommand
{
get
{
if (_loginCommand == null) {
_loginCommand = new RelayCommand(ExecuteLogin);
}
return _loginCommand;
}
}
/// <summary>
/// Calls the authentication service in the background to not block the UI thread
/// </summary>
/// <param name="o"></param>
private void ExecuteLogin(object o)
{
// We are now waiting for the login to be processed
IsProcessingLogin = true;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(GetAuthenticationKey);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ProcessLogin);
worker.RunWorkerAsync(_credentials);
}
/// <summary>
/// Upon receiving a response from the authentication service,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ProcessLogin(object sender, RunWorkerCompletedEventArgs e)
{
// The login is now processed and the rest is fast
IsProcessingLogin = false;
var key = e.Result as string;
if (key != String.Empty) {
LoginSuccessful(this, new LoginEventArgs(key));
} else {
MessageBox.Show("Invalid login information");
}
}
/// <summary>
/// Users authentication service to get auth key
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void GetAuthenticationKey(object sender, DoWorkEventArgs args)
{
var credentials = args.Argument as Credentials;
try {
var client = new AuthServiceClient();
args.Result = client.GetAuthKey(credentials.Username, credentials.Password);
client.Close();
} catch (EndpointNotFoundException e) {
args.Result = String.Empty;
}
}
}
}
<file_sep>/ClientSide/Model/SubscriberService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsletterServer.DataTransferObject;
using ClientSide.ViewModel.Workspace;
namespace ClientSide.Model
{
public class SubscriberService : IDisposable
{
/// <summary>
/// Client used to connect to web service
/// </summary>
SubscriberServiceClient client = new SubscriberServiceClient();
/// <summary>
/// List of subscribers
/// </summary>
List<Subscriber> _subscribers;
/// <summary>
/// Raised when a subscriber is added
/// </summary>
public event EventHandler<SubscriberChangedEventArgs> SubscriberAdded;
/// <summary>
/// Raised when a subscriber is deleted
/// </summary>
public event EventHandler<SubscriberChangedEventArgs> SubscriberDeleted;
/// <summary>
/// Auth key for service client
/// </summary>
public string AuthKey { get; set; }
public SubscriberService(string key)
{
if (key == String.Empty) {
throw new ArgumentException("Service needs valid authentication key");
}
AuthKey = key;
}
/// <summary>
/// Returns all subscribers
/// If not previously loaded, loads them from the repository
/// </summary>
/// <returns></returns>
public List<Subscriber> GetSubscribers()
{
if (_subscribers != null) {
return _subscribers;
}
var subscribers = client.GetSubscribers(AuthKey);
_subscribers = new List<Subscriber>();
foreach (var subscriber in subscribers) {
_subscribers.Add(Subscriber.CreateSubscriber(subscriber.Id, subscriber.Name, subscriber.IsSubscribed, subscriber.Contact));
}
return _subscribers;
}
/// <summary>
/// Adds a subscriber to the collection and sends and add request to the service
/// </summary>
/// <param name="s">subscriber to be added</param>
public void SaveSubscriber(Subscriber s)
{
if (!ContainsSubscriber(s)) {
// Add to collection
_subscribers.Add(s);
// Send to service
var dto = new NewsletterServer.DataTransferObject.SubscriberDto();
dto.Contact = s.Email;
dto.Name = s.Name;
dto.IsSubscribed = true;
// Add user and fetch new Id
s.Id = client.AddSubscriber(AuthKey, dto);
// Raise added event
if (SubscriberAdded != null) {
SubscriberAdded(this, new SubscriberChangedEventArgs(s));
}
} else {
var dto = new NewsletterServer.DataTransferObject.SubscriberDto();
dto.Contact = s.Email;
dto.Name = s.Name;
}
}
/// <summary>
/// Sends a deletion request for the subscriber
/// </summary>
/// <param name="s">subscriber to be removed</param>
public void DeleteSubscriber(Subscriber s)
{
if (ContainsSubscriber(s)) {
client.DeleteSubscriber(AuthKey, s.Id);
}
if (SubscriberDeleted != null) {
SubscriberDeleted(this, new SubscriberChangedEventArgs(s));
}
}
/// <summary>
/// Checks whether the current subscriber list contains a subscriber
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public bool ContainsSubscriber(Subscriber s)
{
return GetSubscribers().Contains(s);
}
/// <summary>
/// Close connection on disposal
/// </summary>
public void Dispose()
{
client.Close();
}
}
}
<file_sep>/DeliveryServer/TransferAgent/Messenger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// Base class for messengers
///
/// Each messenger defines its own strategy for delivery
/// </summary>
internal abstract class Messenger
{
/// <summary>
/// Delivers provided message
/// </summary>
/// <param name="message">message</param>
internal abstract void Deliver();
}
}<file_sep>/NewsletterServer/Services/ISubscriberService.cs
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace NewsletterServer
{
/// <summary>
/// Endpoint for subscriber related features
/// </summary>
[ServiceContract]
interface ISubscriberService
{
/// <summary>
/// Returns an array of subscribers for newsletter logged in with current auth key
/// </summary>
/// <param name="value"></param>
/// <param name="authKey">Authentication key provide by authentication serivce <see cref="IAuthService.GetAuthKey"/></param>
/// <returns></returns>
[OperationContract]
List<DataTransferObject.SubscriberDto> GetSubscribers(string authKey);
/// <summary>
/// Adds the sent subscriber to the database
/// </summary>
/// <param name="authKey"></param>
/// <param name="subscriber">subscriber to be saved</param>
/// <returns>Id of created user</returns>
[OperationContract]
int AddSubscriber(string authKey, DataTransferObject.SubscriberDto subscriber);
/// <summary>
/// Updates a subscriber in the database
/// </summary>
/// <param name="authKey"></param>
/// <param name="subscriber">new subscriber data, matched by ID</param>
[OperationContract]
void UpdateSubscriber(string authKey, DataTransferObject.SubscriberDto subscriber);
/// <summary>
/// Deletes a subscriber from newsletter
/// </summary>
/// <param name="authKey"></param>
/// <param name="id">id of the user</param>
[OperationContract]
void DeleteSubscriber(string authKey, int id);
}
}
<file_sep>/DeliveryServer/TransferAgent/Message.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NewsletterServer;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// A message to be sent, contains message body and tracks sent recepients
/// </summary>
internal class Message
{
/// <summary>
/// Flag that the message is waiting to be sent
/// </summary>
internal const int StatusWaiting = 3;
/// <summary>
/// Flag that the message was delivered to all recepients
/// </summary>
internal const int StatusDelivered = 0;
/// <summary>
/// Entity context
/// </summary>
NewsletterEntities objectContext { get; set; }
/// <summary>
/// Content of the message to be sent
/// </summary>
public NewsletterServer.Message Content;
/// <summary>
/// Handler called when the message is set as delivered
/// </summary>
internal EventHandler MessageDelivered;
/// <summary>
/// Creates a message container
/// </summary>
/// <param name="msg">message data</param>
public Message(NewsletterServer.Message msg, NewsletterEntities context)
{
Content = msg;
objectContext = context;
MessageDelivered += this.OnDelivery;
}
/// <summary>
/// Returns list of subscribers
/// </summary>
/// <returns></returns>
public List<Subscriber> GetUndeliveredSubscribers(int count)
{
var subscribersQuery = from s in Content.Subscribers
select s;
return subscribersQuery.Take(count).ToList();
}
/// <summary>
/// Set the message delivered to the specified subscriber
/// </summary>
/// <param name="s">subscriber message was sent to</param>
public void AddDelivery(Subscriber s)
{
var queueQuery = from q in Content.Subscribers
where q.contact == s.contact
select q;
// Delete subscriber from queue for this mailing
objectContext.DeleteObject(queueQuery.First());
objectContext.SaveChanges();
}
/// <summary>
/// Sets the message status as delivered
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void OnDelivery(object sender, EventArgs args)
{
Content.status = StatusDelivered;
objectContext.SaveChanges();
}
}
}<file_sep>/ClientSide/ViewModel/Workspace/MessageSentEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClientSide.ViewModel.Workspace
{
public class MessageSentEventArgs : EventArgs
{
public MessageSentEventArgs()
{
}
}
}
<file_sep>/DeliveryServer/TransferAgent/RoundRobinMessenger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using NewsletterServer;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// Takes a fixed amount of messages from all queues and sends them
/// </summary>
internal class RoundRobinMessenger : Messenger
{
/// <summary>
/// Limits the number of messages sent per hour for throttling
/// </summary>
readonly static int MessagesPerHour = 2000;
/// <summary>
/// How many messages should be sent during one round-robin circle
/// </summary>
readonly static int MessagesPerBatch = 20;
/// <summary>
/// MTA for sending messages
/// </summary>
MessageTransferAgent mta { get; set; }
/// <summary>
/// Provider of messages
/// </summary>
MessageProvider provider { get; set; }
/// <summary>
/// Used for throttling, stores the last time of the cycle
/// </summary>
protected DateTime LastCycle = DateTime.Now;
/// <summary>
/// Amount of time throttling is behing schedule
/// </summary>
protected TimeSpan TimeDebt = new TimeSpan(0);
/// <summary>
/// Prepares the messenger
/// </summary>
/// <param name="mta">mail transfer agent to be used</param>
internal RoundRobinMessenger(MessageTransferAgent mta, MessageProvider provider)
{
this.mta = mta;
this.provider = provider;
}
/// <summary>
/// Delivers selected messages
/// </summary>
/// <param name="messages">List of messages to be sent</param>
internal override void Deliver()
{
while (true) {
System.Console.WriteLine("Fetching undelivered messages");
var messages = provider.GetUndeliveredMessages();
// Deliver messages until there are none left
while (messages.Count > 0) {
Throttle();
foreach (var msg in messages) {
// Take a fair slice of subscribers so all messages get the same
System.Console.WriteLine("Fetch subscriber batch for message");
var recepients = msg.GetUndeliveredSubscribers(MessagesPerBatch / messages.Count).ToList();
// No recepients left
if (recepients.Count() == 0) {
// Call delivered event
System.Console.WriteLine("Marking message as delivered");
msg.MessageDelivered(this, null);
continue;
}
DeliverMessageToSubscribers(msg, recepients);
}
// Refresh queue
messages = provider.GetUndeliveredMessages();
}
System.Threading.Thread.Sleep(1000);
}
}
/// <summary>
/// Throttles the sending loop to meet the message per hour quota
///
/// Called once each batch, it calculates the time spent on the cycle and determines
/// how long it needs to sleep or pay a time debt to previous long cycles
/// </summary>
protected void Throttle()
{
var previousCycle = LastCycle;
TimeSpan loopTime = DateTime.Now - previousCycle;
if (loopTime.CompareTo(CycleLength) > 0) {
// We are behing of schedule, add how much
TimeDebt += loopTime - CycleLength;
return;
} else {
TimeSpan sleepTime = CycleLength - loopTime;
// We are ahead of schedule during one loop
if (TimeDebt.Seconds > 0) {
// Cover time debt
var diff = sleepTime.CompareTo(TimeDebt) < 0 ? new TimeSpan(0) : sleepTime - TimeDebt; // Math.Max(0, sleepTime - TimeDebt);
TimeDebt -= sleepTime;
sleepTime = diff;
}
// Sleep for what is left of sleep time after covering debt
Console.WriteLine("Throttling for {0}", sleepTime);
System.Threading.Thread.Sleep(sleepTime);
}
LastCycle = DateTime.Now;
}
/// <summary>
/// Gets the expected length of one sending cycle to maintain average message per hour quota
/// </summary>
protected TimeSpan CycleLength
{
get { return new TimeSpan(0, 0, 3600 / (MessagesPerHour / MessagesPerBatch)); }
}
/// <summary>
/// Send message to specified subscribers
/// </summary>
/// <param name="msg">Message</param>
/// <param name="subscribers">List of recepients</param>
protected void DeliverMessageToSubscribers(Message msg, List<Subscriber> subscribers)
{
foreach (var recepient in subscribers) {
mta.Send(recepient.contact, msg.Content);
msg.AddDelivery(recepient);
}
}
}
}<file_sep>/ClientSide/Model/Subscriber.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using ClientSide.Properties;
namespace ClientSide.Model
{
/// <summary>
/// Represents a newsletter subscriber
/// </summary>
public class Subscriber : IDataErrorInfo
{
#region Creation
public static Subscriber CreateNewSubscriber()
{
return new Subscriber();
}
public static Subscriber CreateSubscriber(
int id,
string name,
bool isSubscribed,
string email)
{
return new Subscriber {
Id = id,
Name = name,
IsSubscribed = isSubscribed,
Email = email
};
}
protected Subscriber()
{
}
#endregion // Creation
#region State Properties
/// <summary>
/// Subscriber ID from service
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets/sets the e-mail address
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets/sets the subscribers name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets whether the subscriber is active
/// </summary>
public bool IsSubscribed { get; set; }
/// <summary>
/// Gets/sets the subscribers newsletter ID
/// </summary>
public int NewsletterID { get; set; }
#endregion // State Properties
#region IDataErrorInfo Members
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
#endregion // IDataErrorInfo Members
#region Validation
/// <summary>
/// Returns true if this object has no validation errors.
/// </summary>
public bool IsValid
{
get
{
foreach (string property in ValidatedProperties)
if (GetValidationError(property) != null)
return false;
return true;
}
}
static readonly string[] ValidatedProperties =
{
"Email",
"Name",
};
string GetValidationError(string propertyName)
{
if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
return null;
string error = null;
switch (propertyName) {
case "Email":
error = this.ValidateEmail();
break;
case "Name":
error = this.ValidateName();
break;
default:
Debug.Fail("Unexpected property being validated on Subscriber: " + propertyName);
break;
}
return error;
}
string ValidateEmail()
{
if (IsStringMissing(this.Email)) {
return Resources.Subscriber_MissingEmail;
} else if (!IsValidEmailAddress(this.Email)) {
return Resources.Subscriber_InvalidEmail;
}
return null;
}
string ValidateName()
{
if (IsStringMissing(this.Name)) {
return Resources.Subsciber_MissingName;
}
return null;
}
static bool IsStringMissing(string value)
{
return
String.IsNullOrEmpty(value) ||
value.Trim() == String.Empty;
}
static bool IsValidEmailAddress(string email)
{
if (IsStringMissing(email))
return false;
// This regex pattern came from: http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase);
}
#endregion // Validation
}
}<file_sep>/ClientSide/ViewModel/MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Data;
using ClientSide.Model;
using ClientSide.Properties;
namespace ClientSide.ViewModel
{
/// <summary>
/// The ViewModel for the application's main window.
/// </summary>
public class MainWindowViewModel : ViewModelBase
{
#region Fields
/// <summary>
/// Authentication key received after login
/// </summary>
public string AuthKey { get; set; }
/// <summary>
/// Holds current view
/// </summary>
ViewModelBase _currentView;
#endregion // Fields
#region Constructor
public MainWindowViewModel()
{
base.DisplayName = Resources.MainWindowViewModel_DisplayName;
ShowLoginDialog();
}
#endregion // Constructor
/// <summary>
/// Holds the currently active view in window
/// </summary>
public ViewModelBase CurrentView
{
get
{
return _currentView;
}
set
{
_currentView = value;
base.OnPropertyChanged("CurrentView");
}
}
void ShowWorkspace()
{
var workspaceVm = new WorkspaceViewModel(AuthKey);
this.SetActiveView(workspaceVm);
}
/// <summary>
/// Sets the login dialog as the current view
/// </summary>
void ShowLoginDialog()
{
LoginViewModel loginVm = new LoginViewModel();
// Fetch authentication key from login
loginVm.LoginSuccessful += this.GetAuthenticationKey;
// When logged in, show the main workspace
loginVm.LoginSuccessful += (s, e) => ShowWorkspace();
this.SetActiveView(loginVm);
}
/// <summary>
/// Sets the auth key for the view model from the login call
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void GetAuthenticationKey(object sender, EventArgs args)
{
AuthKey = (args as LoginEventArgs).AuthKey;
}
/// <summary>
/// Sets the view as the currently active in the window
/// </summary>
/// <param name="view">view to be selected as primary</param>
void SetActiveView(ViewModelBase view)
{
this.CurrentView = view;
}
}
}<file_sep>/ClientSide/ViewModel/Workspace/SubscriberChangedEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClientSide.ViewModel.Workspace
{
public class SubscriberChangedEventArgs : EventArgs
{
public SubscriberChangedEventArgs(ClientSide.Model.Subscriber subscriber)
{
Subscriber = subscriber;
}
public ClientSide.Model.Subscriber Subscriber { get; private set; }
}
}
<file_sep>/DeliveryServer/TransferAgent/SmtpTransferAgent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// SMTP implementation of MTA
/// </summary>
internal class SmtpTransferAgent : MessageTransferAgent
{
readonly static string defaultSender = "<NAME> <<EMAIL>>";
/// <summary>
/// Sends a message to the recepient through an SMTP server
/// </summary>
/// <param name="address">recepient e-mail</param>
/// <param name="msg">message</param>
/// <returns>true on successful delivery</returns>
internal override bool Send(string address, NewsletterServer.Message msg)
{
try {
var mail = new MailMessage(defaultSender, address, msg.subject, msg.text);
try {
GetClient().Send(mail);
return true;
} catch (Exception e) {
return false;
}
} catch (FormatException e) {
return false;
}
}
/// <summary>
/// Fetches a configured SMTP client
/// </summary>
/// <returns>ready-to-use SMTP client</returns>
SmtpClient GetClient()
{
return new SmtpClient();
}
}
}<file_sep>/DeliveryServer/TransferAgent/MessageTransferAgent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DeliveryServer.TransferAgent
{
internal abstract class MessageTransferAgent
{
/// <summary>
/// Sends specified message to an address
/// </summary>
/// <param name="address">destination address</param>
/// <param name="msg">message entity</param>
/// <returns>true on successful delivery</returns>
internal abstract bool Send(string address, NewsletterServer.Message msg);
}
}<file_sep>/NewsletterServer/Services/IAuthService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace NewsletterServer
{
[ServiceContract]
public interface IAuthService
{
/// <summary>
/// Returns auth key for subsequent requests for authorization in other newsletter services
/// On unsuccessful login, return an empty string
/// </summary>
/// <param name="username">username to authenticate with</param>
/// <param name="password"><PASSWORD> to authenticate with</param>
/// <returns>string with authentication key</returns>
[OperationContract]
string GetAuthKey(string username, string password);
}
}
<file_sep>/ClientSide/ViewModel/WorkspaceViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Data;
using ClientSide.Properties;
using ClientSide.ViewModel.Workspace;
namespace ClientSide.ViewModel
{
class WorkspaceViewModel : ViewModelBase
{
#region Fields
public string AuthKey { get; set; }
ObservableCollection<ViewModelBase> _workspaces;
ViewModelBase _selectedItem;
public ViewModelBase SelectedWorkspace
{
get { return _selectedItem; }
set
{
_selectedItem = value;
base.OnPropertyChanged("SelectedWorkspace");
}
}
#endregion
public WorkspaceViewModel(string authKey)
{
base.DisplayName = "Newsletter Composer";
AuthKey = authKey;
}
#region Workspaces
/// <summary>
/// Returns the collection of available workspaces to display.
/// A 'workspace' is a ViewModel that can request to be closed.
/// </summary>
public ObservableCollection<ViewModelBase> Workspaces
{
get
{
if (_workspaces == null) {
var msgService = new ClientSide.Model.MessageService(AuthKey);
var svm = new StatusViewModel(msgService);
// Switch to status page after queing a message
msgService.MessageSent += delegate(object sender, MessageSentEventArgs args)
{
SelectedWorkspace = svm;
};
msgService.MessageSent += svm.OnMessageSent;
_workspaces = new ObservableCollection<ViewModelBase> {
new SubscriberListViewModel(new ClientSide.Model.SubscriberService(AuthKey)),
new ComposeViewModel(msgService),
svm,
};
SelectedWorkspace = _workspaces.First();
}
return _workspaces;
}
}
void SetActiveWorkspace(WorkspaceViewModel workspace)
{
System.Diagnostics.Debug.Assert(this.Workspaces.Contains(workspace));
ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Workspaces);
if (collectionView != null)
collectionView.MoveCurrentTo(workspace);
SelectedWorkspace = workspace;
}
#endregion // Workspaces
}
}
<file_sep>/DeliveryServer/TransferAgent/MessageProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DeliveryServer.TransferAgent
{
/// <summary>
/// General message provider
///
/// Possible sources: database, web service, etc.
/// </summary>
internal abstract class MessageProvider
{
/// <summary>
/// Gets a list of messages waiting to be sent
/// </summary>
/// <returns>list of messages to be sent</returns>
internal abstract List<Message> GetUndeliveredMessages();
}
}<file_sep>/ClientSide/ViewModel/LoginEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClientSide.ViewModel
{
/// <summary>
/// Used to hold arguments received upon authentication
/// </summary>
class LoginEventArgs : EventArgs
{
public string AuthKey { get; set; }
public LoginEventArgs(string authKey)
{
AuthKey = authKey;
}
}
}
| 410702120ee1ecedec6394c50890c8b398409e14 | [
"C#"
] | 30 | C# | vvondra/NewsletterServer | 6e585ca702ca46186842a6f5d035166e2ca0d1e7 | 8ad2d4b7fa57f9259d8c3faa7340f229e2045e1e |
refs/heads/master | <file_sep>import type { LanguagePattern } from '../types';
export const Markdown: LanguagePattern[] = [
// headings
{ pattern: /^(#){2,6}\s.+/, type: 'keyword' },
// headings alternate syntax
{ pattern: /^(?!!)(=|-){2,}(?<!>)$/, type: 'meta.module' },
// images
{ pattern: /(!)?\[.+\]\(.+\)/, type: 'keyword' },
// links 2
{ pattern: /\[.+\]\[.+\]/, type: 'keyword' },
// links 3
{ pattern: /^\[.+\]:\s?(<)?(http)?/, type: 'keyword' },
// blockquotes
{ pattern: /^(> .*)+/, type: 'macro' },
// code block
{ pattern: /^```([A-Za-z0-9#_]+)?$/, type: 'keyword' },
// frontmatter
{ pattern: /^---$/, type: 'meta.module', nearTop: true },
];
<file_sep>import { test } from 'uvu';
import * as assert from 'uvu/assert';
import detectLang from '../src';
test('hello world', () => {
const code = detectLang(`IO.puts :stderr, "Goodbye, World!"`);
assert.equal(code.language, 'Elixir');
});
test('fizz buzz', () => {
const code = detectLang(`defmodule FizzBuzz do
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz"
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
def fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
def fizzbuzz(n), do: n
end
Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)`);
assert.equal(code.language, 'Elixir');
});
test('anagrams', () => {
const code = detectLang(`defmodule Anagrams do
def find(file) do
File.read!(file)
|> String.split
|> Enum.group_by(fn word -> String.codepoints(word) |> Enum.sort end)
|> Enum.group_by(fn {_,v} -> length(v) end)
|> Enum.max
|> print
end
defp print({_,y}) do
Enum.each(y, fn {_,e} -> Enum.sort(e) |> Enum.join(" ") |> IO.puts end)
end
end
Anagrams.find("unixdict.txt")`);
assert.equal(code.language, 'Elixir');
});
test('bubble sort', () => {
const code = detectLang(`defmodule Sort do
def bsort(list) when is_list(list) do
t = bsort_iter(list)
if t == list, do: t, else: bsort(t)
end
def bsort_iter([x, y | t]) when x > y, do: [y | bsort_iter([x | t])]
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])]
def bsort_iter(list), do: list
end`);
assert.equal(code.language, 'Elixir');
});
test('heap sort', () => {
const code = detectLang(`defmodule Sort do
def heapSort(list) do
len = length(list)
heapify(List.to_tuple(list), div(len - 2, 2))
|> heapSort(len-1)
|> Tuple.to_list
end
defp heapSort(a, finish) when finish > 0 do
swap(a, 0, finish)
|> siftDown(0, finish-1)
|> heapSort(finish-1)
end
defp heapSort(a, _), do: a
defp heapify(a, start) when start >= 0 do
siftDown(a, start, tuple_size(a)-1)
|> heapify(start-1)
end
defp heapify(a, _), do: a
defp siftDown(a, root, finish) when root * 2 + 1 <= finish do
child = root * 2 + 1
if child + 1 <= finish and elem(a,child) < elem(a,child + 1), do: child = child + 1
if elem(a,root) < elem(a,child),
do: swap(a, root, child) |> siftDown(child, finish),
else: a
end
defp siftDown(a, _root, _finish), do: a
defp swap(a, i, j) do
{vi, vj} = {elem(a,i), elem(a,j)}
a |> put_elem(i, vj) |> put_elem(j, vi)
end
end
(for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect |> Sort.heapSort |> IO.inspect`);
assert.equal(code.language, 'Elixir');
});
test('merge sort', () => {
const code = detectLang(`defmodule Sort do
def merge_sort(list) when length(list) <= 1, do: list
def merge_sort(list) do
{left, right} = Enum.split(list, div(length(list), 2))
:lists.merge( merge_sort(left), merge_sort(right))
end
end`);
assert.equal(code.language, 'Elixir');
});
test('quick sort', () => {
const code = detectLang(`defmodule Sort do
def qsort([]), do: []
def qsort([h | t]) do
{lesser, greater} = Enum.split_with(t, &(&1 < h))
qsort(lesser) ++ [h] ++ qsort(greater)
end
end`);
assert.equal(code.language, 'Elixir');
});
test('ludic numbers', () => {
const code = detectLang(`defmodule Ludic do
def numbers(n \\ 100000) do
[h|t] = Enum.to_list(1..n)
numbers(t, [h])
end
defp numbers(list, nums) when length(list) < hd(list), do: Enum.reverse(nums, list)
defp numbers([h|_]=list, nums) do
Enum.drop_every(list, h) |> numbers([h | nums])
end
def task do
IO.puts "First 25 : #{inspect numbers(200) |> Enum.take(25)}"
IO.puts "Below 1000: #{length(numbers(1000))}"
tuple = numbers(25000) |> List.to_tuple
IO.puts "2000..2005th: #{ inspect for i <- 1999..2004, do: elem(tuple, i) }"
ludic = numbers(250)
triple = for x <- ludic, x+2 in ludic, x+6 in ludic, do: [x, x+2, x+6]
IO.puts "Triples below 250: #{inspect triple, char_lists: :as_lists}"
end
end
Ludic.task`);
assert.equal(code.language, 'Elixir');
});
test('happy numbers', () => {
const code = detectLang(`defmodule Happy do
def task(num) do
Process.put({:happy, 1}, true)
Stream.iterate(1, &(&1+1))
|> Stream.filter(fn n -> happy?(n) end)
|> Enum.take(num)
end
defp happy?(n) do
sum = square_sum(n, 0)
val = Process.get({:happy, sum})
if val == nil do
Process.put({:happy, sum}, false)
val = happy?(sum)
Process.put({:happy, sum}, val)
end
val
end
defp square_sum(0, sum), do: sum
defp square_sum(n, sum) do
r = rem(n, 10)
square_sum(div(n, 10), sum + r*r)
end
end
IO.inspect Happy.task(8)`);
assert.equal(code.language, 'Elixir');
});
test('floyd warshall', () => {
const code = detectLang(`defmodule Floyd_Warshall do
def main(n, edge) do
{dist, next} = setup(n, edge)
{dist, next} = shortest_path(n, dist, next)
print(n, dist, next)
end
defp setup(n, edge) do
big = 1.0e300
dist = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j},(if i==j, do: 0, else: big)}
next = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j}, nil}
Enum.reduce(edge, {dist,next}, fn {u,v,w},{dst,nxt} ->
{ Map.put(dst, {u,v}, w), Map.put(nxt, {u,v}, v) }
end)
end
defp shortest_path(n, dist, next) do
(for k <- 1..n, i <- 1..n, j <- 1..n, do: {k,i,j})
|> Enum.reduce({dist,next}, fn {k,i,j},{dst,nxt} ->
if dst[{i,j}] > dst[{i,k}] + dst[{k,j}] do
{Map.put(dst, {i,j}, dst[{i,k}] + dst[{k,j}]), Map.put(nxt, {i,j}, nxt[{i,k}])}
else
{dst, nxt}
end
end)
end
defp print(n, dist, next) do
IO.puts "pair dist path"
for i <- 1..n, j <- 1..n, i != j,
do: :io.format "~w -> ~w ~4w ~s~n", [i, j, dist[{i,j}], path(next, i, j)]
end
defp path(next, i, j), do: path(next, i, j, [i]) |> Enum.join(" -> ")
defp path(_next, i, i, list), do: Enum.reverse(list)
defp path(next, i, j, list) do
u = next[{i,j}]
path(next, u, j, [u | list])
end
end
edge = [{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}]
Floyd_Warshall.main(4, edge)`);
assert.equal(code.language, 'Elixir');
});
test.run();
<file_sep>import { test } from 'uvu';
import * as assert from 'uvu/assert';
import detectLang from '../src/index';
test('1', () => {
const code = detectLang(`{
"key": "value",
"keys": "must always be enclosed in double quotes",
"numbers": 0,
"strings": "Hellø, wørld. All unicode is allowed, along with \\"escaping\\".",
"has bools?": true,
"nothingness": null,
"big number": 1.2e+100,
"objects": {
"comment": "Most of your structure will come from objects.",
"array": [0, 1, 2, 3, "Arrays can have anything in them.", 5],
"another object": {
"comment": "These things can be nested, very useful."
}
},
"silliness": [
{
"sources of potassium": ["bananas"]
},
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, "neo"],
[0, 0, 0, 1]
]
],
"alternative style": {
"comment": "check this out!"
, "comma position": "doesn't matter, if it's before the next key, it's valid"
, "another comment": "how nice"
},
"whitespace": "Does not matter.",
"that was short": "And done. You now know everything JSON has to offer."
}`);
assert.equal(code.language, 'JSON');
});
test('2', () => {
const code = detectLang(`{
"name": "<NAME>",
"age": 43,
"address": {
"street": "10 Downing Street",
"city": "London"
},
"phones": [
"+44 1234567",
"+44 2345678"
]
}`);
assert.equal(code.language, 'JSON');
});
test('3', () => {
const code = detectLang(`{
"keywords": [
"JSON",
"server",
"fake",
"REST",
"API",
"prototyping",
"mock",
"mocking",
"test",
"testing",
"rest",
"data",
"dummy",
"sandbox"
]
}`);
assert.equal(code.language, 'JSON');
});
test('4', () => {
const code = detectLang(`{
"/api/": "/",
"/blog/:resource/:id/show": "/:resource/:id",
"/blog/:category": "/posts?category=:category"
}`);
assert.equal(code.language, 'JSON');
});
test('5', () => {
const code = detectLang(`{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}`);
assert.equal(code.language, 'JSON');
});
test('6', () => {
const code = detectLang(`{
"middlewares": ["./fixtures/middlewares/en", "./fixtures/middlewares/jp"]
}`);
assert.equal(code.language, 'JSON');
});
test.run();
<file_sep>import { test } from 'uvu';
import * as assert from 'uvu/assert';
import detectLang from '../src/index';
test('heading 2', () => {
const code = detectLang('## Heading level 2');
assert.equal(code.language, 'Markdown');
});
test('heading 3', () => {
const code = detectLang('### Heading level 3');
assert.equal(code.language, 'Markdown');
});
test('heading 4', () => {
const code = detectLang('#### Heading level 4');
assert.equal(code.language, 'Markdown');
});
test('heading 5', () => {
const code = detectLang('##### Heading level 5');
assert.equal(code.language, 'Markdown');
});
test('heading 6', () => {
const code = detectLang('###### Heading level 6');
assert.equal(code.language, 'Markdown');
});
test('heading 1 alternate syntax', () => {
const code = detectLang('Heading level 1\n============');
assert.equal(code.language, 'Markdown');
});
test('heading 2 alternate syntax', () => {
const code = detectLang('Heading level 1\n------------');
assert.equal(code.language, 'Markdown');
});
test('images', () => {
const code = detectLang(``);
assert.equal(code.language, 'Markdown');
});
test('links', () => {
const code = detectLang(`[GitHub](http://github.com)`);
assert.equal(code.language, 'Markdown');
});
test('links 2', () => {
const code = detectLang(`[GitHub][http://github.com]`);
assert.equal(code.language, 'Markdown');
});
test('links 3', () => {
const code = detectLang(`[1]: https://en.wikipedia.org/wiki/Hobbit#Lifestyle`);
assert.equal(code.language, 'Markdown');
});
test('links 4', () => {
const code = detectLang(`[1]: <https://en.wikipedia.org/wiki/Hobbit#Lifestyle> "Hobbit lifestyles"`);
assert.equal(code.language, 'Markdown');
});
test('blockquotes', () => {
const code = detectLang(`> We're living the future so
> the present is our past.`);
assert.equal(code.language, 'Markdown');
});
test('example 1', () => {
const code = detectLang(`# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [12.2.0] - 2021-08-02
### Added
- Ordered lists: add order value to token info.
### Fixed
- Always suffix indented code block with a newline, #799.
## [12.1.0] - 2021-07-01
### Changed
- Updated CM spec compatibility to 0.30.
## [12.0.6] - 2021-04-16
### Fixed
- Newline in \`alt\` should be rendered, #775.
## [12.0.5] - 2021-04-15
### Fixed
- HTML block tags with \`===\` inside are no longer incorrectly interpreted as headers, #772.
- Fix table/list parsing ambiguity, #767.
## [12.0.4] - 2020-12-20
### Fixed
- Fix crash introduced in \`12.0.3\` when processing strikethrough (\`~~\`) and similar plugins, #742.
- Avoid fenced token mutation, #745.
## [12.0.3] - 2020-12-07
### Fixed
- \`[](<foo<bar>)\` is no longer a valid link.
- \`[](url (xxx())\` is no longer a valid link.
- \`[](url xxx)\` is no longer a valid link.
- Fix performance issues when parsing links (#732, #734), backticks, (#733, #736),
emphases (#735), and autolinks (#737).
- Allow newline in \`<? ... ?>\` in an inline context.
- Allow \`<meta>\` html tag to appear in an inline context.
## [12.0.2] - 2020-10-23
### Fixed
- Three pipes (\`|\n|\n|\`) are no longer rendered as a table with no columns, #724.
## [12.0.1] - 2020-10-19
### Fixed
- Fix tables inside lists indented with tabs, #721.
## [12.0.0] - 2020-10-14
### Added
- \`.gitattributes\`, force unix eol under windows, for development.
### Changed
- Added 3rd argument to \`highlight(code, lang, attrs)\`, #626.
- Rewrite tables according to latest GFM spec, #697.
- Use \`rollup.js\` to browserify sources.
- Drop \`bower.json\` (bower reached EOL).
- Deps bump.
- Tune \`specsplit.js\` options.
- Drop \`Makefile\` in favour of npm scrips.
### Fixed
- Fix mappings for table rows (amended fix made in 11.0.1), #705.
- \`%25\` is no longer decoded in beautified urls, #720.
[12.2.0]: https://github.com/markdown-it/markdown-it/compare/12.1.0...12.2.0
[12.1.0]: https://github.com/markdown-it/markdown-it/compare/12.0.6...12.1.0
[12.0.6]: https://github.com/markdown-it/markdown-it/compare/12.0.5...12.0.6
[12.0.5]: https://github.com/markdown-it/markdown-it/compare/12.0.4...12.0.5
[12.0.4]: https://github.com/markdown-it/markdown-it/compare/12.0.3...12.0.4
[12.0.3]: https://github.com/markdown-it/markdown-it/compare/12.0.2...12.0.3
[12.0.2]: https://github.com/markdown-it/markdown-it/compare/12.0.1...12.0.2
[12.0.1]: https://github.com/markdown-it/markdown-it/compare/12.0.0...12.0.1
[12.0.0]: https://github.com/markdown-it/markdown-it/compare/11.0.1...12.0.0`);
assert.equal(code.language, 'Markdown');
});
test('example 2', () => {
const code = detectLang(`---
draft: false
title: Why I use Linux instead of other OS
date: 2020-02-27
desc: A post where I try to explain why I use this beautiful and awesome operating system called Linux
tags:
- linux
---
# Table of Content
# Introduction
Hello internet people of the internet! In this post, I will explain the reason why I use Linux and how I know Linux. Well, the correct term here should be GNU/Linux but it's _way_ too long let's be honest. So, whenever I say Linux, what I mean is GNU/Linux. Let's start with how I know Linux.
# Origin
## My first laptop
It all started when I want to buy my first laptop. Roughly about 9 months ago. It runs Intel Celeron N4000 processor, which is pretty bad (yeah, I know). At that time, I didn't know about Thinkpad which most of people said has the best value for its price. So, I do some quick research on how ~~slow~~ fast this processor runs. It turns out, it's pretty bad.
## How I know Linux
I heard a lot of people say that Windows 10 is heavy for a slow processor like mine. It's bloat, it's too heavy, too many things going on, there's some malicious virus that can easily infect your computer, yaddi yadda. To be honest, I became a bit sad at that time. Then I came across a post on Facebook saying something like "Try Linux if your laptop/pc isn't powerful enough to run windows." Then I start to wonder, what is this guy talking about? Linux? I never heard that before.
I became interested in that. Bare in mind that I don't have any laptop yet. I don't know why I love to read some articles about Linux and joined on several groups even if I don't have any machine that runs Linux (I even help people solve issues that they have on their Linux machine even though I don't have any laptop. That's quite something if you ask me). It's an interesting operating system (mainly because I never heard of it). Somehow, I like the fact that most people don't use it. I like to be different. Finally, after about a month, I bought my very first laptop.
## My first distribution
Linux has so many distributions. Like, a gazillion of them. But from what I observe, there are only a few "big boys" that stands out from the others. Some of them are Debian, Ubuntu, Arch, Manjaro, OpenSUSE, Fedora, RHEL, PopOS, etc. I got confused easily on which one is the best for me. Then I decided to check what's that guy is using on Facebook.
The guy on Facebook runs [Manjaro Linux](https://manjaro.org). I was like, "Why did he choose that? That's a silly name for Linux." Not gonna lie, that's my first impression lol. About a week later, I tried to install one of Linux distribution after getting convinced enough. The one that I chose was [Linux Mint](https://linuxmint.com). At that time, I installed Linux Mint 19.1 XFCE Edition. I was so happy to be able to install Linux. Unfortunately, I lost my first screenshot on Linux Mint.
## Changing distribution
A month has passed. I feel pretty comfortable with Linux. Then, there was this news saying that Ubuntu dropped their support for 32bit libraries. Do you remember that news? I was like, "Well, that's fine I guess. What's wrong with that?" Little did I know, 32bit libraries are what most games depend on. Then I started to panic and confused lmao.
I was like, "Oh come on. I'm already comfortable with my current setup. I still want to play some games but I don't want to change my distribution." Yep, that's literally what I said. And you know what? f*** it. Imma change my distribution. I decided to choose Manjaro since it's not based on Ubuntu. Yep, the one that I've mentioned before. A distribution that I thought has a stupid name (I felt so guilty now lol). Then I started to think, "Who cares about names anyway. As long as it is usable, it's good."
Finally, I installed it. I took a quick screenshot after installing it because I was so excited. Here, take a look!

Manjaro is based on Arch. Some people say that it's Arch without all of its fuss. I mean, it's true. At the time I'm writing this, I use Arch. For beginners that want to try Archlinux, it's a good starting point. I ended up using it for nearly 8 months. It was a great experience.
# Why Linux?
So, why do I use Linux then? Well, let me give you a quick list of why Linux is better than the other OS
- **It's free**
Linux is free both in price and free as in freedom. You don't have to pay for license and you can do anyting you want with it. You can customize your Desktop Environment (look and feel) or even build your very own kernel!
- **It's lightweight**
Linux is so lightweight. It can bring your old hardware to life. There's this joke that says "Linux can run on everything". Starting from [business card](https://www.thirtythreeforty.net/posts/2019/12/my-business-card-runs-linux/) (yes, there's someone out there who built their business card with Linux inside it) until your high end $50000 beast or whatever.
- **It's secure**
Linux is very secure. That's why most of servers around the world is using Linux for it. You don't have to worry to install antivirus to prevent ransomware getting into your system. No need to worry on that stuff.
- **There's always something to learn**
Like, seriously. You can always learn something new everyday. There are so much good stuff that you can learn from Linux. If you like something challenging, go ahead and try Linux.
- **Package Manager**
Now this is the stuff that makes me really love Linux. Linux has a centralized place to download any app that you want. You don't need to go to some kind of obscure website and find the correct download link. You just need to \`apt install\` or \`pacman - S\` any package that you want and it's totally secure.
# Conclusion
At first, I'm afraid that I can't install Windows on my new laptop. Who would've thought that in the end, I use Archlinux which some people say that it's difficult to install. I think it's not that hard, follow the wiki and you're set (said someone who had failed to install Archlinux 3 times lmao).
Alright, this post will end right here. I might post why I use VIM/Window Managers next time. See ya in the next post everyone, have a good day!`);
assert.equal(code.language, 'Markdown');
});
test('example 3', () => {
const code = detectLang(`---
name: 'blog-using-vue-nuxt-markdown'
title: Website with blog and portfolio using Vue.js + Nuxt + Markdown
year: 1 January 2019
color: '#8e7964'
trans: 'blog-usando-vue-nuxt-markdown'
id: 'vue-nuxt-blog'
description: |
How I created my new website with portfolio and blog in two languages. What technology I used and why.
---
## Why did I re-do my website with Nuxt?
Although some of you already know me, I am [<NAME>](https://twitter.com/MarinaAisa), UX Engineer (design and front-end) and I currently work at [Holaluz](https://www.holaluz.com/en).
Last year, 2018, I was very focused on learning more about JavaScript, which was a pending subject and at the same time I learnt [Vue.js](https://vuejs.org/). Meanwhile at my workplace, we started using [Nuxt.js](https://nuxtjs.org/) a framework on VueJS to remake both company's static and dynamic (SPA) webapps into components and create a design system with it.
My previous website was made with [Middleman](https://middlemanapp.com/) a static pages generator based on Ruby, so I took the opportunity to redo my website with Nuxt and Vue, in order to:
- To learn
- Improve performance
- Add functionality as a blog and portfolio system
- Add two languages, Spanish and English, **also in blog posts** but independently, since I guess I won't translate every post in both languages.
What attracts me the most of Nuxt is the philosophy *serverless* (Nuxt can also be SSR tho) and the static prerendering it provides to SPA applications. Briefly, with this stack you can combine the best of a static website: compiled HTML -> what leads to a better SEO, plus the best of a *single page application*: Webpack, cache optimizations, lazy-loading, functions and asynchronous data...
## But where do I get the content if I don't have a server?
Nuxt, by following the architecture [JAMStack](https://jamstack.org/) is built to get content through APIs, so many people use headless CMSs like [Contentful](https://www.contentful.com/) or [Prismic](https://prismic.io/). At first I thought they were interesting options but I realized that it wasn't necessary for a website like mine since CMSs are oriented to be used by people without technical knowledge, besides they are expensive, they save assets on their own servers and they aren't the best option if I wanted to have the best performance.
**Therefore, I decided to use a Markdowns system that I store in Github and call dynamically.**
### Importing posts on the main page depending on the language
Using the asynchronous function \`asyncData\` that Nuxt provides only in its pages (it is not avalaible in its components) I import the Markdowns that I have saved in the folder \`content\` of the project. Later I return them in the form of a promise as an array of objects. As you can see below, this import depends on the constant \`blogs\` which will be the array \`blogsEs\` or \`blogsEn\` depending on the language of the page stored on the Vuex's state.
\`\`\`javascript
import blogsEn from '~/contents/en/blogsEn.js';
import blogsEs from '~/contents/es/blogsEs.js'
async asyncData({ app }) {
const blogs = app.i18n.locale === 'en' ? blogsEn : blogsEs;
async function asyncImport(blogName) {
const wholeMD = await import(\`~/content/\${app.i18n.locale}/blog/\${blogName}.md\`);
return wholeMD.attributes;
}
return Promise.all(blogs.map(blog => asyncImport(blog)))
.then((res) => {
return {
blogs: res
};
});
}
\`\`\`
The reason why I'm importing the arrays containing the blogs names is because I want to use it also to generate the static pages through the object [generate](https://nuxtjs.org/api/configuration-generate/) in the Nuxt configuration, file \`nuxt.config.js\`.
\`\`\`javascript;
import blogsEn from '~/contents/en/blogsEn.js';
import blogsEs from '~/contents/es/blogsEs.js';
generate: {
routes: [
'/es', '404'
]
.concat(blogsEn.map(blog => \`/blog/\${blog}\`))
.concat(blogsEs.map(blog => \`es/blog/\${blog}\`));
}
\`\`\`
### Generating dynamic pages from Markdown files
Nuxt has a very interesting functionality, the creation of [dynamic routes](https://nuxtjs.org/guide/routing/#dynamic-routes).
In the next import I use the function \`asyncData\` instead of \`data\` as it's usual in Vue, to first import each Markdown and then return a new object with the information I want to use in the template of the page.
**The URL will be equal to each markdown file's name.**
In the case that the md file doesn't exist it will simply go to error page 404.
\`\`\`javascript
async asyncData({ params, app }) {
const fileContent = await import(\`~/contents/\${app.i18n.locale}/blog/\${params.slug}.md\`);
const attr = fileContent.attributes;
return {
colors: attr.colors,
date: attr.date,
description: attr.description,
id: attr.id,
name: params.slug,
related: attr.related,
renderFunc: fileContent.vue.render,
staticRenderFuncs: fileContent.vue.staticRenderFns,
title: attr.title,
urlTranslation: attr.urlTranslation
};
}
\`\`\`
If we wanted to create a portfolio in the future, it would be exactly the same as the blog. We would create within \`contents\` a folder called \`portfolio\` and we would do the same process that we have done with \`blogs\`.
The loader for Webpack Markdown files that I use is: [frontmatter-markdown-loader](https://www.npmjs.com/package/frontmatter-markdown-loader) that allows me to put Vue components inside markdown files, as well as extract the \`frontmatter\` attributes as they do static generators like Jekyll. For making the code look pretty I apply: [HighlightJS](https://highlightjs.org/)
## Let's talk about performance
Do you remember that before I told you that one of my motivations for creating this website was to have a blog that had a good performance?
With Nuxt I have achieved it, and I still have a lot to optimize.
If you have arrived here, you have probably thought: *"OMG Marina, you could just have made a blog in [Medium](https://medium.com/) and save you all this crazy work"* and right now you're going to understand why I don't like Medium.
While writing in Medium **you don't have control over your blog** such as CSS, SEO, adding functionalities, **Medium owns your content**, you have a limit of articles read for free... and **their performance seems quite bad**
Thanks to Google's tool [Lighthouse](https://developers.google.com/web/fundamentals/performance/audit/) we can analyze and compare Medium with my website.
<image-responsive
imageURL="blog/vue-nuxt-blog/performance.jpg"
:width="'952'"
:height="'509'"
alt="performance" />
As you can see, Medium does a lot of things well, but performance is not one of them. This translates into user experience as a very slow load, especially on mobile devices. **Because performance is user experience.** We'll talk more about it another day.
The interesting thing here is that with Nuxt I managed to reach a **94%** performance compared to 40% offered by Medium in the first load, but the best thing is that since using cache systems, **the second load on my website the performance is 100%** while Medium scores 60%.
## Web in two languages
To translate the web in English and Spanish I use [nuxt-i18n](https://github.com/nuxt-community/nuxt-i18n). It is a layer above [vue-i18n](https://github.com/kazupon/vue-i18n) which has lazy-loading translations. *Nuxt-i18n* automates how translations are worked on the Vue router, simplifying it for Nuxt. I recommend it for the router, although it has some things that I couldn't managed to make it work as the redirection cookie based on the browser language. But it's a problem that you have to accept if you use a new framework like Nuxt is.
## Features and improvements I want to add in the future
- I am not very happy with the amount of JS that I am putting into the web, I have more than 100k of synchronous JS and I want to reduce it. I still have to figure out how. My relationship with JS is love/hate. On the one hand I love everything you can do with it and on the other I hate it because it has a terrible cost on the performance of the page.
- Adding a portfolio system with dynamic pages like the blog.
- Improvements in design and usability.
- Making the web totally accessible from the design to the code.
- Cleaning CSS that I don't use and try to reduce it.
- I criticize a lot Medium but I really like its design and some of its features, in fact I would like to add its famous *clap* button to my website.
- Add comments to each post.
- Add similar posts to the one you've read.
## Things about the webapp that I'll write another day
- Lazy loading of components and images in Nuxt, I will tell you which packages I use and the component I did to render a first image as a *placeholder* in base64 and afterwards asynchronously the final image.
- How to use \`analyze\` of Nuxt to analyze the JS generated by Webpack in our app and to optimize it.
- The big mistake I made along the way: Vuex. <nuxt-link to="/blog/vuex-what-is-when-use-it">You can read it here</nuxt-link>
- How to put emojis on your website through a sprite made in SCSS so that they always look the same regardless of the browser or device.
- Loading Vue asynchronous components with the practical example of the travel map that is in the home page.
I thought about publishing a starter about it but being realist, I wouldn't have enough time to maintain it. I think this post explains how to do it very well, but if you have any doubt left, you can always contact me at my email: [<EMAIL>](mailto:<EMAIL>).
Since I don't have a comments section on each post, I would love to continue the conversation on [Twitter](https://twitter.com/MarinaAisa). All feedback is welcome! If you think there is something that it can be improved, you would help me a lot.`);
assert.equal(code.language, 'Markdown');
});
test('example 4', () => {
const code = detectLang(`# Visual Studio Code - Open Source ("Code - OSS")
[](https://github.com/microsoft/vscode/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc)
[](https://github.com/microsoft/vscode/issues?utf8=✓&q=is%3Aissue+is%3Aopen+label%3Abug)
[](https://gitter.im/Microsoft/vscode)
## The Repository
This repository ("\`Code - OSS\`") is where we (Microsoft) develop the [Visual Studio Code](https://code.visualstudio.com) product together with the community. Not only do we work on code and issues here, we also publish our [roadmap](https://github.com/microsoft/vscode/wiki/Roadmap), [monthly iteration plans](https://github.com/microsoft/vscode/wiki/Iteration-Plans), and our [endgame plans](https://github.com/microsoft/vscode/wiki/Running-the-Endgame). This source code is available to everyone under the standard [MIT license](https://github.com/microsoft/vscode/blob/main/LICENSE.txt).
## Visual Studio Code
<p align="center">
<img alt="VS Code in action" src="https://user-images.githubusercontent.com/35271042/118224532-3842c400-b438-11eb-923d-a5f66fa6785a.png">
</p>
[Visual Studio Code](https://code.visualstudio.com) is a distribution of the \`Code - OSS\` repository with Microsoft specific customizations released under a traditional [Microsoft product license](https://code.visualstudio.com/License/).
[Visual Studio Code](https://code.visualstudio.com) combines the simplicity of a code editor with what developers need for their core edit-build-debug cycle. It provides comprehensive code editing, navigation, and understanding support along with lightweight debugging, a rich extensibility model, and lightweight integration with existing tools.
Visual Studio Code is updated monthly with new features and bug fixes. You can download it for Windows, macOS, and Linux on [Visual Studio Code's website](https://code.visualstudio.com/Download). To get the latest releases every day, install the [Insiders build](https://code.visualstudio.com/insiders).
## Contributing
There are many ways in which you can participate in this project, for example:
* [Submit bugs and feature requests](https://github.com/microsoft/vscode/issues), and help us verify as they are checked in
* Review [source code changes](https://github.com/microsoft/vscode/pulls)
* Review the [documentation](https://github.com/microsoft/vscode-docs) and make pull requests for anything from typos to additional and new content
If you are interested in fixing issues and contributing directly to the code base,
please see the document [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute), which covers the following:
* [How to build and run from source](https://github.com/microsoft/vscode/wiki/How-to-Contribute)
* [The development workflow, including debugging and running tests](https://github.com/microsoft/vscode/wiki/How-to-Contribute#debugging)
* [Coding guidelines](https://github.com/microsoft/vscode/wiki/Coding-Guidelines)
* [Submitting pull requests](https://github.com/microsoft/vscode/wiki/How-to-Contribute#pull-requests)
* [Finding an issue to work on](https://github.com/microsoft/vscode/wiki/How-to-Contribute#where-to-contribute)
* [Contributing to translations](https://aka.ms/vscodeloc)
## Feedback
* Ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/vscode)
* [Request a new feature](CONTRIBUTING.md)
* Upvote [popular feature requests](https://github.com/microsoft/vscode/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc)
* [File an issue](https://github.com/microsoft/vscode/issues)
* Follow [@code](https://twitter.com/code) and let us know what you think!
See our [wiki](https://github.com/microsoft/vscode/wiki/Feedback-Channels) for a description of each of these channels and information on some other available community-driven channels.
## Related Projects
Many of the core components and extensions to VS Code live in their own repositories on GitHub. For example, the [node debug adapter](https://github.com/microsoft/vscode-node-debug) and the [mono debug adapter](https://github.com/microsoft/vscode-mono-debug) have their own repositories. For a complete list, please visit the [Related Projects](https://github.com/microsoft/vscode/wiki/Related-Projects) page on our [wiki](https://github.com/microsoft/vscode/wiki).
## Bundled Extensions
VS Code includes a set of built-in extensions located in the [extensions](extensions) folder, including grammars and snippets for many languages. Extensions that provide rich language support (code completion, Go to Definition) for a language have the suffix \`language-features\`. For example, the \`json\` extension provides coloring for \`JSON\` and the \`json-language-features\` provides rich language support for \`JSON\`.
## Development Container
This repository includes a Visual Studio Code Remote - Containers / GitHub Codespaces development container.
- For [Remote - Containers](https://aka.ms/vscode-remote/download/containers), use the **Remote-Containers: Clone Repository in Container Volume...** command which creates a Docker volume for better disk I/O on macOS and Windows.
- For Codespaces, install the [Github Codespaces](https://marketplace.visualstudio.com/items?itemName=GitHub.codespaces) extension in VS Code, and use the **Codespaces: Create New Codespace** command.
Docker / the Codespace should have at least **4 Cores and 6 GB of RAM (8 GB recommended)** to run full build. See the [development container README](.devcontainer/README.md) for more information.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [<EMAIL>](mailto:<EMAIL>) with any additional questions or comments.
## License
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the [MIT](LICENSE.txt) license.`);
assert.equal(code.language, 'Markdown');
});
test.run();
<file_sep>import type { LanguagePattern } from '../types';
export const JSON: LanguagePattern[] = [
// object declaration on top
{ pattern: /^\{$/, type: 'meta.module', nearTop: true },
// normal data type
{ pattern: /^\s*".+":\s*(".+"|[0-9]+|null|true|false)(,)?$/, type: 'keyword' },
// object and array
{ pattern: /^\s*".+":\s*(\{|\[)$/, type: 'keyword' },
// inline key/value pair in object
// e.g { "id": 1, "body": "<PASSWORD>", "postId": 1 }
{ pattern: /^\s*".+":\s*\{(\s*".+":\s*(".+"|[0-9]+|null|true|false)(,)?\s*){1,}\}(,)?$/, type: 'keyword' },
// inline value in array
// e.g "middlewares": ["./fixtures/middlewares/en", "./fixtures/middlewares/jp"]
{ pattern: /\s*".+"\s*\[\s*((".+"|[0-9]+|null|true|false)(,)?\s*){1,}\](,)?$/, type: 'keyword' },
];
<file_sep>import type { LanguagePattern } from '../types';
export const Elixir: LanguagePattern[] = [
// Modules
{ pattern: /^\s*defmodule\s+.+\s+do$/, type: 'meta.module' },
// Alias
{ pattern: /\s*alias\s+.+as:.+/, type: 'keyword.other' },
// IO.puts()
{ pattern: /IO\.puts.+/, type: 'keyword.print' },
// Anonymous func
{ pattern: /fn\s+[A-Za-z0-9_:<>()]+\s+->\s+.+(end)?$/, type: 'keyword.function' },
{ pattern: /^\s*(def|defp)\s+.+\s+do$/, type: 'keyword.function' },
{ pattern: /^\s*(if|unless|cond|case|try|defimpl|defprotocol)\s+.+\s+do$/, type: 'keyword.control' },
{ pattern: /^\s*defstruct\s+/, type: 'keyword' },
// Spec
{ pattern: /^\s*@spec\s+.+::.+/, type: 'macro' },
// Lists
{ pattern: /\{:.+,.+\}/, type: 'constant.array' },
// Maps
{ pattern: /%\{(.+(=>|:).+(,)?){1,}\}/, type: 'constant.dictionary' },
];
| 3cad2a962634ea4595d6bcbb69c70a3f3bc2904d | [
"TypeScript"
] | 6 | TypeScript | vijaykrishna536/flourite | d4286d927b93a207be7930fb080848542d9c8299 | c601e11af4e63ddbc49aafde118184e3d73bbc05 |
refs/heads/master | <repo_name>Kaplaugher/rxjsAerial<file_sep>/docs/operators/readme.md
# Operators
## combineLatest
Why Use combineLatest?
This operator is best used when you have multiple, long-lived observables that rely on eachother for some calculation or determination.
Be aware that combineLatest will not emit an initial value until each observable emits at least one value. This is the same behavior as withLatestFrom and can be a gotcha as there will be no output and no error but one (or more) of your inner observables is likely not functioning as intended, or a subscription is late.

In these examples, combine latest is being used to combine observables. The first being the user$ and sortSubject$. The second example combines the user$ and filterText.
## map
Why Use Map?
The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications.

In the first example, map is used to return the data of the observable. In the second example,
## pipe
As of RxJS 5.5 observables now have a pipe method available on the instances allowing you to clean up the code by calling pipe with all our pure functions operators. It is essentially chaining operators.

In the example, pipe is used to chain all the operators on the users$ observable.
## switchMap
<file_sep>/docs/.vuepress/config.js
module.exports = {
title: "Aerial RXJS",
description: "How we use RXJS in our apps",
themeConfig: {
nav: [
{ text: 'Home', link: '/' },
{ text: 'Operators', link: '/operators/' },
{ text: 'Github', link: 'https://github.com/AirbusAerial/rxjsDocs' },
],
sidebar: 'auto'
}
}<file_sep>/docs/readme.md
# Airbus Aerial's RXJS Docs!!
## Introduction
**RxJS** is one of the hottest libraries in web development today. Offering a powerful, functional approach for dealing with events and with integration points into a growing number of frameworks, libraries, and utilities, the case for learning Rx has never been more appealing. Couple this with the ability to utilize your knowledge across nearly any language, having a solid grasp on reactive programming and what it can offer seems like a no-brainer. Here at Airbus Aerial, our goal is to harness the power of this library to make our code more performant and easier to read.
**But...**
Learning RxJS and reactive programming is hard. There's the multitude of concepts, large API surface, and fundamental shift in mindset from an imperative to declarative style. This site focuses on making these concepts approachable, the examples clear and easy to explore, and giving actual examples used in our own code!
<iframe src="https://giphy.com/embed/j3gsT2RsH9K0w" width="480" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/j3gsT2RsH9K0w">via GIPHY</a></p> | 0bb1a075480d471f9cca432c391e0fe6f48db93c | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Kaplaugher/rxjsAerial | 3f837158fa831137c76cb3d94af20a6d34545cd0 | 335a1b1b6d1d16c72adcb05d89c432f3ae808988 |
refs/heads/master | <repo_name>njoyce/lipy<file_sep>/linode/provision.py
from . import config as linode_config
from . import datacenter as linode_datacenter
from . import disk as linode_disk
from . import distribution as linode_distribution
from . import ip as linode_ip
from . import kernel as linode_kernel
from . import plan as linode_plan
from . import linode
def provision(api_key, root_password, datacenter, distribution, plan='1024',
kernel=None, disk_size=None, swap=256, payment_term=1,
private_ip=True):
"""
Create and boot a linode
:param api_key: Linode API Key.
:param root_password: The password to set for the distribution.
:param datacenter: The location of the datacenter. See
https://www.linode.com/wiki/index.php/Network
:param distribution: The Linux distribution. See
https://www.linode.com/faq.cfm#which-distributions-do-you-offer
:param plan: Size in MB of RAM for linode. See
https://manager.linode.com/signup/#plans
:param kernel: The kernel version that you want to use. See
https://www.linode.com/kernels/ The default is to use 'latest' for the
distribution that you choose.
:param disk_size: The size of the disk. The default is to use the maximum
for the plan.
:param swap: How much swap you want to create.
:param payment_term: 1 = monthly, 12 = yearly, 24 = biannually
:param private_ip: Whether to create a LAN IP. Defaults to True
"""
datacenter = linode_datacenter.get_datacenter(api_key, datacenter)
plan = linode_plan.get_plan(api_key, plan)
distribution = linode_distribution.get_distribution(api_key, distribution)
if kernel:
kernel = linode_kernel.get_kernel(api_key, kernel)
else:
kernel = 'Latest '
if distribution.x64:
kernel += '64 bit'
else:
kernel += '32 bit'
kernel = linode_kernel.get_kernel(api_key, kernel)
linode_instance = linode.create_linode(
api_key,
datacenter.id,
plan.id,
payment_term
)
try:
create_disk(
api_key,
linode_instance,
distribution,
root_password,
disk_size,
swap
)
create_config(
api_key,
linode_instance,
distribution,
kernel
)
if private_ip:
linode_ip.add_private(api_key, linode_instance.id)
linode_instance.boot()
except:
linode_instance.delete(True)
raise
return linode_instance
def create_disk(api_key, linode_obj, distribution, root_password, size=None,
swap=256, block=True):
"""
Given an existing Linode instance, create a disk from the distribution and
give it the maximum possible size (assuming that `size` is not provided).
:param api_key: Linode API Key.
:param linode_obj: The `linode` instance from `linode.create_instance` or
similar.
:param distribution: The `Distribution` instance to build the disk from.
:param root_password: The password to set for the disk.
:param size: Size to allocate for the disk. The default is to use the
maximum.
:param swap: The amount of swap to allocate for the instance.
:param block: Whether to wait for the operation to complete.
"""
jobs = []
main_disk, main_job = linode_disk.create_from_distribution(
api_key,
linode_obj.id,
distribution.id,
'{} Disk Image'.format(distribution.label),
linode_obj.plan.disk_size - swap,
root_pass=<PASSWORD>,
block=False
)
jobs.append(main_job)
if swap:
swap_disk, swap_job = linode_disk.create_swap(
api_key,
linode_obj.id,
swap,
block=False
)
jobs.append(swap_job)
if not block:
return jobs
for job in jobs:
job.wait()
def create_config(api_key, linode_obj, distribution, kernel, **extra):
if 'disk_list' not in extra:
extra['disk_list'] = linode_obj.disks
return linode_config.create_config(
api_key,
linode_obj.id,
kernel.id,
'My {} Profile'.format(distribution.label),
**extra
)
<file_sep>/linode/job.py
import time
from . import base
class JobError(Exception):
def __init__(self, job):
self.job = job
class Job(base.BaseObject):
def __init__(self, api_key, id, linode_id, action, label, entered, started,
finish, duration, message, success):
super(Job, self).__init__(api_key, id)
self.linode_id = linode_id
self.action = action
self.label = label
self.entered = entered
self.start = started
self.finish = finish
self.duration = duration
self.message = message
self.success = success
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['JOBID'],
linode_id=data['LINODEID'],
action=data['ACTION'],
label=data['LABEL'],
entered=base.convert_to_date(data['ENTERED_DT']),
started=base.convert_to_date(data['HOST_START_DT']),
finish=base.convert_to_date(data['HOST_FINISH_DT']),
duration=base.convert_to_int(data['DURATION']),
message=data['HOST_MESSAGE'],
success=base.convert_to_bool(data['HOST_SUCCESS'])
)
def wait(self):
"""
Wait for the job to finish
"""
if self.finish:
return self
finished_job = waitany(self.api_key, self.linode_id, self.id)
self.__dict__.clear()
self.__dict__.update(finished_job.__dict__)
if not self.success:
raise JobError(self)
return self
def convert_to_job_id(value):
if isinstance(value, Job):
return value.id
if isinstance(value, (int, long)):
return value
return int(value)
def get(api_key, linode_id, *jobs, **kwargs):
job_ids = map(convert_to_job_id, jobs)
pending = kwargs.get('pending', None)
multiple = kwargs.pop('multiple', False)
batcher = base.APIBatcher(api_key)
for job_id in job_ids:
kwargs = dict(
LinodeID=linode_id,
JobID=job_id
)
if pending is not None:
kwargs['pendingOnly'] = int(bool(pending))
batcher.add(
'linode.job.list',
**kwargs
)
jobs = []
for result in batcher.execute():
try:
data = result[0]
except IndexError:
data = None
if not data:
value = None
else:
value = Job.from_json(api_key, data)
jobs.append(value)
if len(jobs) == 1 and not multiple:
return jobs[0]
return jobs
def waitall(api_key, linode_id, *jobs):
"""
Waits for all jobs to be complete.
"""
if not jobs:
return []
job_ids = map(convert_to_job_id, jobs)
while True:
pending_jobs = get(api_key, linode_id, *job_ids, multiple=True)
if all(filter(lambda job: bool(job.finish), pending_jobs)):
# all jobs are finished
return jobs
time.sleep(5)
def waitany(api_key, linode_id, *jobs):
if not jobs:
return []
job_ids = map(convert_to_job_id, jobs)
while True:
pending_jobs = get(api_key, linode_id, *job_ids, multiple=True)
for job in pending_jobs:
if job.finish:
return job
time.sleep(5)
<file_sep>/linode/plan.py
import re
from . import base, cache
class Plan(base.BaseObject):
def __init__(self, api_key, id, label, disk_size):
super(Plan, self).__init__(api_key, id)
self.label = label
self.disk_size = disk_size
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['PLANID'],
label=data['LABEL'],
disk_size=data['DISK'] * 1024
)
def __unicode__(self):
return self.label
def __eq__(self, value):
if isinstance(value, basestring):
return bool(re.search(value.lower() + '$', self.label.lower()))
if isinstance(value, (int, long)):
return value == self.id
return False
def __repr__(self):
return '<{} id:{} {} at 0x{}>'.format(
self.__class__.__name__,
self.id,
self.label,
format(id(self), 'x')
)
def load_plans(api_key):
try:
result = cache.read_from_cache('plans')
except:
result = base.make_single_call(
api_key,
'avail.linodeplans'
)
cache.write_to_cache('plans', result)
for data in result:
yield Plan.from_json(api_key, data)
def get_plan(api_key, label):
return base.filter(load_plans(api_key), label)
<file_sep>/linode/cache.py
import os.path
import errno
import json
cache_dir = os.path.abspath(os.path.expanduser('~/.lipy/cache'))
def get_cache_dir():
global cache_dir
try:
os.makedirs(cache_dir)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
if not os.path.isdir(cache_dir):
raise
return cache_dir
def get_cache_filename(file_name):
return os.path.join(
get_cache_dir(),
file_name
)
def write_to_cache(file_name, result):
with open(get_cache_filename(file_name), 'wb') as fp:
fp.write(json.dumps(result))
def read_from_cache(name):
with open(get_cache_filename(name), 'rb') as fp:
return json.loads(fp.read())
<file_sep>/linode/disk.py
from . import base, job
class Disk(base.BaseObject):
def __init__(self, api_key, id, label, type, linode_id, status, size,
read_only):
super(Disk, self).__init__(api_key, id)
self.label = label
self.type = type
self.linode_id = linode_id
self.status = status
self.size = size
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['DISKID'],
label=data['LABEL'],
type=data['TYPE'],
linode_id=data['LINODEID'],
read_only=data['ISREADONLY'],
status=data['STATUS'],
size=data['SIZE']
)
def delete(self, block=True):
"""
Delete this disk from the associated linode.
"""
response = self.make_call(
'linode.disk.delete',
LinodeID=self.linode_id,
DiskID=self.id
)
delete_job = job.get(self.api_key, self.linode_id, response['JobID'])
if block:
delete_job.wait()
return delete_job
def update(self):
self.make_call(
'linode.disk.update',
LinodeID=self.linode_id,
DiskID=self.id,
Label=self.label,
isReadOnly=self.read_only
)
def resize(self, new_size, block=True):
response = self.make_call(
'linode.disk.resize',
LinodeID=self.linode_id,
DiskID=self.id,
size=new_size
)
self.size = new_size
resize_job = job.get(self.api_key, self.linode_id, response['JobID'])
if block:
resize_job.wait()
return resize_job
def get_by_linode(api_key, linode_id):
"""
Returns the Disk objects associated with a given Linode
"""
response = base.make_linode_call(
api_key,
'linode.disk.list',
LinodeID=linode_id
)
for data in response['DATA']:
yield Disk.from_json(api_key, data)
def _get_disk_from_response(api_key, linode_id, response, block):
disk_id = response['DiskID']
job_id = response['JobID']
for disk in get_by_linode(api_key, linode_id):
if disk.id == disk_id:
break
disk = None
if not disk:
raise RuntimeError('Could not find disk from Linode API')
disk_job = job.get(api_key, linode_id, job_id)
if not disk_job:
return disk, None
if block:
disk_job.wait()
return disk, disk_job
def create_from_distribution(api_key, linode_id, distribution_id, label, size,
root_pass, block=True):
response = base.make_single_call(
api_key,
'linode.disk.createfromdistribution',
LinodeID=linode_id,
DistributionID=distribution_id,
Label=label,
Size=size,
rootPass=root_pass
)
return _get_disk_from_response(api_key, linode_id, response, block)
def create_swap(api_key, linode_id, size, label=None, block=True):
label = label or '{}MB Swap Image'.format(size)
response = base.make_single_call(
api_key,
'linode.disk.create',
LinodeID=linode_id,
Label=label,
Type='swap',
Size=size
)
return _get_disk_from_response(api_key, linode_id, response, block)
<file_sep>/linode/datacenter.py
from . import base, cache
class Datacenter(base.BaseObject):
def __init__(self, api_key, id, location):
super(Datacenter, self).__init__(api_key, id)
self.location = location
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['DATACENTERID'],
location=data['LOCATION']
)
def __unicode__(self):
return self.location
def __eq__(self, value):
if isinstance(value, basestring):
return self.location.lower().startswith(value.lower())
if isinstance(value, (int, long)):
return value == self.id
return False
def __repr__(self):
return '<{} id:{} {} at 0x{}>'.format(
self.__class__.__name__,
self.id,
self.location,
format(id(self), 'x')
)
def load_datacenters(api_key):
try:
result = cache.read_from_cache('datacenters')
except:
result = base.make_single_call(
api_key,
'avail.datacenters'
)
cache.write_to_cache('datacenters', result)
return [Datacenter.from_json(api_key, data) for data in result]
def get_datacenter(api_key, location):
return base.filter(load_datacenters(api_key), location)
<file_sep>/setup.py
from setuptools import setup, find_packages
setup_args = dict(
name='lipy',
version='0.1',
description='Python API wrapper for Linode - https://www.linode.com',
maintainer='<NAME>',
maintainer_email='<EMAIL>',
packages=find_packages('.'),
install_requires=[
'requests'
]
)
if __name__ == '__main__':
setup(**setup_args)
<file_sep>/linode/distribution.py
import re
from . import base, cache
class Distribution(base.BaseObject):
def __init__(self, api_key, id, label, x64, min_size, vops_kernel):
super(Distribution, self).__init__(api_key, id)
self.label = label
self.x64 = x64
self.min_size = min_size
self.vops_kernel = vops_kernel
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['DISTRIBUTIONID'],
label=data['LABEL'],
x64=data['IS64BIT'],
min_size=data['MINIMAGESIZE'],
vops_kernel=data['REQUIRESPVOPSKERNEL']
)
def __unicode__(self):
return self.label
def __eq__(self, value):
if isinstance(value, basestring):
return bool(re.search(value.lower(), self.label.lower()))
if isinstance(value, (int, long)):
return value == self.id
return False
def __repr__(self):
return '<{} id:{} {} at 0x{}>'.format(
self.__class__.__name__,
self.id,
self.label,
format(id(self), 'x')
)
def load_distributions(api_key):
try:
result = cache.read_from_cache('distributions')
except:
result = base.make_single_call(
api_key,
'avail.distributions'
)
cache.write_to_cache('distributions', result)
for data in result:
yield Distribution.from_json(api_key, data)
def get_distribution(api_key, label):
return base.filter(load_distributions(api_key), label)
<file_sep>/linode/base.py
from datetime import datetime
import json
import requests
class BaseObject(object):
def __init__(self, api_key, id):
self.api_key = api_key
self.id = id
def make_call(self, action, **kwargs):
return make_single_call(
self.api_key,
action,
**kwargs
)
def get_batcher(self):
return APIBatcher(self.api_key)
def make_linode_call(api_key, action, **kwargs):
"""
Makes a call to the linode api
Blocks until a result is returned.
"""
url = 'https://api.linode.com/'
params = {}
for name, value in kwargs.items():
if not isinstance(value, basestring):
value = json.dumps(value)
params[name] = value
params.update({
'api_action': action,
'api_key': api_key
})
response = requests.post(url, params=params)
if response.status_code != 200:
raise RuntimeError
data = response.content
return json.loads(data)
def make_single_call(api_key, action, **kwargs):
response = make_linode_call(api_key, action, **kwargs)
errors = response['ERRORARRAY']
if errors:
raise RuntimeError(errors[0])
return response['DATA']
def make_batch_call(api_key, *calls):
sub_calls = []
for action, kwargs in calls:
kwargs.update({
'api_action': action
})
sub_calls.append(kwargs)
return iterate_results(make_linode_call(
api_key,
'batch',
api_requestArray=sub_calls
))
def iterate_results(batched_response):
for response in batched_response:
errors = response['ERRORARRAY']
if errors:
# yes we're yielding an exception
yield Exception(errors[0])
yield response['DATA']
def filter(items, query):
for obj in items:
if query == obj:
return obj
raise LookupError('{} not found'.format(query))
class APIBatcher(object):
def __init__(self, api_key):
self.api_key = api_key
self.calls = []
def add(self, action, **kwargs):
self.calls.append((action, kwargs))
def execute(self):
return make_batch_call(self.api_key, *self.calls)
def convert_to_date(value):
if not value:
return
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f')
def convert_to_bool(value):
if value == '':
return
return bool(value)
def convert_to_int(value):
if value == '':
return
return int(value)
<file_sep>/linode/ip.py
from . import base
class IP(base.BaseObject):
def __init__(self, api_key, id, linode_id, address, public):
super(IP, self).__init__(api_key, id)
self.linode_id = linode_id
self.address = address
self.public = public
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['IPADDRESSID'],
linode_id=data['LINODEID'],
address=data['IPADDRESS'],
public=data['ISPUBLIC']
)
def get_by_linode(api_key, linode_id, address_id=None):
response = base.make_single_call(
api_key,
'linode.ip.list',
LinodeID=linode_id,
IPAddressID=address_id
)
if address_id:
return IP.from_json(api_key, response[0])
return [IP.from_json(api_key, data) for data in response]
def add_private(api_key, linode_id):
"""
Assigns a Private IP to a Linode.
:returns: An `IP` instance corresponding to the version created.
"""
response = base.make_single_call(
api_key,
'linode.ip.addprivate',
LinodeID=linode_id
)
return get_by_linode(api_key, linode_id, response['IPAddressID'])
<file_sep>/linode/__init__.py
from .datacenter import get_datacenter
from .distribution import get_distribution
from .kernel import get_kernel
from .plan import get_plan
from .provision import provision
from .linode import list_linodes, get_by_id
__all__ = [
'list_linodes',
'get_by_id',
'get_datacenter',
'get_distribution',
'get_kernel',
'get_plan',
'provision'
]
<file_sep>/linode/config.py
from . import base
_missing = object()
_field_mapping = {
'linode_id': 'LinodeID',
'config_id': 'ConfigID',
'kernel_id': 'KernelID',
'label': 'Label',
'comments': 'Comments',
'ram_limit': 'RAMLimit',
'disk_list': 'DiskList',
'run_level': 'RunLevel',
'root_device_num': 'RootDeviceNum',
'root_device_custom': 'RootDeviceCustom',
'root_device_ro': 'RootDeviceRO',
'disable_update_db': 'helper_disableUpdateDB',
'xen': 'helper_xen',
'depmod': 'helper_depmod',
'devtmpfs_automount': 'devtmpfs_automount',
}
class Config(base.BaseObject):
def __init__(self, api_key, id, **kwargs):
super(Config, self).__init__(api_key, id)
for py_name in _field_mapping:
value = kwargs[py_name]
setattr(self, py_name, value)
@classmethod
def from_json(cls, api_key, data):
config_dict = {}
for py_name, li_name in _field_mapping.items():
config_dict[py_name] = data[li_name]
config_dict.pop('ConfigID', None)
return cls(
api_key,
data['ConfigID'],
**config_dict
)
def update(self):
fields = self.__dict__.copy()
fields.pop('api_key')
fields.pop('linode_id')
fields.pop('config_id')
update_config(self.api_key, self.linode_id, self.id, **fields)
def delete(self):
delete_config(self.api_key, self.linode_id, self.id)
def get_disk_list(value):
if isinstance(value, basestring):
return value
if not isinstance(value, list):
return value
ret = []
for disk in value:
if isinstance(disk, (basestring, int)):
ret.append(str(disk))
continue
ret.append(str(disk.id))
for _ in xrange(9 - len(ret)):
ret.append('')
return ','.join(ret)
def _dict_to_request(obj):
"""
Convert a dict of python keyword arguments to a form suitable for
consumption by the Linode API.
"""
ret = {}
for py_name, li_name in _field_mapping.items():
value = obj.get(py_name, _missing)
if value is _missing:
continue
if py_name == 'disk_list':
value = get_disk_list(value)
ret[li_name] = value
return ret
def create_config(api_key, linode_id, kernel_id, label, **kwargs):
"""
Creates a Linode Configuration Profile.
"""
request = _dict_to_request(kwargs)
request.update({
'LinodeID': linode_id,
'KernelID': kernel_id,
'Label': label
})
response = base.make_single_call(
api_key,
'linode.config.create',
**request
)
return list_config(api_key, linode_id, response['ConfigID'])[0]
def update_config(api_key, linode_id, config_id, **kwargs):
request = _dict_to_request(kwargs)
request.update({
'LinodeID': linode_id,
'ConfigID': config_id,
})
base.make_single_call(
api_key,
'linode.config.update',
**request
)
def delete_config(api_key, config_id, linode_id):
"""
Deletes a Linode Configuration Profile.
"""
base.make_single_call(
api_key,
'linode.config.delete',
LinodeID=linode_id,
ConfigID=config_id,
)
def list_config(api_key, linode_id, config_id=None):
"""
Lists a Linode's Configuration Profiles.
"""
kwargs = {
'LinodeID': linode_id,
}
if config_id:
kwargs['ConfigID'] = config_id
response = base.make_single_call(
api_key,
'linode.config.list',
**kwargs
)
return [Config.from_json(api_key, data) for data in response]
<file_sep>/linode/linode.py
from . import base, datacenter, plan, ip, job, disk
class Linode(base.BaseObject):
def __init__(self, api_key, id, label, datacenter_id, plan_id,
loaded=False):
super(Linode, self).__init__(api_key, id)
self.label = label
self.datacenter_id = datacenter_id
self.plan_id = plan_id
@classmethod
def from_json(cls, api_key, data):
return cls(
api_key,
id=data['LINODEID'],
datacenter_id=data['DATACENTERID'],
plan_id=data['PLANID'],
label=data['LABEL'],
loaded=True
)
@property
def plan(self):
if hasattr(self, '_plan'):
return self._plan
if not self.plan_id:
return
self._plan = plan.get_plan(self.api_key, self.plan_id)
return self._plan
@plan.setter
def plan(self, value):
self.plan_id = value.id
self._plan = value
@property
def datacenter(self):
if hasattr(self, '_datacenter'):
return self._datacenter
if not self.datacenter_id:
return
self._datacenter = datacenter.get_datacenter(self.datacenter_id)
return self._datacenter
@datacenter.setter
def datacenter(self, value):
self.datacenter_id = value.id
self._dc = value
def boot(self, block=True):
"""
Boot the linode.
"""
return boot_linode(self.api_key, self.id, block=block)
def delete(self, skip_checks=False):
"""
Delete the linode. By default the Linode API will not delete a running
instance.
:param skip_checks: Skip the checks before deleting the instance
"""
delete_linode(self.api_key, self.id, skip_checks)
def get_public_ip(self):
for addr in self.get_ips():
if addr.public:
return addr
def get_private_ip(self):
for addr in self.get_ips():
if not addr.public:
return addr
def get_ips(self):
return ip.get_by_linode(self.api_key, self.id)
def add_private_ip(self):
addr = ip.add_private_ip(self.api_key, self.id)
return addr
@property
def disks(self):
return list(disk.get_by_linode(self.api_key, self.id))
def remove(self, skip_check):
self.client(
'linode.delete',
LinodeID=self.id
)
def list_linodes(api_key, linode_id=None):
kwargs = {}
if linode_id:
kwargs['LinodeID'] = linode_id
response = base.make_single_call(
api_key,
'linode.list',
**kwargs
)
return [Linode.from_json(api_key, data) for data in response]
def get_by_id(api_key, linode_id):
"""
Helper method to get a linode by a specific id
"""
try:
return list_linodes(api_key, linode_id)[0]
except IndexError:
return None
def boot_linode(api_key, linode_id, config_id=None, block=True):
"""
Boot a linode.
If `block` is `True` then block the current thread until the boot
completes.
:returns: The Job instances associated with the build request.
"""
kwargs = {
'LinodeID': linode_id
}
if config_id:
kwargs['ConfigID'] = config_id
response = base.make_single_call(
api_key,
'linode.boot',
**kwargs
)
boot_job = job.get(api_key, linode_id, response['JobID'])
if block:
boot_job.wait()
return boot_job
def clone_linode(api_key, linode_id, datacenter_id, plan_id, payment_term):
"""
Creates a new Linode, assigns you full privileges, and then clones the
specified `linode_id` to the new Linode. There is a limit of 5 active clone
operations per source Linode. It is recommended that the source Linode be
powered down during the clone.
"""
response = base.make_single_call(
api_key,
'linode.clone',
LinodeID=linode_id,
DatacenterID=datacenter_id,
PlanID=plan_id,
PaymentTerm=payment_term
)
cloned_id = response['LinodeID']
return get_by_id(api_key, cloned_id)
def create_linode(api_key, datacenter_id, plan_id, payment_term):
"""
Creates a Linode and assigns you full privileges. There is a
75-linodes-per-hour limiter in place.
"""
response = base.make_single_call(
api_key,
'linode.create',
DatacenterID=datacenter_id,
PlanID=plan_id,
PaymentTerm=payment_term
)
return get_by_id(api_key, response['LinodeID'])
def delete_linode(api_key, linode_id, skip_checks=False):
"""
Immediately removes a Linode from your account and issues a pro-rated
credit back to your account, if applicable.
To prevent accidental deletes, this requires the Linode has no Disk images.
You must first delete its disk images.
"""
base.make_single_call(
api_key,
'linode.delete',
LinodeID=linode_id,
skipChecks=skip_checks
)
def reboot_linode(api_key, linode_id, config_id=None, block=True):
"""
Reboot a linode.
If `block` is `True` then block the current thread until the boot
completes, otherwise return the `Job` instance.
"""
kwargs = {
'LinodeID': linode_id
}
if config_id:
kwargs['ConfigID'] = config_id
response = base.make_single_call(
api_key,
'linode.reboot',
**kwargs
)
reboot_job = job.get(api_key, linode_id, response['JobID'])
if block:
reboot_job.wait()
return reboot_job
def resize_linode(api_key, linode_id, plan_id):
"""
This is a weird one - would have expected a JobID response here.
"""
base.make_single_call(
api_key,
'linode.resize',
LinodeID=linode_id,
PlanID=plan_id
)
# expect some sort of Job here
def shutdown_linode(api_key, linode_id, block=True):
"""
Issues a shutdown job for a given LinodeID.
If `block` is `True` then block the current thread until the shutdown
completes.
"""
response = base.make_single_call(
api_key,
'linode.shutdown',
LinodeID=linode_id,
)
shutdown_job = job.get(api_key, linode_id, response['JobID'])
if block:
shutdown_job.wait()
return shutdown_job
| 3348a7c24fb2d008e8357aff0e93339363412e36 | [
"Python"
] | 13 | Python | njoyce/lipy | ff7969247bdf0520a14705f68c0f0f0ecbf7743b | ede2770cb65582c28046de7ede24969564a7c9c2 |
refs/heads/master | <file_sep>package com.project1.learning.pesky.timemanager;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.widget.ListView;
import com.project1.learning.pesky.timemanager.model.AttivitaFavoriti;
import java.util.ArrayList;
public class AggiungiAttivitaStorico extends TmNuovaAttivita {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aggiungi_attivita_storico);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Nuova attività storico");
listView = (ListView)findViewById(R.id.listView);
listView.setOnItemClickListener(this);
filtro = new ArrayList<>();
array = new ArrayList<>();
array.add(new AttivitaFavoriti("Pausa caffe", true));
array.add(new AttivitaFavoriti("Meeting", false));
array.add(new AttivitaFavoriti("Pausa pranza", true));
array.add(new AttivitaFavoriti("Assistenza clienti", false));
array.add(new AttivitaFavoriti("Pausa caffe", true));
array.add(new AttivitaFavoriti("Pausa caffe", true));
array.add(new AttivitaFavoriti("Pausa caffe", true));
array.add(new AttivitaFavoriti("Pausa caffe", true));
renderList(array);
}
}
| 464891c107af4adf4a95c035298adb3a169b9e64 | [
"Java"
] | 1 | Java | Azuel97/TimeManager-1 | e27b26ab42b78b3905ed27385b1740a9bd4c4b94 | fc17f022afabdcbac3ff5545eea2d9eb7224d264 |
refs/heads/master | <repo_name>brandcolors/brandcolors-support<file_sep>/includes/admin/menus.php
<?php
/**
* Admin Menus
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Remove unused pages from the WordPress admin.
*/
function bcs_remove_menus() {
remove_menu_page( 'index.php' ); // Dashboard
remove_menu_page( 'upload.php' ); // Media
remove_menu_page( 'edit.php' ); // Posts
remove_menu_page( 'edit-comments.php' ); // Comments
}
add_action( 'admin_menu', 'bcs_remove_menus' );<file_sep>/includes/export.php
<?php
/**
* Takes a WP_Query object containing brands and turns it into a CSS export.
*/
function bcs_export_css( $brands ) {
// If there are brands to export
if ( ! empty( $brands ) && $brands->have_posts() ) {
// Declare the output variable
$output = '';
// Loop through the brands
while ( $brands->have_posts() ) {
// Setup the post data
$brands->the_post();
// Get the brand's colors
$colors = bcs_get_colors();
// Save the brand slug
$brand_slug = basename( get_permalink() );
// Start a counter
$counter = 1;
// Begin with a line break
$output .= "\n";
// Loop through the brand colors
foreach ( $colors as $color ) {
// Classes for background-color
$output .= "\n.bc-background-$brand_slug";
$output .= ( $counter > 1 ? "-$counter" : '' );
$output .= " { background-color: #$color; }\n";
// Classes for color
$output .= ".bc-color-$brand_slug";
$output .= ( $counter > 1 ? "-$counter" : '' );
$output .= " { color: #$color; }";
// Increment the counter
$counter++;
}
}
// Return the ouput
return $output;
}
// Return false if brands weren't found
return false;
}
/**
* Takes a WP_Query object containing brands and turns it into a SCSS export.
*/
function bcs_export_scss( $brands ) {
// If there are brands to export
if ( ! empty( $brands ) && $brands->have_posts() ) {
// Declare the output variable
$output = '';
// Loop through the brands
while ( $brands->have_posts() ) {
// Setup the post data
$brands->the_post();
// Get the brand's colors
$colors = bcs_get_colors();
// Save the brand slug
$brand_slug = basename( get_permalink() );
// Start a counter
$counter = 1;
// Begin with a line break
$output .= "\n";
// Loop through the brand colors
foreach ( $colors as $color ) {
// SCSS variables
$output .= "\n" . '$bc-' . $brand_slug;
$output .= ( $counter > 1 ? "-$counter" : '' );
$output .= ": #$color;";
// Increment the counter
$counter++;
}
}
// Return the ouput
return $output;
}
// Return false if brands weren't found
return false;
}
/**
* Takes a WP_Query object containing brands and turns it into a LESS export.
*/
function bcs_export_less( $brands ) {
// If there are brands to export
if ( ! empty( $brands ) && $brands->have_posts() ) {
// Declare the output variable
$output = '';
// Loop through the brands
while ( $brands->have_posts() ) {
// Setup the post data
$brands->the_post();
// Get the brand's colors
$colors = bcs_get_colors();
// Save the brand slug
$brand_slug = basename( get_permalink() );
// Start a counter
$counter = 1;
// Begin with a line break
$output .= "\n";
// Loop through the brand colors
foreach ( $colors as $color ) {
// LESS variables
$output .= "\n@bc-$brand_slug";
$output .= ( $counter > 1 ? "-$counter" : '' );
$output .= ": #$color;";
// Increment the counter
$counter++;
}
}
// Return the ouput
return $output;
}
// Return false if brands weren't found
return false;
}
/**
* Takes a WP_Query object containing brands and turns it into a Stylus export.
*/
function bcs_export_styl( $brands ) {
// If there are brands to export
if ( ! empty( $brands ) && $brands->have_posts() ) {
// Declare the output variable
$output = '';
// Loop through the brands
while ( $brands->have_posts() ) {
// Setup the post data
$brands->the_post();
// Get the brand's colors
$colors = bcs_get_colors();
// Save the brand slug
$brand_slug = basename( get_permalink() );
// Start a counter
$counter = 1;
// Begin with a line break
$output .= "\n";
// Loop through the brand colors
foreach ( $colors as $color ) {
// Stylus variables
$output .= "\nbc-$brand_slug";
$output .= ( $counter > 1 ? "-$counter" : '' );
$output .= " = #$color";
// Increment the counter
$counter++;
}
}
// Return the ouput
return $output;
}
// Return false if brands weren't found
return false;
}
/**
* Takes a WP_Query object containing brands and turns it into a ASE export.
*/
function bcs_export_ase( $brands ) {
// If there are brands to export
if ( ! empty( $brands ) && $brands->have_posts() ) {
// Include the ASE Export library
require( dirname( __FILE__ ) . '/library/ASE-Export/ASE-Export.php' );
// Declare the ASE brands array
$ase_brands = array();
// Loop through the brands
while ( $brands->have_posts() ) {
// Setup the post data
$brands->the_post();
// Declare the ASE brand array
$ase_brand = array();
// Set the ASE brand title
$ase_brand['title'] = get_the_title( get_the_ID() );
// Delcare the ASE colors array
$ase_colors = array();
// Get the brand's colors
$colors = bcs_get_colors();
// Start a counter
$counter = 1;
// Loop through the brand colors
foreach ( $colors as $color ) {
// Add color to ASE colors array
$ase_colors[] = array( $color, 'rgb-hex', get_the_title( get_the_ID() ) . ' ' . ( $counter > 1 ? $counter : '' ) );
// Increment the counter
$counter++;
}
// Add the ASE brand colors to the ASE brand array
$ase_brand['colors'] = $ase_colors;
// Add the ASE brand to the ASE brands array
$ase_brands[] = $ase_brand;
}
// Return the ASE brands
return mkASE( $ase_brands );
}
// Return false if brands weren't found
return false;
}<file_sep>/brandcolors-support.php
<?php
/*
Plugin Name: BrandColors Support
Description: Turns WordPress into a lean, mean, brand-color-makin' machine.
Author: <NAME>
Author URI: http://galengidman.com/
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
// Everywhere includes.
$includes = array(
'brands.php',
'colors.php',
'export.php',
'post-types.php'
);
foreach ( $includes as $include ) {
require( dirname( __FILE__ ) . '/includes/' . $include );
}
// Admin includes.
if ( is_admin() ) {
// CT Meta Box
if ( ! defined( 'CTMB_URL' ) ) define( 'CTMB_URL', plugin_dir_url( __FILE__ ) . 'includes/library/ct-meta-box/' );
require( dirname( __FILE__ ) . '/includes/library/ct-meta-box/ct-meta-box.php' );
// Plugin includes
$admin_includes = array(
'assets.php',
'brand-fields.php',
'menus.php'
);
foreach ( $admin_includes as $admin_include ) {
require( dirname( __FILE__ ) . '/includes/admin/' . $admin_include );
}
}
// Activate the download template on pages with the slug 'download'
function bcs_download_template( $page_template ) {
if ( is_page( 'download' ) ) $page_template = dirname( __FILE__ ) . '/templates/download.php';
if ( is_page( 'api' ) ) $page_template = dirname( __FILE__ ) . '/templates/api.php';
if ( is_page( 'api/v1' ) ) $page_template = dirname( __FILE__ ) . '/templates/api-v1.php';
return $page_template;
}
add_filter( 'page_template', 'bcs_download_template' );<file_sep>/templates/api-v1.php
<?php
$brand_ids = ( isset( $_GET['brands'] ) ? explode( ',', $_GET['brands'] ) : '' );
$brands = bcs_get_brands( $brand_ids );
if ( $brands->have_posts() ) {
$output = array();
while ( $brands->have_posts() ) {
$brands->the_post();
$b = array();
$c = array();
$b['id'] = get_the_id();
$b['title'] = get_the_title();
$colors = bcs_get_colors();
foreach ( $colors as $color ) {
$c[] = $color;
}
$b['colors'] = $c;
$output[] = $b;
}
$json = json_encode( $output );
header( 'Content-Type: application/json' );
echo $json;
} else {
wp_die( 'No brands found.' );
}<file_sep>/includes/colors.php
<?php
function bcs_get_colors( $brand = null ) {
if ( empty( $brand ) ) {
$brand = get_the_id();
}
$colors = get_post_meta( $brand, '_brand_colors', true );
$colors = explode( ',', $colors );
return $colors;
}<file_sep>/includes/admin/brand-fields.php
<?php
/**
* Brand Fields
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Register the brand settings meta box.
*/
function bcs_brand_fields() {
$args = array(
'id' => 'brand-settings',
'title' => 'Brand Settings',
'post_type' => 'brand',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
'_brand_colors' => array(
'name' => 'Brand Colors',
'desc' => 'Comma-separated hex codes',
'type' => 'textarea',
'attributes' => array(
'id' => 'brand-colors'
),
'custom_sanitize' => 'bcs_clean_hex_codes'
),
'_brand_url' => array(
'name' => 'Brand URL',
'type' => 'url'
),
'_source_url' => array(
'name' => 'Source URL',
'type' => 'url'
)
)
);
new CT_Meta_Box( $args );
}
add_action( 'admin_init', 'bcs_brand_fields' );
/**
* Clean unneeded spaces and # from hex codes.
*/
function bcs_clean_hex_codes( $codes ) {
$search = array(
' ',
'#'
);
$cleaned_codes = trim( strtolower( str_replace( $search, '', $codes ) ) );
return $cleaned_codes;
}<file_sep>/includes/post-types.php
<?php
/**
* Post Types
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Register the Brand post type.
*/
function bcs_brand_init() {
$labels = array(
'name' => 'Brands',
'singular_name' => 'Brand',
'menu_name' => 'Brands',
'name_admin_bar' => 'Brand',
'add_new' => 'Add New',
'add_new_item' => 'Add New Brand',
'new_item' => 'New Brand',
'edit_item' => 'Edit Brand',
'view_item' => 'View Brand',
'all_items' => 'All Brands',
'search_items' => 'Search Brands',
'parent_item_colon' => 'Parent Brands:',
'not_found' => 'No brands found.',
'not_found_in_trash' => 'No brands found in Trash.'
);
$supports = array(
'author',
'title'
);
$args = array(
'labels' => $labels,
'show_ui' => true,
'menu_position' => 0,
'menu_icon' => 'dashicons-screenoptions',
'supports' => $supports
);
register_post_type( 'brand', $args );
}
add_action( 'init', 'bcs_brand_init' );
<file_sep>/includes/admin/assets.php
<?php
/**
* Admin Assets
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Enqueue admin scripts and styles.
*/
function bcs_admin_scripts() {
$screen = get_current_screen();
if ( $screen->base == 'post' && $screen->post_type == 'brand' ) {
// Admin scripts
wp_enqueue_script( 'bcs-admin', plugin_dir_url( __FILE__ ) . '../../assets/js/admin.js', array( 'jquery' ) );
// Admin styles
wp_enqueue_style( 'bcs-admin', plugin_dir_url( __FILE__ ) . '../../assets/css/admin.css' );
}
}
add_action( 'admin_enqueue_scripts', 'bcs_admin_scripts' );<file_sep>/templates/api.php
<?php
wp_die( 'Please select an API version.' );<file_sep>/templates/download.php
<?php
/**
* Download Template
*/
// Store the download format. If none exists, display an error message.
if ( isset( $_GET['format'] ) ) {
$format = strtolower( htmlspecialchars( $_GET['format'] ) );
} else {
wp_die( 'Please select a download format.' );
}
// Store the brand IDs to download if we're only downloading a subset of them.
$brand_ids = ( isset( $_GET['brands'] ) ? explode( ',', $_GET['brands'] ) : null );
// Get and store the brands.
$brands = bcs_get_brands( $brand_ids );
// If there are brands...
if ( $brands->have_posts() ) {
switch ( $format ) {
case 'css' :
$output = bcs_export_css( $brands );
break;
case 'scss' :
$output = bcs_export_scss( $brands );
break;
case 'less' :
$output = bcs_export_less( $brands );
break;
case 'styl' :
$output = bcs_export_styl( $brands );
break;
case 'ase' :
$output = bcs_export_ase( $brands );
break;
}
if ( ! empty( $output ) ) {
if ( $format == 'ase' ) {
header( 'Content-Type: application/octet-stream' );
header( 'Content-Length: ' . strlen( $output ) );
} else {
header( 'Content-Type: text/plain' );
}
header( 'Content-Disposition: attachment; filename="brandcolors-' . time() . '.' . $format . '"' );
echo $output;
} else {
wp_die( 'Invalid format.' );
}
} else {
wp_die( 'No brands found.' );
}<file_sep>/includes/brands.php
<?php
function bcs_get_brands( $brands = null ) {
$args = array(
'posts_per_page' => 1000,
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'brand',
'no_found_rows' => true
);
if ( ! empty( $brands ) ) {
$brand_args = array(
'post__in' => $brands
);
$args = array_merge( $args, $brand_args );
}
$brands = new WP_Query( $args );
return $brands;
} | 3834a7c1af6121be09d652687558c2d40a29c9be | [
"PHP"
] | 11 | PHP | brandcolors/brandcolors-support | 61ee06a71a67732d3522a9eea7ca141eacaef137 | 7ef3cca12ee03ee4af0af8bda5db946da6a2787a |
refs/heads/main | <file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { ParentComponent } from './views/parent/parent/parent.component';
import { Child1Component } from './views/child/child1/child1.component';
import { Child2Component } from './views/child/child2/child2.component';
import { Child3Component } from './views/child/child3/child3.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
ParentComponent,
Child1Component,
Child2Component,
Child3Component
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: 'parent', component: ParentComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, EventEmitter, Input, OnInit, Output, SimpleChanges } from '@angular/core';
import { ParentService } from '../../../services/parent.service';
@Component({
selector: 'child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
@Input() parentData: string;
@Output() data: EventEmitter<any> = new EventEmitter();
constructor(private service: ParentService) { }
ngOnInit(): void {
this.service.child1dataService = this.parentData;
}
sendData() {
this.service.child1dataService = this.parentData;
this.data.emit(this.parentData);
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { ParentService } from '../../../services/parent.service';
@Component({
selector: 'child2',
templateUrl: './child2.component.html',
styleUrls: ['./child2.component.css']
})
export class Child2Component implements OnInit {
@Input() parentData: string;
//child1data: string = '';
constructor(private service: ParentService) { }
ngOnInit(): void {
//this.child1data = this.service.child1dataService;
}
//ngDoCheck() {
// if (this.child1data != this.service.child1dataService) {
// this.child1data = this.service.child1dataService;
// }
//}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ParentService {
child1dataService: string = '';
child2dataService: string = '';
child3dataService: string = '';
constructor() { }
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { Child1Component } from '../../child/child1/child1.component';
import { Child2Component } from '../../child/child2/child2.component';
import { Child3Component } from '../../child/child3/child3.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
@ViewChild(Child1Component) child1: Child1Component;
@ViewChild(Child2Component) child2: Child2Component;
@ViewChild(Child3Component) child3: Child3Component;
child1Data: string = "child 1";
child2Data: string = "child 2";
child3Data: string = "child 3";
constructor() { }
ngOnInit(): void {
}
setChild1Data(data) {
this.child1Data = data;
}
}
| 07c2a8ba4d3550bcb863ae87d9e9b88d9d478fb9 | [
"TypeScript"
] | 5 | TypeScript | krish7448/angular-parent-child-master | 4bffae8d8a97a596d0d87d49d2a3161ad3bb5238 | 36a62d2445faf6a3641b134eb9f842618712aa5e |
refs/heads/master | <file_sep>use spectral::prelude::*;
use std::path::PathBuf;
#[test]
fn basic_executable() {
let root_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let test_dir = root_dir.join("tests").join("c");
let hello_source = test_dir.join("hello.c");
let symbols_path = PathBuf::from(env!("COMPILEDFILES_BASIC_TEST_SYM_PATH"));
let symbols_file = std::fs::File::open(&symbols_path).unwrap();
let files = compiledfiles::parse(symbols_file).unwrap();
assert_that!(files.iter().find(|&f| f.path == hello_source)).is_some();
}
| 1e310c2463d1d78c234e36909e2147f19dc1116d | [
"Rust"
] | 1 | Rust | pombredanne/compiledfiles | 78e66124851845d9a7c71e1eabc8b24bbddbc665 | 261b5f753214c9637588986ad189f207ab3aacfb |
refs/heads/master | <file_sep>using System;
using Infrastructure.TorreHanoi.Log;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Domain.TorreHanoi;
using Moq;
namespace TorreHanoi.Tests
{
[TestClass]
public class TorreHanoiUnit
{
private const string CategoriaTeste = "Domain/TorreHanoi";
private Mock<ILogger> _mockLogger;
[TestInitialize]
public void SetUp()
{
_mockLogger = new Mock<ILogger>();
_mockLogger.Setup(s => s.Logar(It.IsAny<string>(), It.IsAny<TipoLog>()));
}
[TestMethod]
[TestCategory(CategoriaTeste)]
public void Construtor_Deve_Retornar_Sucesso()
{
var torreHanoi = new Domain.TorreHanoi.TorreHanoi(3, _mockLogger.Object);
Assert.IsNotNull(torreHanoi.Id);
Assert.IsNotNull(torreHanoi.Discos);
Assert.IsNotNull(torreHanoi.Destino);
Assert.IsNotNull(torreHanoi.Intermediario);
Assert.IsNotNull(torreHanoi.Origem);
Assert.IsNotNull(torreHanoi.DataCriacao);
Assert.AreEqual(torreHanoi.Status,TipoStatus.Pendente);
Assert.IsNotNull(torreHanoi.PassoAPasso);
}
[TestMethod]
[TestCategory(CategoriaTeste)]
public void Processar_Deverar_Retornar_Sucesso()
{
var torreHanoi = new Domain.TorreHanoi.TorreHanoi(3,_mockLogger.Object);
Assert.IsTrue(torreHanoi.Processar());
}
}
}
| 9a5180d6a38a8221e80e1599019098ccd44baf1d | [
"C#"
] | 1 | C# | KevinLira/teste-backend-csharp | ef6d7a8ee940c7011fff91d9d9e3d5253cbf8659 | 08d464d396e1574eb1fad6a53a9e342d7163ade5 |
refs/heads/master | <repo_name>SBajonczak/ioBroker.SpotifyUi<file_sep>/View mehrere Instanzen/JS-Vis/view_spotify.js
/* -----
Material Design JS for ioBroker.vis
(c) 2017 Uhula, MIT License
https://github.com/Uhula/ioBroker-Material-Design-Style
V1.7 28.12.2017
o Korrektur mdui-lnav/rnav. Funktionierte mit mdui-toggle nicht korrekt
V1.6 16.10.2017
O _toggleFullscreen geändert, damit die function auch im ioBroker
fullscreen Mode funktioniert
o Delegator-Eventhandler für body gesetzt (bisher #vis_container, wirkten dann aber in Dialogen nicht)
V1.5 11.10.2017
o MDUI.handleTables fertig
V1.3 24.09.2017
+ MDUI.handleTables hinzu (in Entwicklung)
V1.0 01.09.2017
----- */
// Zur sicheren CSS-Erkennung der Runtime eine CSS-Klasse anlegen
document.documentElement.className += " mdui-runtime";
// Überprüfen ob touch zur Verfügung steht und entsprechend eine
// CSS Klasse touch bzw no-touch erzeugen
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? " mdui-touch" : " mdui-notouch");
/* -----
MDUI
-----
Sammlung von JS-Funktionen für das Material Design
(c) 2017 Uhula, MIT License
*/
var MDUI = (function () {
var isSubtreeModified = false;
// liefert den suffix einer gegeben class zurück-Navigieren
// Bsp: mdui-target-w00002 -> w00002
// mdui-zoom-to-200 -> 200
function _getClassSuffix( $ele, classname ) {
var suf = "";
if ($ele) {
var c = $ele.attr( "class" );
suf = c.substr(c.indexOf(classname)+classname.length,1000)+" ";
suf = suf.substr(0,suf.indexOf(" "));
}
return suf;
}
//
function _getGroupID( ele ) { return _getClassSuffix(ele, "mdui-group-" ); }
//
function _getTargetID( ele ) { return _getClassSuffix(ele, "mdui-target-" ); }
//
function _getScrollbarWidth() {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
}
//
function _getScrollbarHeight() {
var $outer = $('<div>').css({visibility: 'hidden', height: 100, overflow: 'scroll'}).appendTo('body'),
heightWithScroll = $('<div>').css({height: '100%'}).appendTo($outer).outerHeight();
$outer.remove();
return 100 - heightWithScroll;
}
function _formatDatetime(date, format) {
function fill(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
}
var months = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
var d = format;
var o = {
"y+": date.getFullYear(), // year
"m+": fill(date.getMonth()+1), //month
"M+": months[date.getMonth()], //month
"d+": fill(date.getDate()), //day
"H+": fill((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"h+": fill(date.getHours()), //hour
"n+": fill(date.getMinutes()), //minute
"s+": fill(date.getSeconds()), //second
"S+": fill(date.getMilliseconds()), //millisecond,
"b+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
d = d.replace(RegExp.$1, o[k]);
}
}
return d;
}
// alle Elemente mit class "mdui-group-XXX" togglen, in denen
// XXX aus class "mdui-group-XXX" des ele ist UND
// alle Elemente mit class "mdui-target-XXX" togglen, in denen
// XXX aus class "mdui-target-XXX" des ele ist
function _toggleVisibility( $ele ) {
$ele.toggleClass("ui-state-active");
var id = _getGroupID( $ele );
if (id!=="")
$("[class*='mdui-group-"+id+"']").not("[class*='mdui-toggle']").each( function (index) {
$(this).toggleClass("mdui-hide");
});
id = _getTargetID( $ele );
if (id!=="")
$( "[class*='mdui-target-"+id+"']").not("[class*='mdui-toggle']").each( function (index) {
$(this).toggleClass("mdui-hide");
});
}
// das in ele class \"mdui-target-XXX\" angegeben Element mit der id \"XXX\" wird
// - fullscreen angezeigt, wenn es noch nicht fullscreen ist
// - wieder normal angezeigt, wenn es fullscreen ist
function _toggleFullscreen( $ele ){
if (!$ele) return;
var $target = $ele.closest(".vis-view");
if (!$target) return;
var styleold = $target.attr("styleold");
if (styleold) {
$target.attr("style",styleold);
$target.removeAttr("styleold");
$target.appendTo(".mdui-id-"+$target.attr("id"));
} else {
$target.parent().addClass("mdui-id-"+$target.attr("id"));
$target.attr("styleold",$target.attr("style"));
$target.attr("style","position:fixed; left:0; top:0; width:100%; height:100%; z-index: 2147483647 !important;background:#212121 !important; ");
$target.appendTo( "body" );
//$target.appendTo( "body #vis_container" );
}
}
// ele muss class Einträge für das Target und den Skalierungsmodus haben
// "mdui-target-(id) mdui-scale-(scalemode)"
// id: Ziel-Element mit id=id, welches ein zu skalierendes img enthält
// scalemode: fit / hfit / vfit / in / out / (number)
// number: Zahl in %
function _scale( ele ) {
var id = _getTargetID( ele );
var $img = $( "#"+id+" img" );
if ($img) {
var scale = _getClassSuffix(ele, "mdui-scale-" );
$img.width("1px"); // Scrollbars entfernen um die echte Höhe zu bekommen
$img.height("1px");
var dim = {
pw : $img.parent().width(),
ph : $img.parent().height(),
w : $img[0].naturalWidth,
h : $img[0].naturalHeight
};
switch(scale) {
case "fit":
if (dim.pw / dim.w < dim.ph / dim.h ) scale = dim.pw / dim.w;
else scale = dim.ph / dim.h;
break;
case "hfit":
if (dim.pw / dim.w < dim.ph / dim.h ) scale = dim.pw / dim.w;
else scale = (dim.pw - _getScrollbarWidth() - 4 ) / dim.w;
break;
case "vfit":
if ( dim.pw / dim.w > dim.ph / dim.h ) scale = dim.ph / dim.h;
else scale = (dim.ph - _getScrollbarHeight() - 4 ) / dim.h;
break;
case "in":
case "out":
var old = $img.attr( "style" );
old = old.substr(old.indexOf("scale(")+6,20);
old = old.substr(0,old.indexOf(")"));
if (old * 1==0) scale = 1;
else if (scale=="in") scale = old * 1.41;
else scale = old / 1.41;
break;
default:
if (scale<=0 || scale>10000)
scale = 100;
scale = scale/100;
}
scale = Math.round(scale*100)/100;
$img.attr( "style", "position:absolute;top:0;left:0;transform-origin:0 0;transition: transform 0.3s ease-out; transform:scale("+scale+");" );
}
}
// ersetzt im src-Attribute des Unter-Elements von (id) den "&range=&
// durch den Wert des in ele angegebenen (span). Für flot-Diagramme
// "mdui-target-(id) mdui-timespan-(span)"
// id: Ziel-Element mit id=id, welches das flot (src) enthält
// span: inc / dec / (number)
// number: Zahl in Minuten
function _timespan( ele ) {
var id = _getTargetID( ele );
var target = $( "#"+id+" [src]" );
if (target) {
var timespan = _getClassSuffix(ele, "mdui-timespan-" );
var src = target.attr( "src" );
var min = src.substr(src.indexOf("&range=")+7,20);
min = min.substr(0,min.indexOf("&"));
switch(timespan) {
case "inc":
min = min * 2;
break;
case "dec":
min = min / 2;
break;
default:
if ( timespan<=0 )
timespan = 1440;
min = timespan;
}
src = src.replace(/&range=[0-9]*&/g, "&range="+min+"&");
target.attr("src",src);
}
}
/* */
function _resetTable( $ele, $table ) {
$ele.removeClass("mdui-table-tile");
$ele.removeClass("mdui-table-card");
$ele.removeClass("mdui-table-list");
$table.find("tbody>tr").each( function(index) {
$(this).width("auto");
$(this).height("auto");
$(this).find("td").each( function(index) {
$(this).attr("labelth","");
});
});
}
/* */
function _handleTable( $ele, $table, opt ) {
function setColWidth( colwidth ) {
$table.find("tbody>tr").each( function(index) {
$(this).outerWidth(colwidth);
});
}
function setColHeight() {
var height = 0;
$table.find("tbody>tr").each( function(index) {
if ($(this).height() > height ) height = $(this).height();
});
if ( height > 0 )
$table.find("tbody>tr").each( function(index) {
$(this).height( height );
});
}
var innerWidth = $ele.innerWidth();
_resetTable($ele, $table);
$ele.addClass("mdui-table-"+opt.type);
if (opt.label) {
// Zellen mit Labels aus <th> ergänzen ?
var labels = [];
$table.find("thead>tr>th").each( function(index) {
labels[index] = $(this).text();
});
$table.find("tbody>tr").each( function(index) {
$(this).find("td").each( function(index) {
if (index < labels.length)
$(this).attr("labelth",labels[index]);
});
});
}
if (opt.colwidth>1) setColWidth(opt.colwidth);
if (opt.colwidth>2) setColHeight();
return true;
}
/* Alle mdui-table durchlaufen und überprüfen, ob die minimale Width erreicht
wurde um sie in den responsive State zu überführen
mdui-table-(mode)(-opt1)(-opt2)...(-optn)
mdui-table-ascard-r600-w200-l */
function _handleTables( ) {
$("[class*='mdui-table ']").each( function (index) {
var $ele = $(this);
var $table;
$table = $ele;
if (!$table.is("table")) $table=$table.find("table");
if (!$table.is("table")) return true; // next each
var innerWidth = $ele.innerWidth();
var classes = $ele.attr("class")
.split(" ")
.filter( function ( ele ) {
return (ele.indexOf("mdui-table-ascard") > -1)
|| (ele.indexOf("mdui-table-astile") > -1)
|| (ele.indexOf("mdui-table-aslist") > -1); });
var opts = [];
var opt;
for (var i = 0; i < classes.length; i++) {
opts[i] = [];
opts[i].reswidth = 9999;
opts[i].colwidth = 0;
opts[i].label = false;
opts[i].type = classes[i].substr(13,4);
opt = classes[i].substr(18,200).split("-");
for (var j = 0; j < opt.length; j++) {
switch(opt[j][0]) {
case "r":
opts[i].reswidth = parseInt(opt[j].substr(1,5));
break;
case "w":
opts[i].colwidth = parseInt(opt[j].substr(1,5));
break;
case "c":
opts[i].colwidth = parseInt(opt[j].substr(1,5));
if (opts[i].colwidth>0) opts[i].colwidth = (innerWidth-_getScrollbarWidth()-8) / opts[i].colwidth;
break;
case "l":
opts[i].label = true;
break;
default:
}
}
}
opts.sort(function(a, b){return a.reswidth-b.reswidth});
//console.log(opts);
if (opts.length === 0) return true; // next each
var handled = false;
for (i = 0; i < opts.length; i++) {
if ( innerWidth < opts[i].reswidth )
handled = _handleTable( $ele, $table, opts[i]);
if (handled) break;
}
if (!handled) _resetTable($ele, $table);
});
}
// DOM SubTree-Änderungen einmalig alle 500ms auswerten (diese Events werden
// u.U. 1000-fach gefeuert und müssen deswegen verzögert ausgeführt werden)
function _onSubTreeModified( $ele ) {
if (!isSubtreeModified) {
isSubtreeModified = true;
setTimeout(function () {
_handleTables();
isSubtreeModified=false;
}, 500);
}
}
return {
toggleVisibility: _toggleVisibility,
toggleFullscreen: _toggleFullscreen,
scale: _scale,
timespan: _timespan,
handleTables: _handleTables,
onSubTreeModified : _onSubTreeModified
};
})();
// Eventhandler für body-Delegators setzen (früher:#vis_container)
setTimeout(function () {
// click-Event für das left-nav Element zum Öffnen
$("body").on( "click", ".mdui-lnavbutton", function() {
$( ".mdui-lnav" ).addClass( "mdui-lnav-open" );
} );
// click-Event für die left-nav zum Schließen
$("body").on( "click", ".mdui-lnav", function() {
$( ".mdui-lnav" ).removeClass( "mdui-lnav-open" );
} );
// click-Event für das right-nav Element zum Öffnen
$("body").on( "click", ".mdui-rnavbutton", function() {
$( ".mdui-rnav" ).addClass( "mdui-rnav-open" );
} );
// click-Event für die right-nav zum Schließen
$("body").on( "click", ".mdui-rnav", function() {
$( ".mdui-rnav" ).removeClass( "mdui-rnav-open" );
} );
// click-Eventhandler für "mdui-scale-" setzen
$("body").on( "click", "[class*='mdui-scale-']", function(event) {
MDUI.scale( $(this) );
} );
// click-Handler für "mdui-toggle"
$("body").on( "click", ".mdui-toggle", function(event) {
event.preventDefault();
event.stopImmediatePropagation();
MDUI.toggleVisibility( $(this) );
} );
// click-Handler für "mdui-fullscreen"
$("body").on( "click", ".mdui-fullscreen", function(event) {
MDUI.toggleFullscreen( $(this) );
} );
// click-Handler für "mdui-timepsan-"
$("body").on( "click", "[class*='mdui-timespan-']", function(event) {
MDUI.timespan( $(this) );
} );
$( window ).on("resize", function() {
MDUI.handleTables();
});
// Überwachen des #vis_containers auf Änderungen (z.B. wenn views nachgeladen
// werden)
$( "#vis_container" ).on( "DOMSubtreeModified", function(event) {
MDUI.onSubTreeModified( $(this) );
} );
// für den ersten load einmal aufrufen
MDUI.onSubTreeModified( );
}, 1000); | 91224c09245f93bf44ef2331a16c54f0a0387473 | [
"JavaScript"
] | 1 | JavaScript | SBajonczak/ioBroker.SpotifyUi | 9513b6d013c74d291aeba90831b3386688ec429b | 7a2e4f35c5cc263b30a6f51bbe1423a828ca9b84 |
refs/heads/master | <repo_name>Mechachleopteryx/amrlib<file_sep>/setup.py
#!/usr/bin/python3
import setuptools
from amrlib import __version__
# To create the pypi distribution and upload to pypi do..
# ./setup.py sdist bdist_wheel
# twine upload dist/*
# To install to the user account d0..
# ./setup.py install --user
# Load the README.md to use as the long description that shows up on pypi
with open('README.md', 'r') as fh:
readme = fh.read()
# Remove lines with png file references (because these don't seem to display on pypi)
lines = readme.splitlines()
lines = [l for l in lines if not '.png' in l]
readme = '\n'.join(lines)
setuptools.setup(
name='amrlib',
version=__version__,
author='<NAME>',
author_email='<EMAIL>',
description='A python library that makes AMR parsing, generation and visualization simple.',
long_description=readme,
long_description_content_type='text/markdown',
url='https://github.com/bjascob/amrlib',
# The following adds data files for the binary distribution only (not the source)
# This impacts `setup bdist_wheel`. Use the MANIFEST.in file to add data files to
# the source package. Also note that just using wildcards (ie.. *.csv) without the
# path doesn't work unless there's an __init__.py in the directory because setup
# doesn't look in there without it.
include_package_data=True,
package_data={'amrlib':['amr_view/*',
'alignments/faa_aligner/model_aligner_faa.tar.gz',
'alignments/faa_aligner/resources/*.txt',
'alignments/isi_hand_alignments/*.txt']},
packages=setuptools.find_packages(),
# Minimal requirements here. More extensive list in requirements.txt
install_requires=['penman>=1.1.0', 'torch>=1.6', 'numpy', 'spacy>=2.0', 'tqdm', 'transformers>=3.0', 'smatch'],
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
"Operating System :: OS Independent",
],
# Scripts to be packaged and installed in an exe directory
entry_points={ "gui_scripts": ['amr_view = amrlib.amr_view.cli:main' ]}
)
<file_sep>/requirements.txt
# Basic/minimal requirements
penman>=1.1.0
torch>=1.6
numpy
spacy>=2.0 # also requires model download `python -m spacy download en_core_web_sm`
tqdm
transformers>=3.0 # Note that original models trained with v3.4.0
smatch
# Used for amr_view / PlotAMR
PyQt5
graphviz # this requires the Graphviz non-python library to be installed too (see pypi page)
# Used for testing/scoring trained models
nltk
# Other
unidecode # LDC2020T02 pre-processing and adding wiki tags
requests # Adding wiki tags
word2number # used in alignments code
<file_sep>/README.md
# amrlib
**A python library that makes AMR parsing, generation and visualization simple.**
For the latest documentation, see **[ReadTheDocs](https://amrlib.readthedocs.io/en/latest/)**.
**!! Note:** The models must be downloaded and installed separately. See the [Installation Instructions](https://amrlib.readthedocs.io/en/latest/install).
## About
amrlib is a python module designed to make processing for [Abstract Meaning Representation](https://amr.isi.edu/)
(AMR) simple by providing the following functions
* Sentence to Graph (StoG) parsing to create AMR graphs from English sentences.
* Graph to Sentence (GtoS) generation for turning AMR graphs into English sentences.
* A QT based GUI to facilitate conversion of sentences to graphs and back to sentences
* Methods to plot AMR graphs in both the GUI and as library functions
* Training and test code for both the StoG and GtoS models.
* A [SpaCy](https://github.com/explosion/spaCy) extension that allows direct conversion of
SpaCy `Docs` and `Spans` to AMR graphs.
* Sentence to Graph alignment routines
- FAA_Aligner (Fast_Align Algorithm), based on the ISI aligner code detailed in this
[paper](https://www.isi.edu/natural-language/mt/amr_eng_align.pdf).
- RBW_Aligner (Rule Based Word) for simple, single token to single node alignment
* An evaluation metric API including including...
- Smatch (multiprocessed with enhanced/detailed scores) for graph parsing
- BLEU for sentence generation
- Alignment scoring metrics detailing precision/recall
* There is also a related co-referencing project/model at [amr_coref](https://github.com/bjascob/amr_coref).
## AMR Models
The system includes different neural-network models for parsing and for generation.
* Parse (StoG) model parse_t5 gives **81 SMATCH score** with LDC2020T02. This model uses the
pretrained HuggingFace T5 transformer model to convert sentences to graph-encoded sequences which
are then deserialized into an AMR graph.
* Parse (StoG) model parse_gsii gives **77 SMATCH score** with LDC2020T02. This model comes from
[jcyk/AMR-gs](https://github.com/jcyk/AMR-gs), the details of which can be found in this
[paper](https://arxiv.org/abs/2004.05572). The version of the model used here eliminates
much of the data abstraction (aka anonymization) used in the original code
* Generation (GtoS) generate_t5wtense gives a **54 BLEU** with tense tags or **44 BLEU** with un-tagged LDC2020T02.
Similar to parse_t5, the model takes advantage of the pretrained [HuggingFace](https://github.com/huggingface/transformers)
T5 transformer. Details on using this type of model for generation can be found in this
[paper](https://arxiv.org/abs/2007.08426). The model is fine-tuned to translate AMR graphs to English
sentences.
* Generation (GtoS) generate_t5 gives a **43 BLEU**. This model is deprecated in favor of the above model "with tense".
* CoReference resolution at [amr_coref](https://github.com/bjascob/amr_coref) achieves a **0.548 CoNLL-2012 average** score.
For more information on the models see their descriptions in **[ReadTheDocs/Models](https://amrlib.readthedocs.io/en/latest/models)**.
**!! Note:** The models must be downloaded and installed separately. See the [Installation Instructions](https://amrlib.readthedocs.io/en/latest/install).
## AMR View
The GUI allows for simple viewing, conversion and plotting of AMR Graphs.

<!--- docs/images/AMRView01.png --->
<!--- https://github.com/bjascob/amrlib/raw/master/docs/images/AMRView01.png --->
## Requirements and Installation
The project was built and tested under Python 3 and Ubuntu but should run on any Linux, Windows, Mac, etc.. system.
See [Installation Instructions](https://amrlib.readthedocs.io/en/latest/install) for details on setup.
## Library Usage
To convert sentences to graphs
```
import amrlib
stog = amrlib.load_stog_model()
graphs = stog.parse_sents(['This is a test of the system.', 'This is a second sentence.'])
for graph in graphs:
print(graph)
```
To convert graphs to sentences
```
import amrlib
gtos = amrlib.load_gtos_model()
sents, _ = gtos.generate(graphs)
for sent in sents:
print(sent)
```
For a detailed description see the [Model API](https://amrlib.readthedocs.io/en/latest/api_model/).
## Usage as a Spacy Extension
To use as an extension, you need spaCy version 2.0 or later. To setup the extension and use it do the following
```
import amrlib
import spacy
amrlib.setup_spacy_extension()
nlp = spacy.load('en_core_web_sm')
doc = nlp('This is a test of the SpaCy extension. The test has multiple sentences.')
graphs = doc._.to_amr()
for graph in graphs:
print(graph)
```
For a detailed description see the [Spacy API](https://amrlib.readthedocs.io/en/latest/api_spacy/).
## Paraphrasing
For an example of how to use the library to do paraphrasing, see the
[Paraphrasing](https://amrlib.readthedocs.io/en/latest/paraphrase/) section in the docs.
## Issues
If you find a bug, please report it on the [GitHub issues list](https://github.com/bjascob/amrlib/issues).
Additionally, if you have feature requests or questions, feel free to post there as well. I'm happy to
consider suggestions and Pull Requests to enhance the functionality and usability of the module.
<file_sep>/amrlib/utils/logging.py
import logging
from logging import DEBUG, INFO, WARN, ERROR
def setup_logging(logfname=None, level=None):
# Remove any existing handler (ie.. penman has logging.basicConfig() in __init__.py)
# Note that in python 3.6 there is no "force" in basicConfig()
# From https://stackoverflow.com/questions/12158048/changing-loggings-basicconfig-which-is-already-set
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Setup the logger
if level is None:
level = logging.INFO
format = '[%(levelname)s %(filename)s ln=%(lineno)s] %(message)s'
if logfname is not None:
logging.basicConfig(level=level, filename=logfname, filemode='w', format=format)
else:
logging.basicConfig(level=level, format=format)
# Penman spews a lot of messages
def silence_penman():
logging.getLogger('penman').setLevel(logging.ERROR)
#logging.getLogger('penman.layout').setLevel(logging.ERROR)
#logging.getLogger('penman._lexer').setLevel(logging.ERROR)
logging.getLogger('pe').setLevel(logging.ERROR) # pre v1.1, penman._parse.py
# Silense the request library
def silence_requests():
logging.getLogger('urllib3.connectionpool').setLevel(logging.ERROR)
<file_sep>/amrlib/graph_processing/annotator.py
import os
import json
import logging
import multiprocessing
from tqdm import tqdm
import penman
from penman.models.noop import NoOpModel
from .amr_loading import load_amr_entries
from .. import defaults
logger = logging.getLogger(__name__)
# Default set of tags to keep when annotatating the AMR. Throw all others away
# To keep all, redefine this to None
keep_tags=set(['id','snt'])
# Annotate a file with multiple AMR entries and save it to the specified location
def annotate_file(indir, infn, outdir, outfn):
load_spacy()
graphs = []
inpath = os.path.join(indir, infn)
entries = load_amr_entries(inpath)
pool = multiprocessing.Pool()
#for pen in tqdm(map(_process_entry, entries), total=len(entries)):
for pen in tqdm(pool.imap(_process_entry, entries), total=len(entries)):
graphs.append(pen)
pool.close()
pool.join()
infn = infn[:-3] if infn.endswith('.gz') else infn # strip .gz if needed
outpath = os.path.join(outdir, outfn)
print('Saving file to ', outpath)
penman.dump(graphs, outpath, indent=6)
# Annotate a single AMR string and return a penman graph
def annotate_graph(entry, tokens=None):
load_spacy()
return _process_entry(entry, tokens)
# Annotate a single penman AMR Graph and return a penman graph
def annotate_penman(pgraph, tokens=None):
load_spacy()
return _process_penman(pgraph, tokens)
# Worker process that takes in an amr string and returns a penman graph object
# Annotate the raw AMR entries with SpaCy to add the required ::tokens and ::lemmas fields
# plus a few other fields for future pre/postprocessing work that may be needed.
# Keep only tags in "keep_tags"
def _process_entry(entry, tokens=None):
pen = penman.decode(entry) # standard de-inverting penman loading process
return _process_penman(pen, tokens)
# Split out the _process_entry for instances where the string is already converted to a penman graph
def _process_penman(pen, tokens=None):
# Filter out old tags and add the tags from SpaCy parse
global keep_tags
if keep_tags is not None:
pen.metadata = {k:v for k,v in pen.metadata.items() if k in keep_tags} # filter extra tags
# If tokens aren't supplied then annoate the graph
if not tokens:
global spacy_nlp
assert spacy_nlp is not None
tokens = spacy_nlp(pen.metadata['snt'])
pen.metadata['tokens'] = json.dumps([t.text for t in tokens])
ner_tags = [t.ent_type_ if t.ent_type_ else 'O' for t in tokens] # replace empty with 'O'
pen.metadata['ner_tags'] = json.dumps(ner_tags)
pen.metadata['ner_iob'] = json.dumps([t.ent_iob_ for t in tokens])
pen.metadata['pos_tags'] = json.dumps([t.tag_ for t in tokens])
# Create lemmas
# The spaCy 2.0 lemmatizer returns -PRON- for pronouns so strip these (spaCy 3.x does not do this)
# Don't try to lemmatize any named-entities or proper nouns. Lower-case any other words.
lemmas = []
for t in tokens:
if t.lemma_ == '-PRON-': # spaCy 2.x only
lemma = t.text.lower()
elif t.tag_.startswith('NNP') or t.ent_type_ not in ('', 'O'):
lemma = t.text
else:
lemma = t.lemma_.lower()
lemmas.append(lemma)
pen.metadata['lemmas'] = json.dumps(lemmas)
return pen
# Take a graph string entry and process it through spacy to create metadata fields for
# tokens and lemmas using the snt_key. If a 'verify_tok_key' is provided, compare the
# tokenization length for spacy tokenization to the space-tokenized ":tok" field and
# only return a graph is they match.
# This was added speficially for alignments but with a little work, could be harmonized with above
def add_lemmas(entry, snt_key, verify_tok_key=None):
global spacy_nlp
load_spacy()
graph = penman.decode(entry, model=NoOpModel()) # do not de-invert graphs
doc = spacy_nlp(graph.metadata[snt_key])
nlp_tokens = [t.text for t in doc]
graph.metadata['tokens'] = json.dumps(nlp_tokens)
# Create lemmas
# SpaCy's lemmatizer returns -PRON- for pronouns so strip these
# Don't try to lemmatize any named-entities or proper nouns. Lower-case any other words.
lemmas = []
for t in doc:
if t.lemma_ == '-PRON-':
lemma = t.text.lower()
elif t.tag_.startswith('NNP') or t.ent_type_ not in ('', 'O'):
lemma = t.text
else:
lemma = t.lemma_.lower()
lemmas.append(lemma)
graph.metadata['lemmas'] = json.dumps(lemmas)
# If verify_tok_key is not None, verify that the new tokenization is the same as the existing
# and only return the graph if the tokenized length is the same
if verify_tok_key is not None:
isi_tokens = graph.metadata[verify_tok_key].split()
if len(isi_tokens) == len(lemmas) == len(nlp_tokens):
return graph
else:
return None
else:
return graph
# Spacy NLP - lazy loader
# This will only load the model onece, even if called again with a different model name.
# Note that when multiprocessing, call this once from the main process (before using pool)
# to load it into the main processes, then when pool forks, it will be copied, otherwise it
# will be loaded multiple times.
spacy_nlp = None
def load_spacy(model_name=None):
global spacy_nlp
if spacy_nlp is not None: # will return if a thread is already loading
return
model_name = model_name if model_name is not None else defaults.spacy_model_name
#print('Loading SpaCy NLP Model:', model_name)
import spacy
spacy_nlp = spacy.load(model_name)
<file_sep>/tests/auto/ModelGenericTypes.py
#!/usr/bin/python3
import sys
sys.path.insert(0, '../..') # make '..' first in the lib search path
import logging
import unittest
import spacy
import amrlib
graph01 = '''
# ::id DF-199-194215-653_0484.1 ::date 2013-08-30T09:02:09 ::annotator SDL-AMR-09 ::preferred
# ::snt I am 24 and a mother of a 2 and a half year old.
# ::save-date Tue Apr 29, 2014 ::file DF-199-194215-653_0484_1.txt
(a / and
:op1 (a2 / age-01
:ARG1 (i / i)
:ARG2 (t / temporal-quantity :quant 24
:unit (y2 / year)))
:op2 (h / have-rel-role-91
:ARG0 i
:ARG1 (p / person
:age (t3 / temporal-quantity :quant 2.5
:unit (y / year)))
:ARG2 (m / mother)))
'''
# UnitTest creates a separate instance of the class for each test in it.
# The init time doesn't seem to get counted towards the total testing time.
# To avoid loading things multiple times, load in globally and reference it in __init__
# as needed.
SPACY_NLP = spacy.load('en_core_web_sm')
class ModelGenericTypes(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
amrlib.setup_spacy_extension()
self.nlp = SPACY_NLP
def testStoG(self):
stog = amrlib.load_stog_model()
graphs = stog.parse_sents(['This is a test of the system.'])
self.assertEqual(len(graphs), 1)
def testGtoS(self):
gtos = amrlib.load_gtos_model()
sents, clips = gtos.generate([graph01], disable_progress=True)
self.assertEqual(len(sents), 1)
def testSpaCyDoc(self):
doc = self.nlp('This is a test of the SpaCy extension. The test has multiple sentence')
graphs = doc._.to_amr()
self.assertEqual(len(graphs), 2)
def testSpaCySpan(self):
doc = self.nlp('This is a test of the SpaCy extension. The test has multiple sentence')
span = list(doc.sents)[0] # first sentence only
graphs = span._.to_amr()
self.assertEqual(len(graphs), 1)
if __name__ == '__main__':
level = logging.WARNING
format = '[%(levelname)s %(filename)s ln=%(lineno)s] %(message)s'
logging.basicConfig(level=level, format=format)
# run all methods that start with 'test'
unittest.main()
| 58143c2276a066afbab63a29fd807f5e3e9acf81 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | Mechachleopteryx/amrlib | 7ddb4dd59f463ffc6e9d659d01b3b36b98d71afe | 9c91cdc36507f571d3df8bafd930e83442879382 |
refs/heads/master | <file_sep># Unlink
A link shortner
<file_sep>import "../styles.css";
export default () => (
<div>
<h1
className="
m-5 px-5 py-8
rounded
text-white
bg-gradient-to-r from-green-700 to-blue-700"
>
My Work is awesome
</h1>
<button
className="
m-10 px-4 py-2
rounded-full
text-white
bg-gradient-to-r from-orange-500 to-purple-500"
>
Click Here to hire me
</button>
<p
className="inline
m-10 px-4 py-2
rounded-full
text-white
bg-gradient-to-r from-orange-500 to-purple-500 text-xs"
>
Accept me 🤣 please
</p>
</div>
);
| 3494795f53efeaf35296e903e026f530d60daf3b | [
"Markdown",
"JavaScript"
] | 2 | Markdown | anixide/unlink | e3db3fafa48f6481b49aa4aabaca2cd4a1c7ab19 | 02d632457db4fada2441f1347320bd7fbb57ff3e |
refs/heads/master | <file_sep>#include<stdio.h>
void main()
{
int number = 25;
int a = 1, b = 2, c = 3;
float real = 99.99;
float point1 = 45.2, point2 = 30;
char choice = 'a';
char ch1 ='o' , ch2='z';
printf("number = %d\n",number);
printf("a=%d b=%d c=%d\n",a,b,c);
printf("real=%f\n",real);
printf("point1=%.1f point2=%.0f\n",point1,point2);
printf("choice=%c\n",choice);
printf("ch1= %c ch2=%c\n",ch1,ch2);
short int number2 = 32764;
printf("number2=%d",number2);
char subject[12] ="Programming";
char nick[4] ="com" ;
char nick_1[4] = {'C','o','m','\0'};
char name[] = "Jirasak";
}
<file_sep>#include<stdio.h>
int main()
{
printf("58224090131\n");
printf("%-8s %-13s\n","Gunchanick","Wiriyalai");
printf("13/August/1995\n");
printf("%119s\n","http://www.npru.ac.th");
printf("%65s\n","bye bye");
return 0;
}
<file_sep>#include<stdio.h>
void main()
{
char subject[12] ="Programming";
char nick[4] ="com" ;
char nick_1[4] = {'C','o','m','\0'};
char name[] = "Jirasak";
printf("%15s%15s%15s%15s\n",subject,nick,nick_1,name);
}
| 4283c926b0c568724d53aa72a86e109fcef72d7c | [
"C"
] | 3 | C | bitoey/58224090131 | 43737f2959447fdbda06917d90754d298a9a86ae | 66e24ebb0ecca5be972882efa1648d893c5b6987 |
refs/heads/master | <file_sep>package com.evertix.reviewservice.service.impl;
import com.evertix.reviewservice.entities.Review;
import com.evertix.reviewservice.model.User;
import com.evertix.reviewservice.repository.ReviewRepository;
import com.evertix.reviewservice.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ReviewServiceImpl implements ReviewService {
@Autowired
ReviewRepository reviewRepository;
@Autowired
RestTemplate restTemplate;
@Override
public List<Review> getAllReviews() {
return reviewRepository.findAll().stream().map(review -> {
//User student=restTemplate.getForObject("https://user-service/api/users/"+review.getStudentId(),User.class);
//User teacher=restTemplate.getForObject("https://user-service/api/users/"+ review.getTeacherId(),User.class);
User student=restTemplate.getForObject("https://tutofast-user-service.herokuapp.com/api/users/"+review.getStudentId(),User.class);
User teacher=restTemplate.getForObject("https://tutofast-user-service.herokuapp.com/api/users/"+ review.getTeacherId(),User.class);
review.setStudentModel(student);
review.setTeacherModel(teacher);
return review;
}).collect(Collectors.toList());
}
@Override
public Page<Review> getAllReviewsPage(Pageable pageable) {
Page<Review> page=reviewRepository.findAll(pageable);
List<Review> result=page.getContent().stream().map(review -> {
//User student=restTemplate.getForObject("https://user-service/api/users/"+review.getStudentId()+"/",User.class);
//User teacher=restTemplate.getForObject("https://user-service/api/users/"+ review.getTeacherId()+"/",User.class);
User student=restTemplate.getForObject("https://tutofast-user-service.herokuapp.com/api/users/"+review.getStudentId()+"/",User.class);
User teacher=restTemplate.getForObject("https://tutofast-user-service.herokuapp.com/api/users/"+ review.getTeacherId()+"/",User.class);
review.setStudentModel(student);
review.setTeacherModel(teacher);
return review;
}).collect(Collectors.toList());
return new PageImpl<>(result,pageable, page.getTotalElements());
}
/*
@Override
public Page<Review> getReviewsByTeacher(Long teacherId, Pageable pageable) {
return reviewRepository.getAllByTeacherId(teacherId,pageable);
}
@Override
public Review createReview(Long studentId,Long teacherId,Review review) {
return userRepository.findById(studentId).map(student ->{
return userRepository.findById(teacherId).map(teacher ->{
review.setStudent(student);
review.setTeacher(teacher);
return reviewRepository.save(review);
}).orElseThrow(()-> new ResourceNotFoundException("Teacher with id: "+teacherId+"not found"));
}).orElseThrow(()-> new ResourceNotFoundException("Student with id: "+studentId+"not found"));
}
@Override
public Review updateReview(Long reviewId, Review reviewDetails) {
return reviewRepository.findById(reviewId).map(review ->{
review.setDescription(reviewDetails.getDescription());
review.setStars(reviewDetails.getStars());
return reviewRepository.save(review);
}).orElseThrow(()-> new ResourceNotFoundException("Review with id: "+reviewId+"not found"));
}
@Override
public ResponseEntity<?> deleteReview(Long reviewId) {
return reviewRepository.findById(reviewId).map(review ->{
reviewRepository.delete(review);
return ResponseEntity.ok().build();
}).orElseThrow(()-> new ResourceNotFoundException("Review with id: "+reviewId+"not found"));
}
*/
}
<file_sep>package com.evertix.reviewservice.controller;
import com.evertix.reviewservice.entities.Review;
import com.evertix.reviewservice.service.ReviewService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@Tag(name = "Review", description = "API")
@RestController
@RequestMapping("/api/reviews")
public class ReviewController {
@Autowired
ReviewService reviewService;
@GetMapping("/")
@Operation(summary = "Get All Reviews", description = "Get All Review", tags = {"Review"})
public List<Review> getAllReviewsPage(){
return reviewService.getAllReviews();
}
@GetMapping("/page")
@Operation(summary = "Get All Reviews Page", description = "Get All Review Page", tags = {"Review"},
parameters = {
@Parameter(in = ParameterIn.QUERY
, description = "Page you want to retrieve (0..N)"
, name = "page"
, content = @Content(schema = @Schema(type = "integer", defaultValue = "0"))),
@Parameter(in = ParameterIn.QUERY
, description = "Number of records per page."
, name = "size"
, content = @Content(schema = @Schema(type = "integer", defaultValue = "20"))),
@Parameter(in = ParameterIn.QUERY
, description = "Sorting criteria in the format: property(,asc|desc). "
+ "Default sort order is ascending. " + "Multiple sort criteria are supported."
, name = "sort"
, content = @Content(array = @ArraySchema(schema = @Schema(type = "string"))))
})
public Page<Review> getAllReviewsPage(@PageableDefault @Parameter(hidden = true) Pageable pageable){
return reviewService.getAllReviewsPage(pageable);
}
/*
@GetMapping("reviews/teacher/{teacherId}")
@Operation(summary = "Get Reviews By User Id", description = "Get Reviews By Teacher Id", tags = {"Review"})
public Page<ReviewResource> getAllTeachersReviews(@PathVariable(name = "teacherId") Long teacherId, @PageableDefault @Parameter(hidden = true) Pageable pageable){
Page<Review> reviewPage = reviewService.getReviewsByTeacher(teacherId, pageable);
List<ReviewResource> resources = reviewPage.getContent().stream().map(this::convertToResource).collect(Collectors.toList());
return new PageImpl<>(resources,pageable,resources.size());
}
@PostMapping("/reviews/student/{studentId}/teacher/{teacherId}")
@Operation(summary = "Create To Review", description = "Student creates a Review of a Teacher", tags = {"Review"})
public ReviewResource subscribeToPlan(@PathVariable(name = "studentId") Long studentId,@PathVariable(name = "teacherId") Long teacherId,@Valid @RequestBody ReviewSaveResource resource){
return convertToResource(reviewService.createReview(studentId,teacherId,convertToEntity(resource)));
}
@PutMapping("/reviews/{reviewId}")
@Operation(summary = "Create To Review", description = "Student creates a Review of a Teacher", tags = {"Review"})
public ReviewResource updateReviewDetails(@PathVariable(name = "reviewId") Long reviewId,@Valid @RequestBody ReviewSaveResource resource){
return convertToResource(reviewService.updateReview(reviewId,convertToEntity(resource)));
}
@DeleteMapping("/reviews/{reviewId}")
@Operation(summary = "Delete Review", description = "Student delete Review", tags = {"Review"})
public ResponseEntity<?> updateReview(@PathVariable(name = "reviewId") Long reviewId){
return reviewService.deleteReview(reviewId);
}
*/
}
<file_sep>package com.evertix.reviewservice.entities;
import com.evertix.reviewservice.model.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "complaints")
@Getter
@JsonIgnoreProperties(value = {"madeById","reportedId"},allowSetters = true)
@Setter
public class Complaint extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotNull(message = "Name cannot be null")
@NotBlank(message = "Name cannot be blank")
@Size(max = 250)
private String subject;
@Column(unique = true)
@NotNull(message = "Name cannot be null")
@NotBlank(message = "Name cannot be blank")
@Size(max = 250)
private String description;
@Column(name = "madeby_id")
private Long madeById;
@Column(name = "reported_id")
private Long reportedId;
@Transient
private User madeByModel;
@Transient
private User reportedModel;
public Complaint(String subject, String description, Long madeById, Long reportedId) {
this.description=description;
this.subject=subject;
this.madeById=madeById;
this.reportedId=reportedId;
}
public Complaint() {
}
}
<file_sep># Tutofast Review Service
This is a Spring Boot RESTFul API build for future microservices implementation. Entities worked in this project are: Review and Complaints
## Swagger API Documentation
The API Documention is available at this [link](https://tutofast-review-service.herokuapp.com/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config).

## Deploy at Heroku
Main endpoints are available at the links below. For more endpoints check the project.
| Entity |Description |Link|
|----------------|-------------------------------|-----------------------------|
|Session |get All Session |[https://tutofast-review-service.herokuapp.com/api/reviews](https://tutofast-review-service.herokuapp.com/api/reviews).
|SessionDetail |get All SessionDetails |[https://tutofast-review-service.herokuapp.com/api/complaints](https://tutofast-review-service.herokuapp.com/api/complaints) |
## Team
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
Evertix © 2020
<file_sep>package com.evertix.reviewservice.service;
import com.evertix.reviewservice.entities.Complaint;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import java.util.List;
public interface ComplaintService {
List<Complaint> getAllComplaints();
Page<Complaint> getAllComplaintsPage(Pageable pageable);
//Page<Complaint> getAllComplaintsByMadeById(Long madeById, Pageable pageable);
//Page<Complaint> getAllComplaintsByReportedId(Long reportedId, Pageable pageable);
//Complaint createComplaint(Long madeById,Long reportedId, Complaint complaint);
//Complaint updateComplaint(Long complaintId, Complaint complaintDetails);
//ResponseEntity<?> deleteComplaint(Long complaintId);
}
<file_sep>package com.evertix.reviewservice.service;
import com.evertix.reviewservice.entities.Review;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import java.util.List;
public interface ReviewService {
Page<Review> getAllReviewsPage(Pageable pageable);
List<Review> getAllReviews();
//Page<Review> getReviewsByTeacher(Long teacherId, Pageable pageable);
//Review createReview(Long studentId,Long teacherId,Review review);
//Review updateReview(Long reviewId, Review reviewDetails);
//ResponseEntity<?> deleteReview(Long reviewId);
}
<file_sep>package com.evertix.reviewservice.repository;
import com.evertix.reviewservice.entities.Complaint;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ComplaintRepository extends JpaRepository<Complaint, Long> {
Page<Complaint> findAllByMadeById(Long madeById, Pageable pageable);
Page<Complaint> findAllByReportedId(Long reportedId, Pageable pageable);
}
| 7fdc3004965d59f5ced2f49c9300bea245dffccc | [
"Markdown",
"Java"
] | 7 | Java | Gonzarod/review-service | 006302775bbf8aaa5d339dd3e42ddb7a072ea954 | 134cd33e23de87f6944971d8ecd1654b72ced153 |
refs/heads/master | <file_sep>var Strings = {
sanitize: function(str) {
return str.replace(/\W+/g, "-")
}
}
<file_sep>const AjaxRequest = function(cmd) {
var self = this;
var promise = new Promise(function(resolve, reject) {
var ajax = { type: cmd.type, url: cmd.url, headers: {}, contentType: false, processData: false };
if (cmd.data) {
ajax.data = cmd.data
}
var token = cmd.access_token;
if (token) {
ajax.headers.Authorization = "BEARER " + cmd.token;
}
ajax.success = resolve;
ajax.error = function(xhr, err, msg) {
console.error("AJAX Error: %o", arguments);
if (xhr.responseJSON) {
var txt = "["+xhr.responseJSON.code+"] "+xhr.responseJSON.error;
} else {
console.error("ERROR GetMany: %o", arguments);
alert("ERROR: "+msg +" @ "+cmd.url);
}
reject.apply(self, arguments);
}
self.debug && console.log("ajaxRequest[%s]: %o -> %o", cmd.type, cmd.url, ajax);
$.ajax(ajax);
});
return promise;
};
| 7ce1113cde86e2ddb9098b3b4d142c2f005ec447 | [
"JavaScript"
] | 2 | JavaScript | troven/meta4ui | 642947f3e373ef51d28c8acffece2eb268cf7c93 | c741028e903bb9723b7843148af0207b1c06fff4 |
refs/heads/master | <file_sep>package cz.folprechtova.hides.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import cz.folprechtova.hides.R;
import cz.folprechtova.hides.dto.Hide;
public class HideDetail extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_hide_detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //zobrazení šipky zpět - ale ňák to nefachá? :(
Hide hide = (Hide) getIntent().getExtras().getSerializable("HIDE"); //natažení serializable z intentu
TextView titleStand = (TextView) findViewById (R.id.titleStand);
titleStand.setText(hide.getName());
titleStand.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HideDetail.this, MapsActivity.class);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); //zavírání na button zpět
}
return super.onOptionsItemSelected(item);
}
public void onButtonShowMapClick(View v){
Hide hide = (Hide) getIntent().getExtras().getSerializable("HIDE");
float lat = hide.getLatitude();
float lon = hide.getLongitude();
//SharedPreferences sharedPreferences =
// getSharedPreferences(getString(R.string.shared_preferences), MODE_PRIVATE);
//ve strings.xml do toho stringu dát jméno projektu, cz.uhk.folprle1.mapa
startActivity(new Intent(this, MapsActivity.class));
}
}
<file_sep># Myslivost-project
Školní projekt na předmět UMTE
| 696543ca3d51930ad5b57818d4d0ed0bac57afee | [
"Markdown",
"Java"
] | 2 | Java | GentoriArunai/Myslivost-project | 9b50a0ac66d7628a4ac68293e589f452d12c6c9c | c80a2c275fb07ff11489ed790f04c3cb8d516d19 |
refs/heads/master | <repo_name>pronym-inc/josh-project-deploy<file_sep>/commands/commit.command
cd -- "$(dirname "$BASH_SOURCE")/.."
vagrant ssh -c "sudo sudo -u josh_project HOME=/home/josh_project git -C /webapps/josh_project/src/josh_project add /webapps/josh_project/src/josh_project"
echo "Enter commit message:"
read commitmsg
vagrant ssh -c "sudo sudo -u josh_project HOME=/home/josh_project git -C /webapps/josh_project/src/josh_project commit -am '$commitmsg'"
vagrant ssh -c "sudo sudo -u josh_project HOME=/home/josh_project git -C /webapps/josh_project/src/josh_project push"
echo "Git commit complete!"<file_sep>/Makefile
export VAGRANT_GIT_EMAIL=$(shell git config --get user.email)
export VAGRANT_GIT_NAME=$(shell git config --get user.name)
spinup:
echo "192.168.50.48 joshproject.local" | sudo tee -a /etc/hosts
cp ~/.ssh/id_rsa git_ssh_key
vagrant up
sleep 5s
open -a "Google Chrome" http://joshproject.local
update:
vagrant ssh -c "sudo sudo -u josh_project git -C /webapps/josh_project/src/josh_project pull"
vagrant ssh -c "sudo sudo -u josh_project HOME=/home/josh_project /webapps/josh_project/bin/pip install -r /webapps/josh_project/src/josh_project/requirements.pip --upgrade"
vagrant ssh -c "sudo sudo -u josh_project /webapps/josh_project/bin/python /webapps/josh_project/bin/manage.py migrate" | 8277b25262fdea77aa332bd05747bbe454e483f2 | [
"Makefile",
"Shell"
] | 2 | Shell | pronym-inc/josh-project-deploy | 254936358523e8b499f34318c61e873e35b5ac41 | 282d63bbe5386fafeef727a6c2fd0f0a08fafc3e |
refs/heads/master | <file_sep>/**
*This file contains code for sending xml data to server side and getting properties as a response from Server.
*/
/**
* This function will send the xml data via AJAX request.
*/
var xmlContent;
$(document).ready( function () {debugger
document.getElementById('fileChooser').addEventListener('change', handleFileSelect, false);
});
function sendXMLData() {debugger
$.ajax({
url:'convert.spring',
type:'post',
cache:false,
data : {
xmlContent : xmlContent,
},
success : function( result ) {debugger
$("#displayArea").html( result ) ;
},
error : function( error ) {
alert ( "Something Went Wrong" );
}
});
}
function handleFileSelect(evt) {debugger
var files = evt.target.files; // FileList object
//Getting the first file object from File List.
var file = files[0];
var reader = new FileReader();
//Function which reads the data from the file.
reader.readAsText(file);
// Reading and storing the file content in the xmlContent object.
reader.onload = (function(theFile) {
return function(event) {
xmlContent = event.target.result;
};
})(file);
}
| 4f546f53fe5a8db62f59e9b596e6e5b04a7384bc | [
"JavaScript"
] | 1 | JavaScript | raman002/CCU_Java | 8a9f9be72a431b367401c5438394c2b951867b7b | bc1e9a1e563147427e3ec8b21c3869056219e421 |
refs/heads/master | <file_sep>'''
Jenkins handler
A dynamically configurable handler to start Jenkins jobs.
Configuration is available via environment variables, YAS_JENKINS_URL, YAS_JENKINS_USERNAME,
YAS_JENKINS_PASSWORD, and the json encoded YAS_JENKINS_JOBS. For instance, with:
YAS_JENKINS_URL=https://jenkins.example.com
YAS_JENKINS_USERNAME=yas
YAS_JENKINS_PASSWORD=<PASSWORD>
YAS_JENKINS_JOBS='{"MyTestJob": "deploy (?P<branch>\w+) to (?P<site>\w+)"}'
The job 'MyTestJob' on jenkins.example.com would be triggered by the message "@yas deploy master to uat". The named
groups in the command regex will be passed as parameters to the job..
'''
import json
import os
import time
import re
import jenkins
from yas import YasHandler
class JenkinsHandlerError(Exception):
pass
class JenkinsHandler(YasHandler):
def __init__(self, bot):
super().__init__(bot)
raw_jobs = json.loads(os.environ.get('YAS_JENKINS_JOBS', '{}'))
self.jobs = {name: re.compile(regex) for name, regex in raw_jobs.items()}
url = os.environ.get('YAS_JENKINS_URL')
username = os.environ.get('YAS_JENKINS_USERNAME')
password = os.environ.get('<PASSWORD>')
self.timeout = int(os.environ.get('YAS_JENKINS_BUILD_TIMEOUT', 30))
self.server = jenkins.Jenkins(url, username=username, password=<PASSWORD>)
self.server.get_whoami()
self.current_job = None
self.current_match = None
self.verbose_reply = False
def test(self, data):
text = data.get('text', '').strip()
if text.endswith('verbose'):
self.verbose_reply = True
for job, regex in self.jobs.items():
current_match = regex.search(text)
if bool(current_match):
self.current_job = job
self.current_match = current_match
return True
return False
def handle(self, _, reply):
job_info = self.server.get_job_info(self.current_job)
next_build_number = job_info['nextBuildNumber']
self.server.build_job(self.current_job, parameters=self.current_match.groupdict())
pretty_params = ', '.join([f'`{name}: {value}`' for name, value in self.current_match.groupdict().items()])
reply(f'Starting build {next_build_number} of {self.current_job} with {pretty_params}')
for _ in range(self.timeout):
time.sleep(1)
job_info = self.server.get_job_info(self.current_job)
if job_info['lastBuild']['number'] == next_build_number:
break
else:
reply(f'Build {next_build_number} of {self.current_job} did not start in {self.timeout} seconds. '
f' It may have failed, please check <{job_info["url"]}|the job> before notifying your ops team.')
return
build_info = self.server.get_build_info(self.current_job, job_info['lastBuild']['number'])
if self.verbose_reply:
reply(f'Build started: <{build_info["url"]}|{build_info["displayName"]}>'
f' with an estimated duration of {build_info["estimatedDuration"]} milliseconds.')
else:
reply(f'Build started: <{build_info["url"]}|{build_info["displayName"]}>')
<file_sep>[MASTER]
ignore=.git
persistent=yes
[MESSAGES CONTROL]
disable=hex-method,next-method-called,metaclass-assignment,buffer-builtin,unpacking-in-except,print-statement,old-raise-syntax,unichr-builtin,file-builtin,cmp-method,raising-string,intern-builtin,setslice-method,filter-builtin-not-iterating,delslice-method,long-suffix,dict-iter-method,input-builtin,getslice-method,backtick,suppressed-message,basestring-builtin,cmp-builtin,dict-view-method,round-builtin,unicode-builtin,reduce-builtin,using-cmp-argument,coerce-builtin,oct-method,long-builtin,raw_input-builtin,execfile-builtin,old-division,map-builtin-not-iterating,no-absolute-import,old-octal-literal,xrange-builtin,reload-builtin,import-star-module-level,standarderror-builtin,coerce-method,useless-suppression,indexing-exception,range-builtin-not-iterating,nonzero-method,parameter-unpacking,zip-builtin-not-iterating,old-ne-operator,apply-builtin,missing-docstring,too-few-public-methods,no-member,import-error,anomalous-backslash-in-string
[REPORTS]
output-format=text
files-output=no
reports=yes
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
[TYPECHECK]
ignore-mixin-members=yes
ignored-modules=
ignored-classes=optparse.Values,thread._local,_thread._local
generated-members=
contextmanager-decorators=contextlib.contextmanager
[MISCELLANEOUS]
notes=FIXME,XXX,TODO
[FORMAT]
max-line-length=120
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
single-line-if-stmt=no
no-space-check=trailing-comma,dict-separator
max-module-lines=1000
indent-string=' '
indent-after-paren=4
expected-line-ending-format=
[VARIABLES]
init-import=no
dummy-variables-rgx=(_+[a-zA-Z0-9]*?$)|dummy
additional-builtins=
callbacks=cb_,_cb
redefining-builtins-modules=six.moves,future.builtins
[SIMILARITIES]
min-similarity-lines=4
ignore-comments=yes
ignore-docstrings=yes
ignore-imports=yes
[BASIC]
good-names=i,j,k,ex,Run,_
bad-names=foo,bar,baz,toto,tutu,tata
name-group=
include-naming-hint=no
property-classes=abc.abstractproperty
function-rgx=[a-z_][a-z0-9_]{2,30}$
function-name-hint=[a-z_][a-z0-9_]{2,30}$
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
method-rgx=[a-z_][a-z0-9_]{2,30}$
method-name-hint=[a-z_][a-z0-9_]{2,30}$
argument-rgx=[a-z_][a-z0-9_]{2,30}$
argument-name-hint=[a-z_][a-z0-9_]{2,30}$
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
attr-rgx=[a-z_][a-z0-9_]{2,30}$
attr-name-hint=[a-z_][a-z0-9_]{2,30}$
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
variable-rgx=[a-z_][a-z0-9_]{2,30}$
variable-name-hint=[a-z_][a-z0-9_]{2,30}$
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
class-rgx=[A-Z_][a-zA-Z0-9]+$
class-name-hint=[A-Z_][a-zA-Z0-9]+$
no-docstring-rgx=^_
docstring-min-length=-1
[ELIF]
max-nested-blocks=5
[CLASSES]
defining-attr-methods=__init__,__new__,setUp
valid-classmethod-first-arg=cls
valid-metaclass-classmethod-first-arg=mcs
exclude-protected=_asdict,_fields,_replace,_source,_make
[DESIGN]
max-args=10
ignored-argument-names=_.*
max-locals=15
max-returns=6
max-branches=12
max-statements=50
max-parents=7
max-attributes=7
min-public-methods=2
max-public-methods=20
max-bool-expr=5
[IMPORTS]
deprecated-modules=optparse
import-graph=
ext-import-graph=
int-import-graph=
known-standard-library=
known-third-party=enchant
analyse-fallback-blocks=no
[EXCEPTIONS]
overgeneral-exceptions=Exception
<file_sep># Yas Jenkins [Handler]
###### A handler for [yas](github.com/schlueter/yas) to interact with a Jenkins instance
## Setup
To simply run a an instance of yas with this handler, `docker run` may be executed directly, albeit with a number of requisite environment variables:
docker run --rm --tty \
--env YAS_SLACK_TOKEN=<KEY> \
--env YAS_BOT_NAME=yasjenkins \
--env YAS_JENKINS_URL=https://jenkins.example.com \
--env YAS_JENKINS_USERNAME=yasjenkins \
--env YAS_JENKINS_PASSWORD=<PASSWORD> \
--env YAS_JENKINS_JOBS='{"MyJob": "do ci (?P<branch>\w+)"}' \
--env YAS_HANDLER_LIST=yas.handlers.ignored_types_handler.,yas.handlers.not_talking_to_bot_handler.,yas.handlers.help_handler.,yas.handlers.identify_handler.,yasjenkins.,yas.handlers.rules_handler.,yas.handlers.default_handler. \
schlueter/yasjenkins:latest
That handler list should be made DRYer sometime; the important bit for this module is the `yasjenkins.`, but the
rest is mostly necessary for YAS to operate in a reasonable way.
With yas installed manually, this module may be installed from pip with `python -m pip install yasjenkins` and the handler entry
"yasjenkins." added to the `YAS_HANDLER_LIST` environment variable in the execution environment. This handler may work
with pre 2.0 versions of yas by adding it to the handler list in the configuration file, but that is neither tested nor supported.
## Configuration
In addition to the configuration of yas itself, this handler is configured via the environment variables `YAS_JENKINS_URL`,
`YAS_JENKINS_USERNAME`, `YAS_JENKINS_PASSWORD`, and `YAS_JENKINS_JOBS`. The url, username, and password refer to the url
of a Jenkins instance, and the user credentials for a user on that instance. A service account should be preferred. The
jobs variable is used to expose jobs (surprise) via the indicated command. The command is a python regex string with any
parameters to the job present as named group like `(?P<my_parameter>\w+)` where my_parameter matches an **existing**
parameter defined in the job and `\w+` will match any value which should be expected from a slack request.
## Architecture
This plugin uses the [python-jenkins](https://python-jenkins.readthedocs.io/en/latest/) module to interact with the
configured Jenkins instance. At present (version 1.0) only triggering builds of jobs is exposed. The configured
jobs' command regexes are looped over to determine if any of them match a previously unmatched message to the host
YAS instance and a request to build the associated job is sent. At present (version 1.0) there is meek acknowledgement
that the request was made (it doesn't indicate which job or anything else), and nothing more. Improving that initial
response should be an expected feature in an upcoming version, but acknowledgement of failure or other state of
completion of the job will be left to the Jenkins job.
<file_sep>from yasjenkins.handler import JenkinsHandler
| ea8ba94f3218ecd68179f7e98990c0368948ae55 | [
"Markdown",
"Python",
"INI"
] | 4 | Python | schlueter/yasjenkins | e6f54b3f0f6dc85dd4859ca3d38c9ce2c939c4b3 | 9d5fa7a0095f721f64b8b1fc803b62c688aa1ea6 |
refs/heads/master | <repo_name>ericriot/EALGT<file_sep>/assets/javascript/site.js
$(document).ready( function() {
// Responsive stuff for the homepage. If they have a large enough screen, give them the nice tagline image and the google map
if($(window).width() >= 735) {
// Clear the current header div
$("div#tag").empty();
// Create a new tagline image and give it a source and alt text
var tag = $('<img id="tagImage">'); // Creates a new image
tag.attr('src', 'assets/images/tag.gif');
tag.attr('alt', 'HUNTER MEMORIAL GOLF COURSE / SATURDAY, OCTOBER 19th 2013. To raise awareness of mental illness and support the Evan Allen Landry Memorial Scholarship');
tag.attr('title', 'HUNTER MEMORIAL GOLF COURSE / SATURDAY, OCTOBER 19th 2013. To raise awareness of mental illness and support the Evan Allen Landry Memorial Scholarship');
tag.appendTo("div#tag");
}
});<file_sep>/sponsors.php
<?php
$page_title = "2013 Sponsors";
include('assets/php/header.php');
require('assets/php/functions.php');
?>
<h3>2013 Sponsors</h3>
<p>Pay a visit to one of these great local businesses that help make this tournament possible. Please consider <a href="sponsor.php">becoming a sponsor</a>.</p>
<ul id="sponsors">
<?php
$strLevel = "";
$sql = "
SELECT name, website, image, level, description
FROM sponsors_display
WHERE year = 2013
ORDER BY sort ASC;
";
// Make sure sql is ok
$stmt = prepareStatement($mysqli, $sql);
$stmt->execute();
// bind the name and email address
$stmt->bind_result($name, $website, $image, $level, $description);
while ($stmt->fetch()) {
if ($strLevel != $level) {
echo "</ul>\n\n";
echo "<h2>$level Sponsors</h2>\n\n";
echo "<ul id=\"sponsors\">\n";
$strLevel = $level;
}
if ($image == '') {
$image = "Min_EAL.gif";
}
echo "<li>\n";
echo "<div class=\"sponsor_image\">\n";
echo "<span></span>\n";
$img = "<img src=\"assets/images/sponsors/$image\" alt=\"$name\" title=\"$name\" />";
if ($website != '') {
echo "<a href=\"$website\" target=\"_blank\">$img</a>\n";
} else {
echo "$img\n";
}
echo "<br class=\"clear\" />\n";
echo "</div>\n";
echo "$name<br />\n";
if ($description != '') {
echo "<em>$description</em><br />\n";
}
if ($website != '') {
echo "<a href=\"$website\" target=\"_blank\">Visit Website</a><br />\n";
}
echo "<br class=\"clear\" />\n";
echo "</li>\n\n";
}
$mysqli->close();
?>
</ul>
<?php require('assets/php/footer.php'); ?><file_sep>/payment_cancel.php
<?php
session_start(); // This page will use the session variables
// We're good, back to the regular setup
$payment_amount = $_SESSION['payment_amount'];
?>
<?php include('assets/php/header.php'); ?>
<h3>Payment Cancel Page</h3>
<p>User Chickened Out.</p>
<?php require('assets/php/footer.php'); ?>
<file_sep>/payment_proc.php
<?php
session_start(); // This page will use the session variables
require('assets/php/functions.php');
// We're good, back to the regular setup
$payment_amount = $_SESSION['payment_amount'];
$payment_mode = $_SESSION['payment_mode'];
$payment_mode_friendly = '';
$id = $_SESSION[$payment_mode . '_id'];
// This page only hits on a successful pay pal transaction, so we don't have to worry about any pay pal errors at this point
$PPREF = getGetValue('PPREF');
$TRANSTIME = getGetValue('TRANSTIME');
// store the date/time and order reference number provided by PayPal. May add more but this should be fine
switch ($payment_mode) {
case 'donation':
$sql = " UPDATE donations SET PPREF = ?, TRANSTIME = ? WHERE Id = ? ";
break;
case 'registration':
$sql = " UPDATE registrations SET PPREF = ?, TRANSTIME = ? WHERE Id = ? ";
break;
case 'sponsor':
$sql = " UPDATE sponsors SET PPREF = ?, TRANSTIME = ? WHERE Id = ? ";
break;
}
// echo "sql = " . $sql . "<br />";
// echo "payment_mode = " . $payment_mode . "<br />";
$stmt = prepareStatement($mysqli, $sql);
// Bind the params
$stmt->bind_param("ssi", $PPREF, $TRANSTIME, $id);
// And run it
$stmt->execute();
// Get the user name and email based on payment_mode
switch ($payment_mode) {
case 'donation':
$sql = " SELECT name, email FROM donations WHERE Id = ? ";
$payment_mode_friendly = 'Donation';
break;
case 'registration':
$sql = " SELECT name, email FROM registrations_people WHERE form_order = 1 AND registration_id = ? ";
$payment_mode_friendly = 'Registration';
break;
case 'sponsor':
$sql = " SELECT name, email FROM sponsors WHERE Id = ? ";
$payment_mode_friendly = 'Sponsorship';
break;
}
// Make sure sql is ok
$stmt = prepareStatement($mysqli, $sql);
// Bind the id
// Bind the params
$stmt->bind_param("i", $id);
$stmt->execute();
// bind the name and email address
$stmt->bind_result($name, $email);
$stmt->fetch();
$strSubject = "EAL Golf Tournament - " . $payment_mode_friendly . " Confirmation";
// No header include here, need email friendly mark-up
$strBody = '<body style=" font-family:Arial; font-size:11pt; ">';
$strBody .= '<img src="http://ealgolftournament.com/assets/images/eal-logo.gif" alt="EAL Golf Tournament" style="width:250px; padding:3px; border:1px solid #94C33F;" /><br /><br />';
$strBody .= 'Dear ' . $name . '<br /><br />';
$strBody .= 'Thanks for your ' . $payment_mode_friendly . ' amount of $' . $payment_amount . '. We truly appreciate your support.<br /><br />';
$strBody .= '<strong>Order Summary:</strong><br /><br />';
$strBody .= 'Please retain for your records.<ul>';
$strBody .= '<li>' . $payment_mode_friendly . ' Id: ' . $id . '</li>';
$strBody .= '<li>PayPal Transaction Id: ' . $PPREF . '</li>';
$strBody .= '</ul>';
$strBody .= '<strong>Tournament Details:</strong><br /><br />';
$strBody .= 'Be sure to tell your friends!<ul>';
$strBody .= '<li>Date: Saturday, October 19<sup>th</sup> 2013</li>';
$strBody .= '<li>Registration: 11AM</li>';
$strBody .= '<li>Location: Hunter Golf Club - 688 Westfield Rd, Meriden, CT 06450</li>';
$strBody .= '<li>Website: <a href="http://ealgolftournament.com/">http://ealgolftournament.com/</a></li>';
$strBody .= '<li>Twitter: <a href="https://twitter.com/@EALGolfTourney">https://twitter.com/@EALGolfTourney</a></li>';
$strBody .= '</ul>';
$strBody .= '</body>';
// echo $strBody;
// Now send the email and redirect the opener to the thank you page.
// $strBody = implode("|", get_defined_vars());
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Bcc: <EMAIL>, <EMAIL>' . "\r\n";
$headers .= 'From: <EMAIL>' . "\r\n";
if ($GLOBALS['serverMode'] == "LIVE") {
mail($email, $strSubject, $strBody, $headers, "");
} else {
echo $strBody;
die('Local version, no redirect');
}
// Order record is updated, email is sent
?>
<script language="javascript">
window.parent.location.replace('payment_thankYou.php');
</script><file_sep>/payment_thankYou.php
<?php
session_start();
$page_title = "Thank You";
include('assets/php/header.php');
// This page will use the session variables
require('assets/php/functions.php');
$payment_mode = $_SESSION['payment_mode'];
$strHeading = '';
switch ($payment_mode) {
case 'donation':
$strHeading = 'Thank you for supporting the Evan Allen Landry Golf Tournament.';
break;
case 'registration':
$strHeading = 'Thank you for supporting the Evan Allen Landry Golf Tournament.<br />We look forward to seeing you there!';
break;
case 'sponsor':
$strHeading = 'Thank you for supporting the Evan Allen Landry Golf Tournament.';
break;
}
?>
<h3><?php echo $strHeading; ?></h3>
<p>An email has been sent to you confirming your order details.</p>
<?php require('assets/php/footer.php'); ?><file_sep>/sponsor_proc.php
<?php
require('assets/php/functions.php');
require('assets/php/variables.php');
require('assets/php/paypal.php');
session_start(); // This page will store session variables for the payment screen.
// This page will store all info for a registration
$name = getPostValue('name');
$name_contact = getPostValue('name_contact');
$level = getPostValue('level');
$address = getPostValue('address');
$city_state = getPostValue('city_state');
$email = getPostValue('email');
$phone = getPostValue('phone');
$message = getPostValue('message');
switch ($level) {
case "Platinum Sponsor":
$payment_amount = 2500;
break;
case "Gold Sponsor":
$payment_amount = 1000;
break;
case "Silver Sponsor":
$payment_amount = 500;
break;
case "Longest Drive Sponsor":
$payment_amount = 250;
break;
case "Closest to the Pin Sponsor":
$payment_amount = 250;
break;
case "Tee Sponsor":
$payment_amount = 125;
break;
default:
$payment_amount = 0;
break;
}
// Create an inserto statement. This is a two phase process, kind of strange but safer I guess
$sql = " INSERT INTO sponsors ( submitted_at, name, name_contact, address, city_state, phone, email, sponsor_level, message, payment_amount ) "
. " VALUES ( NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ? ) ; ";
$stmt = prepareStatement($mysqli, $sql);
// Bind the params
$stmt->bind_param("ssssssssd", $name, $name_contact, $address, $city_state, $phone, $email, $level, $message, $payment_amount);
// Execute the above statement, and get our registration_id
executeStatement($stmt);
$sponsor_id = $mysqli->insert_id;
// echo "registration_id = $registration_id<br />";
// Store registration_id and payment_amount as session variables
$_SESSION['sponsor_id'] = $sponsor_id;
$_SESSION['payment_amount'] = $payment_amount;
$_SESSION['payment_mode'] = 'sponsor'; // One form will have payPayl iframe, send it some info
$_SESSION['SECURETOKENID'] = '2013_' . $_SESSION['payment_mode'] . '_' . $sponsor_id . '_' . $serverMode;
// Now connect to paypal and request a transaction. I'm not sure if I should do it here later.
// Note, user has 30 minutes to complete the transaction
$_SESSION['SECURETOKEN'] = ppGetSecureToken($payment_amount, $_SESSION['SECURETOKENID'], $name, $email, $level );
// echo ('payment_amount = ' . $payment_amount);
// Close our db connection
$mysqli->close();
header('location: payment.php');
?><file_sep>/assets/php/header.php
<!DOCTYPE html>
<html>
<head>
<title><?php if (isset($page_title)) { echo $page_title . ' - ' ; } ?>Evan Allen Landry Golf Tournament</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
<link rel="shortcut icon" href="assets/images/fav.ico" type="image/x-icon" />
<script type="text/javascript" src="assets/javascript/jquery-1.10.2.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
<div id="container">
<div id="logo_holder">
<a href="index.php"><img src="assets/images/eal-logo.gif" alt="Evan Allen Landry 1st Annual Golf Tournament - 2013" /></a>
</div>
<div id="tag">
<h1>HUNTER MEMORIAL GOLF COURSE / SATURDAY, OCTOBER 19<SUP>th</SUP> 2013</h1>
<h2>To raise awareness of mental illness and support the Evan Allen Landry Memorial Scholarship</h2>
</div><file_sep>/register_proc.php
<?php
require('assets/php/functions.php');
require('assets/php/variables.php');
require('assets/php/paypal.php');
session_start(); // This page will store session variables for the payment screen.
// This page will store all info for a registration
$payment_amount = 0; // I will calc this, dont want to get it from the front end. This frustrates me, pricing is very spread out
// Create an inserto statement. This is a two phase process, kind of strange but safer I guess
$sql = " INSERT INTO registrations ( submitted_at ) VALUES ( NOW() ) ; ";
$stmt = prepareStatement($mysqli, $sql);
// Execute the above statement, and get our registration_id
executeStatement($stmt);
$registration_id = $mysqli->insert_id;
// echo "registration_id = $registration_id<br />";
// Now prepare the insert statement 1 time, out of the loop
$sql = " INSERT INTO registrations_people ( registration_id, name, type, address, city_state, email, phone, form_order ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? ) ; ";
$stmt = prepareStatement($mysqli, $sql);
for ($i = 1; $i <=4; $i += 1) {
$name = getPostValue('name_' . $i);
$type = getPostValue('registration_type_' . $i);
$address = getPostValue('address_' . $i);
$city_state = getPostValue('city_state_' . $i);
$email = getPostValue('email_' . $i);
$phone = getPostValue('phone_' . $i);
if ($name != "" && $type != "") {
// these are just like sql query params, i = integer, s = string, b = text / blob
$stmt->bind_param("issssssi", $registration_id, $name, $type, $address, $city_state, $email, $phone, $i);
executeStatement($stmt);
// echo "$i: name = $name, type = $type, address = $address, city_state = $city_state, email = $email, phone = $phone<br />";
if ($type == "Player") {
$payment_amount += $cost_player;
} elseif ($type == "Guest") {
$payment_amount += $cost_guest;
}
}
}
$message = getPostValue('message');
// Store the payment amount and message
$sql = " UPDATE registrations SET payment_amount = ?, message = ? WHERE Id = ? ";
$stmt = prepareStatement($mysqli, $sql);
// Bind the params
$stmt->bind_param("dsi", $payment_amount, $message, $registration_id);
// And run it
$stmt->execute();
// Reset name and email for paypal records
$name = getPostValue('name_1');
$email = getPostValue('email_1');
// Store registration_id and payment_amount as session variables
$_SESSION['registration_id'] = $registration_id;
$_SESSION['payment_amount'] = $payment_amount;
$_SESSION['payment_mode'] = 'registration'; // One form will have payPayl iframe, send it some info
$_SESSION['SECURETOKENID'] = '<PASSWORD>_' . $_SESSION['payment_mode'] . '_' . $registration_id . '_' . $serverMode;
// Now connect to paypal and request a transaction. I'm not sure if I should do it here later.
// Note, user has 30 minutes to complete the transaction
$_SESSION['SECURETOKEN'] = ppGetSecureToken($payment_amount, $_SESSION['SECURETOKENID'], $name, $email, "Registration" );
header('location: payment.php');
?><file_sep>/sql/sponsors_add.sql
INSERT INTO sponsors_display (name, level, website, image, year, sort)
VALUES
('Central Connecticut Acoustics','Platinum', 'http://www.centralconnacoustics.com/', 'CCA Logo.jpg', 2013, 1),
('Armstrong World Industries','Platinum', 'http://www.armstrong.com/', 'armstrong_logo300x68.gif', 2013, 2),
('USG Interiors','Gold', 'http://www.usg.com/', 'usg_logo.gif', 2013, 3),
('Seasons Federal Credit Union','Gold', 'https://www.seasonsfcu.org/', 'seasons_logo.png', 2013, 4),
('Bill & <NAME> Contractors', 'Gold', '', '', 2013, 5),
('Apical Land Care','Gold', 'http://www.apicallandcare.com/', 'apical_land_care.png', 2013, 6),
('Fasulo & Albini, CPAs','Silver', 'http://southington.patch.com/listings/fasulo-albini', '', 2013, 7),
('Life Choice Donor Services','Closest to the Pin', 'http://www.lifechoiceopo.org/', 'life_choice.jpg', 2013, 8),
('<NAME>, CPA','Closest to the Pin', 'https://www.meridenchamber.com/directory/MemberView.asp?MemberID=3617', '', 2013, 9),
('Riotte Consulting','Longest Drive', 'http://riotteconsulting.com/', 'riotte_consulting.jpg', 2013, 10),
('Marjam Supply Company','Longest Drive','http://www.marjam.com/', 'marjam_logo.png', 2013, 11),
('Dunkin Donuts of Broad Street Meriden', 'Longest Drive', 'http://www.dunkindonuts.com/content/dunkindonuts/en/stores.html?t=57+S+Broad+St%2C+Meriden%2C+CT+06450#.Ujcm5Z5jYzo.gmail', 'dunkin_logo.png', 2013, 12),
('Fiderio & Sons','Tee', 'http://www.fiderio.com/', 'fiderio.png', 2013, 13),
('Champagne Financial Services','Tee', 'http://southington.patch.com/listings/champagne-financial-services', '', 2013, 14),
('Rotating Composite Technologies','Tee', 'http://rotatingcomposites.com/', 'rct.png', 2013, 15),
('B&B Threaded Components','Tee', 'http://www.bbthreaded.com/', 'b_and_b.jpg', 2013, 16),
('<NAME> of William Raveis Real Estate','Tee', 'http://michaelchoromanski.raveis.com/michaelchoromanski/?SITE=agt', 'raveis.png', 2013, 17),
('<NAME>','Tee', '', '', 2013, 18),
('<NAME>','Tee', 'https://www.romanoil.com/', 'roman_oil_logo.png', 2013, 19),
('EBM Papst', 'Tee', 'http://www.ebmpapst.com/','ebm_papst.gif',2013, 20)
;
<file_sep>/sponsor.php
<?php
$page_title = "Sponsor";
include('assets/php/header.php');
require('assets/php/functions.php');
?>
<h3>Sponsorship</h3>
<p><a href="sponsors.php">View the 2013 Sponsors</a></p>
<?php if(registrationClosed() ): ?>
<?php showClosedDiv(); ?>
<br class="clear" />
<?php else : ?>
<ul id="sponsorship">
<li><div class="description">Platinum Sponsor</div> <div class="price">$2500</div>
<ul>
<li>Two Foursomes</li>
<li>Two Tee Signs</li>
<li>Recognition on Sponsor Board & Program Book</li>
</ul>
</li>
<li><div class="description">Gold Sponsor</div> <div class="price">$1000</div>
<ul>
<li>One Foursome</li>
<li>Two Tee Signs</li>
<li>Recognition on Sponsor Board & Program Book</li>
</ul>
</li>
<li><div class="description">Silver Sponsor</div> <div class="price">$500</div>
<ul>
<li>Two Tee Signs</li>
<li>Recognition on Sponsor Board & Program Book</li>
</ul>
</li>
<li><div class="description">Longest Drive Sponsor</div> <div class="price">$250</div>
<ul>
<li>Name Listed at Tee</li>
<li>Recognition on Sponsor Board & Program Book</li>
</ul>
</li>
<li><div class="description">Closest to the Pin Sponsor</div> <div class="price">$250</div>
<ul>
<li>Name Listed at Tee</li>
<li>Recognition on Sponsor Board & Program Book</li>
</ul>
</li>
<li><div class="description">Tee Sponsor</div> <div class="price">$125</div>
<ul>
<li>Sign at Tee</li>
<li>Recognition in Program Book</li>
</ul>
</li>
</ul>
<div class="clear"></div>
<p>* Indicates required field.</p>
<form action="sponsor_proc.php" method="post" id="registerForm">
<div class="registration">
<fieldset><span>Business Name:</span> * <input type="text" class="text" name="name" id="name" /></fieldset>
<fieldset><span>Contact Name:</span> * <input type="text" class="text" name="name_contact" id="name_contact" /></fieldset>
<div class="clear"></div>
<fieldset>Address: * <input type="text" class="text" name="address" id="address" /></fieldset>
<fieldset>City, State: * <input type="text" class="text" name="city_state" id="city_state" /></fieldset>
<div class="clear"></div>
<fieldset>Email: * <input type="text" class="text" name="email" id="email" /></fieldset>
<fieldset>Phone: * <input type="text" class="text" name="phone" id="phone"/></fieldset>
<div class="clear"></div>
<fieldset><span>Sponsorship Level:</span> *
<select id="level" name="level">
<option value="">Please select...</option>
<option value="Platinum Sponsor">Platinum Sponsor</option>
<option value="Gold Sponsor">Gold Sponsor</option>
<option value="Silver Sponsor">Silver Sponsor</option>
<option value="Longest Drive Sponsor">Longest Drive Sponsor</option>
<option value="Closest to the Pin Sponsor">Closest to the Pin Sponsor</option>
<option value="Tee Sponsor">Tee Sponsor</option>
</select>
</fieldset>
<div class="clear"></div>
<fieldset>Message to us <em>(Optional)</em> <textarea class="text" name="message" id="message"></textarea>
</fieldset>
<div class="clear"></div>
</div>
<div class="registration">
Total Due: <span id="TotalDue">--</span><br />
<fieldset><input type="image" src="assets/images/continue.gif" alt="Continue" /></fieldset>
<p>Please Note: Your sponsorship will not be completed until you enter payment information on the next page. </p>
<div class="clear"></div>
</div>
</form>
<script type="text/javascript" src="assets/javascript/sponsor.js"></script>
<?php endif; ?>
<?php require('assets/php/footer.php'); ?><file_sep>/payment_error.php
<?php
session_start(); // This page will use the session variables
require('assets/php/functions.php');
// We're good, back to the regular setup
$payment_amount = $_SESSION['payment_amount'];
?>
<?php include('assets/php/header.php'); ?>
<h3>PayPal Error.</h3>
<p>We are sorry, something has gone wrong with your PayPal information. Your information has been saved and we will contact you shortly.</p>
<?php
// A function will send this out, hopefully.
emailError("Error received from PayPal");
?>
<?php require('assets/php/footer.php'); ?>
<file_sep>/assets/javascript/register.js
// Recalc the total whenever the form is changed. This should probably be done only on the radios but that's ok.
$("#registerForm").change(function () {
'use strict';
var total = 0, i = 1, playerType;
for (i = 1; i <= 4; i += 1) {
playerType = $('input[name=registration_type_' + i + ']:checked', '#registerForm').val();
// console.log ('i = ' + i + ', value = ' + value);
if (playerType === "Player") {
total += 145;
} else if (playerType === "Guest") {
total += 65;
}
}
$("#TotalDue").text('$' + total.toFixed(2));
});
$("#registerForm").submit(function () {
'use strict';
// Store all the problems in one string, and keep track of the field they should be focused on
var i, strError = '', focusItem = null, name, playerType, email, phone, address, city_state;
// First off, all of registration one is required.
name = $('#name_1');
playerType = $('input[name=registration_type_1]:checked', '#registerForm');
email = $('#email_1');
phone = $('#phone_1');
address = $('#address_1');
city_state = $('#city_state_1');
// Name, email, address, etc. Focus on the highest field up in the list.
if (name.val() === '') {
strError += 'The Name of person 1 is required.\n';
if (!focusItem) { focusItem = name; }
}
if (playerType.val() !== 'Guest' && playerType.val() !== 'Player') {
strError += 'The Type of person 1 is required.\n';
if (!focusItem) { focusItem = playerType; }
}
if (email.val() === '') {
strError += 'The Email of person 1 is required.\n';
if (!focusItem) { focusItem = email; }
}
if (address.val() === '') {
strError += 'The Address of person 1 is required.\n';
if (!focusItem) { focusItem = address; }
}
if (city_state.val() === '') {
strError += 'The City and State of person 1 is required.\n';
if (!focusItem) { focusItem = city_state; }
}
if (phone.val() === '') {
strError += 'The Phone of person 1 is required.\n';
if (!focusItem) { focusItem = phone; }
}
// Now we will loop through the other 3 options. If a name, player type, address is in there, the person will require all of those to be considered ok
// If none of those are filled in, we dont care about them and we move on
for (i = 2; i <= 4; i += 1) {
// Get the next registration
name = $('#name_' + i);
playerType = $('input[name=registration_type_' + i + ']:checked', '#registerForm');
address = $('#address_' + i);
city_state = $('#city_state' + i);
email = $('#email_' + i);
phone = $('#phone_' + i);
// This rule could change to require address and city/state. will wait on mr. landry
if (name.val() !== '' || playerType.val() !== undefined) {
if (name.val() === '') {
strError += 'The Name of person ' + i + ' is required.\n';
if (!focusItem) { focusItem = name; }
}
if (playerType.val() !== 'Guest' && playerType.val() !== 'Player') {
strError += 'The Type of person ' + i + ' is required.\n';
if (!focusItem) { focusItem = playerType; }
}
/* Disabling for now, too strict
if (address.val() === '') {
strError += 'The Address of person ' + i + ' is required.\n';
if (!focusItem) { focusItem = address; }
}
if (city_state.val() === '') {
strError += 'The City and State of person ' + i + ' is required.\n';
if (!focusItem) { focusItem = cityState; }
}
*/
}
}
if (strError === '') {
return true;
} else {
alert(strError);
// focusItem.focus();
// console.log(focusItem);
return false;
}
});<file_sep>/register.php
<?php
$page_title = "Register";
include('assets/php/header.php');
require('assets/php/functions.php');
require('assets/php/variables.php');
?>
<h3>Player / Team / Guest Registration</h3>
<?php if(registrationClosed() ): ?>
<?php showClosedDiv(); ?>
<br class="clear" />
<?php else : ?>
<p>Please complete the form below and click CONTINUE to provide payment information.</p>
<ul id="sponsorship">
<li><div class="description">Golfer</div> <div class="price">$<?php echo $cost_player; ?></div>
<ul>
<li>Includes golf with cart, lunch, and dinner.</li>
</ul>
</li>
<li><div class="description">Dinner Guest</div> <div class="price">$<?php echo $cost_guest; ?></div>
<ul>
<li>Includes dinner only.</li>
</ul>
</li>
</ul>
<div class="clear"></div>
<p>* Indicates required field.</p>
<form action="register_proc.php" method="post" id="registerForm">
<?php for($i = 1; $i <= 4; $i++) : ?>
<div class="registration">
<fieldset><span>Name:</span> <?php if($i == 1) echo "*"; ?> <input type="text" class="text" name="name_<?php echo $i; ?>" id="name_<?php echo $i; ?>" /></fieldset>
<fieldset>Registration Type: <?php if($i == 1) echo "*"; ?>
<label><input type="radio" name="registration_type_<?php echo $i; ?>" value="Player" /> Player</label>
<label><input type="radio" name="registration_type_<?php echo $i; ?>" value="Guest" /> Guest</label>
</fieldset>
<div class="clear"></div>
<fieldset>Address: <?php if($i == 1) echo "*"; ?> <input type="text" class="text" name="address_<?php echo $i; ?>" id="address_<?php echo $i; ?>" /></fieldset>
<fieldset>City, State: <?php if($i == 1) echo "*"; ?> <input type="text" class="text" name="city_state_<?php echo $i; ?>" id="city_state_<?php echo $i; ?>" /></fieldset>
<div class="clear"></div>
<fieldset>Email: <?php if($i == 1) echo "*"; ?> <input type="text" class="text" name="email_<?php echo $i; ?>" id="email_<?php echo $i; ?>" /></fieldset>
<fieldset>Phone: <?php if($i == 1) echo "*"; ?> <input type="text" class="text" name="phone_<?php echo $i; ?>" id="phone_<?php echo $i; ?>"/></fieldset>
<div class="clear"></div>
</div>
<?php endfor; ?>
<div class="registration">
<fieldset>Message to us <em>(Optional)</em> <textarea class="text" name="message" id="message"></textarea>
</fieldset>
<div class="clear"></div>
</div>
<div class="registration">
Total Due: <span id="TotalDue">--</span><br />
<fieldset><input type="image" src="assets/images/continue.gif" alt="Continue" /></fieldset>
<p>Please Note: Your registration will not be completed until you enter payment information on the next page. </p>
<div class="clear"></div>
</div>
</form>
<script type="text/javascript" src="assets/javascript/register.js"></script>
<?php endif; ?>
<?php require('assets/php/footer.php'); ?><file_sep>/donate.php
<?php
$page_title = "Donate";
include('assets/php/header.php'); ?>
<h3>Donation</h3>
<p>Thank you for supporting the Evan Allen Landry Memorial Scholarship. Please complete this form and click CONTINUE to provide payment information.</p>
<p>* Indicates required field.</p>
<form action="donate_proc.php" method="post" id="registerForm">
<div class="registration">
<fieldset><span>Name:</span> * <input type="text" class="text" name="name" id="name" /></fieldset>
<fieldset><span>Amount:</span> * $<input type="text" class="text" name="amount" id="amount" /></fieldset>
<div class="clear"></div>
<fieldset>Address: * <input type="text" class="text" name="address" id="address" /></fieldset>
<fieldset>City, State: * <input type="text" class="text" name="city_state" id="city_state" /></fieldset>
<div class="clear"></div>
<fieldset>Email: * <input type="text" class="text" name="email" id="email" /></fieldset>
<fieldset>Phone: * <input type="text" class="text" name="phone" id="phone"/></fieldset>
<div class="clear"></div>
<fieldset>Message to us <em>(Optional)</em> <textarea class="text" name="message" id="message"></textarea>
</fieldset>
<div class="clear"></div>
</div>
<div class="registration">
<fieldset><input type="image" src="assets/images/continue.gif" alt="Continue" /></fieldset>
<p>Please Note: Your donation will not be completed until you enter payment information on the next page. </p>
<div class="clear"></div>
</div>
</form>
<script type="text/javascript" src="assets/javascript/donate.js"></script>
<?php require('assets/php/footer.php'); ?><file_sep>/assets/javascript/donate.js
// Validate the submission form
$("#registerForm").submit(function () {
'use strict';
// Store all the problems in one string, and keep track of the field they should be focused on
var i, strError = '', focusItem = null, name, amount, email, phone, address, city_state;
// First off, all of registration one is required.
name = $('#name');
email = $('#email');
phone = $('#phone');
address = $('#address');
city_state = $('#city_state');
amount = $('#amount');
// Name, email, address, etc. Focus on the highest field up in the list.
if (name.val() === '') {
strError += 'Name is required.\n';
if (!focusItem) { focusItem = name; }
}
if (amount.val() === '') {
strError += 'Amount is required.\n';
if (!focusItem) { focusItem = amount; }
} else if (!$.isNumeric(amount.val())) {
strError += 'Amount must be a valid dollar amount.\n';
if (!focusItem) { focusItem = amount; }
}
if (email.val() === '') {
strError += 'Email is required.\n';
if (!focusItem) { focusItem = email; }
}
if (address.val() === '') {
strError += 'Address is required.\n';
if (!focusItem) { focusItem = address; }
}
if (city_state.val() === '') {
strError += 'City and State is required.\n';
if (!focusItem) { focusItem = city_state; }
}
if (phone.val() === '') {
strError += 'Phone is required.\n';
if (!focusItem) { focusItem = phone; }
}
if (strError === '') {
return true;
} else {
alert(strError);
// focusItem.focus();
// console.log(focusItem);
return false;
}
});<file_sep>/index.php
<?php
$page_title = "Welcome";
include('assets/php/header.php');
require('assets/php/variables.php');
require('assets/php/functions.php');
?>
<div class="home_option">
<div class="evan_image">
<img src="assets/images/evan_web3.jpg" alt="<NAME>" />
</div>
<div >
<p>
<NAME> was a passionate golfer.
He played countless rounds at Hunter Memorial Golf Course, where enjoying the outdoors and friendship of his fellow golfers was as important as the game.
Tragically, Evan's life was cut short by schizophrenia, which was diagnosed in his mid-twenties.
The Evan Allen Landry Golf Tournament has been created to honor Evan's life and to raise awareness of severe mental illness, which affects 6% of the population and is too often fatal.
Tournament proceeds will be used to fund the Evan Allen Landry Memorial Scholarship.
</p>
</div>
</div>
<?php if(registrationClosed() ): ?>
<?php showClosedDiv(); ?>
<?php else : ?>
<div class="home_option">
<div class="home_image">
<a href="register.php"><img src="assets/images/register.gif" alt="Register" /></a>
</div>
<div class="home_description">
<p>
To register yourself or a team or to register as a non-golfing dinner guest, click REGISTER.
</p>
<ul>
<li>Golfers - $<?php echo $cost_player; ?> per player (includes golf w/cart, lunch and dinner)</li>
<li>Guests - $<?php echo $cost_guest; ?> (dinner only)</li>
</ul>
</div>
</div>
<?php endif; ?>
<div class="home_option">
<div class="home_image">
<a href="sponsor.php"><img src="assets/images/sponsor.gif" alt="Sponsor" id="sponsorImage" /></a>
</div>
<div class="home_description">
<p>
Advertise your business while supporting the Evan Allen Landry Memorial Scholarship. To learn more click SPONSOR.
</p>
<p><a href="sponsors.php">View the 2013 Sponsors</a></p>
</div>
</div>
<div class="home_option">
<div class="home_image">
<a href="donate.php"><img src="assets/images/donate.gif" alt="Donate" /></a>
</div>
<div class="home_description">
<p>
To donate to the Evan Allen Landry Memorial Scholarship, click DONATE.
</p>
</div>
</div>
<div class="home_option">
<div class="home_image">
<img src="assets/images/schedule.gif" alt="Schedule" />
</div>
<div class="home_description">
<ul>
<li>11AM Registration and Complimentary Driving Range
<li>NOON Shotgun Start (Scramble Format)
<li>6PM Dinner at Violi's Tent (at Golf Course)<br />
Raffle and Awards<br />
Prizes for Lowest Team Scores,Closest to Pin, Longest Drive and Hole in One
</li>
</ul>
</div>
</div>
<div class="home_option">
<div class="home_image">
<a href="http://goo.gl/maps/pdhKd" target="_blank"><img src="assets/images/location.gif" alt="Location" /></a>
</div>
<div class="home_description">
<p>
<strong>Hunter Memorial Golf Course</strong> - <a href="http://www.huntergolfclub.com" target="_blank">huntergolfclub.com</a><br />
688 Westfield Road<br />
Meriden, CT 06450<br />
(203) 634-3366<br />
<a href="http://goo.gl/maps/pdhKd" target="_blank">View on Google Maps</a>
</p>
</div>
</div>
<?php require('assets/php/footer.php'); ?>
<file_sep>/assets/php/variables.php
<?php
// A few globals / constants / what have you.
$cost_player = 145;
$cost_guest = 65;
?>
<file_sep>/assets/javascript/sponsor.js
// Show the total due based on dropdown selection
$("select#level").change(function () {
'use strict';
var total = 0, level = '';
level = $('#level').val();
// This pricing is in the front end, the javascript, and the php :-/ should be in a databse but no time.
switch (level) {
case "Platinum Sponsor":
total = 2500;
break;
case "Gold Sponsor":
total = 1000;
break;
case "Silver Sponsor":
total = 500;
break;
case "Longest Drive Sponsor":
total = 250;
break;
case "Closest to the Pin Sponsor":
total = 250;
break;
case "Tee Sponsor":
total = 125;
break;
default:
total = 0;
break;
}
$("#TotalDue").text('$' + total.toFixed(2));
});
// Validate the submission form
$("#registerForm").submit(function () {
'use strict';
// Store all the problems in one string, and keep track of the field they should be focused on
var i, strError = '', focusItem = null, name, name_contact, level, email, phone, address, city_state;
// First off, all of registration one is required.
name = $('#name');
name_contact = $('#name_contact');
email = $('#email');
phone = $('#phone');
address = $('#address');
city_state = $('#city_state');
level = $('#level');
// Name, email, address, etc. Focus on the highest field up in the list.
if (name.val() === '') {
strError += 'Business Name is required.\n';
if (!focusItem) { focusItem = name; }
}
if (name_contact.val() === '') {
strError += 'Contact Name is required.\n';
if (!focusItem) { focusItem = name_contact; }
}
if (level.val() === '') {
strError += 'Sponsorship level is required.\n';
if (!focusItem) { focusItem = level; }
}
if (email.val() === '') {
strError += 'Email is required.\n';
if (!focusItem) { focusItem = email; }
}
if (address.val() === '') {
strError += 'Address is required.\n';
if (!focusItem) { focusItem = address; }
}
if (city_state.val() === '') {
strError += 'City and State is required.\n';
if (!focusItem) { focusItem = city_state; }
}
if (phone.val() === '') {
strError += 'Phone is required.\n';
if (!focusItem) { focusItem = phone; }
}
if (strError === '') {
return true;
} else {
alert(strError);
// focusItem.focus();
// console.log(focusItem);
return false;
}
});<file_sep>/payment.php
<?php
$page_title = "Payment";
session_start(); // This page will use the session variables
require('assets/php/functions.php');
// This form requires some session information to be set. If it's not present, something is wrong, send them back to the homepage
if(!array_key_exists('payment_mode', $_SESSION) || $_SESSION['SECURETOKEN'] == '' || $_SESSION['SECURETOKENID'] == '') {
// A function will send this out, hopefully.
emailError("Session not set on payment.php");
header('Location:index.php?msg=paymentError');
// the header is too strong, lets do some javascript instead
// echo "<script>alert('We are sorry, your session has ended or you came to this page in error. Please try again.); history.go(-1);</script>";
}
// We're good, back to the regular setup
$payment_amount = $_SESSION['payment_amount'];
?>
<?php include('assets/php/header.php'); ?>
<h3>Enter Payment Information</h3>
<?php
$payment_amount = number_format($_SESSION['payment_amount'], 2);
$payment_mode = $_SESSION['payment_mode'];
if ($payment_mode === 'donation') {
echo '<p>Donation Amount: <span id="TotalDue">$' . $payment_amount . '</span></p>';
} elseif ($payment_mode === 'registration') {
echo '<p>Registration Amount: <span id="TotalDue">$' . $payment_amount . '</span></p>';
} elseif ($payment_mode === 'sponsor') {
echo '<p>Sponsorship Amount: <span id="TotalDue">$' . $payment_amount . '</span></p>';
}
?>
<p>Thanks, you're almost there! Transaction is now being handled by PayPal using the form below.</p>
<p style="font-size:110%; color:brown; font-weight:bold;">
Note: Please provide payment via the 'Pay with credit or debit card' option below as we are currently experiencing technical difficulties with the 'Pay with PayPal' options. The payment with credit and debit card option is securely handled through PayPal.
</p>
<iframe
id="PayPalIFrame"
src="https://payflowlink.paypal.com?MODE=LIVE&SECURETOKENID=<?php echo $_SESSION['SECURETOKENID']; ?>&SECURETOKEN=<?php echo $_SESSION['SECURETOKEN']; ?>"
scrolling="yes"
></iframe>
<?php require('assets/php/footer.php'); ?><file_sep>/donate_proc.php
<?php
require('assets/php/functions.php');
require('assets/php/variables.php');
require('assets/php/paypal.php');
session_start(); // This page will store session variables for the payment screen.
// This page will store all info for a registration
$name = getPostValue('name');
$amount = getPostValue('amount');
$address = getPostValue('address');
$city_state = getPostValue('city_state');
$email = getPostValue('email');
$phone = getPostValue('phone');
$message = getPostValue('message');
// Validate the email. If it fails, send them back with an alert
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('Please make sure your email address is valid.'); history.go(-1); </script>";
exit();
}
// Create an inserto statement. This is a two phase process, kind of strange but safer I guess
$sql = " INSERT INTO donations ( submitted_at, name, amount, address, city_state, email, phone, message ) VALUES ( NOW(), ?, ?, ?, ?, ?, ?, ? ) ; ";
$stmt = prepareStatement($mysqli, $sql);
// Bind the params
$stmt->bind_param("sdsssss", $name, $amount, $address, $city_state, $email, $phone, $message);
// Execute the above statement, and get our registration_id
executeStatement($stmt);
$donation_id = $mysqli->insert_id;
// echo "registration_id = $registration_id<br />";
// Store registration_id and payment_amount as session variables
$_SESSION['donation_id'] = $donation_id;
$_SESSION['payment_amount'] = $amount;
$_SESSION['payment_mode'] = 'donation'; // One form will have payPayl iframe, send it some info
$_SESSION['SECURETOKENID'] = '2013_' . $_SESSION['payment_mode'] . '_' . $donation_id . '_' . $serverMode;
// Now connect to paypal and request a transaction. I'm not sure if I should do it here later.
// Note, user has 30 minutes to complete the transaction
$_SESSION['SECURETOKEN'] = ppGetSecureToken($amount, $_SESSION['SECURETOKENID'], $name, $email, "Donation");
header('location: payment.php');
?> | 04de5725d29cdf6fea7e268c80a0c61c6f6c4e85 | [
"JavaScript",
"SQL",
"PHP"
] | 20 | JavaScript | ericriot/EALGT | 11413b2ccd92dfba1d25d07bc9994d20af0c74bb | bdc9fe97e622b1d5e82745f31998e9ce5d95e077 |
refs/heads/master | <repo_name>azuls123/meragua3.2<file_sep>/resources/logo/teardrop.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
function teardrop() {
console.log("GAD Cantonal de + Departamento ");
console.log(" Mera +++ de Agua ");
console.log(" +++++ Potable ");
console.log(" * +++++++ * ");
console.log(" *** +++++++++ *** ");
console.log(" ***** +++++++++++ * *** ");
console.log(" * ***** +++++++++++++ * ** ");
console.log("* ****** + +++++++++++++ '-' ");
console.log("* ****** + ++++++++++++++ ");
console.log(" ******* + ++++++++++++++ ");
console.log(" '---' + ++++++++++++++ ");
console.log(" + +++++++++++++ ");
console.log(" + +++++++++++++ ");
console.log(" +_ _+++++++++++++ ");
console.log("======- - +++++++++++++++++ - -======");
console.log("===- -===- +++++++++++++ -===- -===");
console.log("=- -====- --= +++++++ =-- -====- -=");
console.log("- -====- --==== ====-- -====- -");
console.log("=- -====- --===============-- -====- -=");
console.log("===- -===-_ _ _ _ _ _ _ _ _ _-===- -===");
console.log("======- -=====================- -======");
console.log("=========-_ _ _ _ _ _ _ _ _ _ _ _ _-=========");
console.log("=============================================");
};
// Exportacion del modulo en forma global
module.exports = teardrop;<file_sep>/controllers/backups/meter - copia.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable del esquema del modelo //
var Meter = require('../../models/meter');
var mongoosePaginate = require('mongoose-pagination');
var moment = require('moment');
var fs = require('fs');
var path = require('path');
// var User = require('../models/user');
// var Rate = require('../models/rate');
//=================Declaracion de Funciones //
// Funcion de register de datos //
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var meter = new Meter;
// variable de fecha //
var today = new Date();
var currDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
// Log de Comprobacion //
console.log("Dentro de save");
// comprobacion de los valores obligatorios enviados desde el formulario //
if (params.clave) {
// Asignacion de los parametros al modelo del Controlador //
meter.clave = params.clave;
meter.user = params.user;
meter.rate = params.rate;
meter.direccion = params.direccion;
meter.updated_at = moment().unix();
meter.edited_by = req.user.sub;
meter.image = null;
// meter.updated_at = currDate;
// comprobar valor Unico //
Meter.findOne({ clave: meter.clave }).exec((err, meteres) => {
if (err) {
// Log de Error mostrado en la Consola //
console.log(err);
// Retorno de un error 500: no se pudo realizar la accion //
return res.status(500).send({
Message: 'Error al Guardar',
message2: err
});
}
if (meteres && meteres.length >= 1) {
return res.status(500).send({
Message: 'valores duplicados',
message2: err
});
}
})
// Logs de Comprobacion //
console.log("Dentro del traspaso de Parametros");
console.log(meter);
Meter.find({ clave: meter.clave }).exec((err, meteres) => {
if (err) {
return res.status(500).send({
Message: 'Error al guardar el Medidor'
},
console.log(err))
}
if (meteres && meteres.length >= 1) {
return res.status(500).send({ Message: 'Medidor duplicado' })
} else {
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
meter.save((err, meterStored) => {
// Sentencia 'Si' para comprobar la existencia de errores //
if (err) {
// Log de Error mostrado en la Consola //
console.log(err);
// Retorno de un error 500: no se pudo realizar la accion //
return res.status(500).send({
Message: 'Error al Guardar',
message2: err
});
}
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (meterStored) {
// Se envian los datos del objeto mediante un send con el objeto mismo y un codigo 200 //
res.status(200).send({ Message: 'El medidor ' + meterStored.clave + ' ha sido Guardado Exitosamente',meter: meterStored });
}
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
else {
// Se devuelve un error 404 al cliente indicando que el objeto se encuentra vacio //
res.status(404).send({
Message: 'Objeto Vacio o Incompleto'
})
}
})
}
})
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
res.status(200).send({
Message: 'Datos faltantes o erroneos'
})
}
}
function show(req, res) {
Meter.find().populate('user rate edited_by').sort([['clave', 'asc']]).exec((err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({Medidores: resp});
});
}
function getMeter(req, res) {
Meter.findOne({_id: req.params.id}).populate('rate edited_by user').exec((err, meter) => {
if (err) return res.status(500).send({Message: 'Error interno en el servidor', Error: err});
if (!meter) return res.status(404).send({Message: 'No se encontró ningun medidor'});
return res.status(200).send({meter: meter});
})
}
function showByUser(req, res) {
var id = req.params.id;
// id = 'ObjectId("'+id+'")';
Meter.find({user: id}).populate('rate user edited_by').exec((err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({Medidores: resp});
});
}
function showByRate(req, res) {
var rate = req.params.rate;
console.log(rate);
if (!rate) showSimple(req, res); else {
Meter.find({rate: rate}, (err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({Tarifa: rate, Medidores: resp});
});
}
}
function update(req, res) {
var id = req.params.id;
var updateMeter = req.body;
updateMeter.updated_at = moment().unix();
updateMeter.edited_by = req.user.sub;
Meter.findByIdAndUpdate(id, updateMeter, { new: true }, (err, updated) => {
if (err) return res.status(500).send({ Message: 'error al ejecutar la peticion... ', Error: err });
if (!updated) return res.status(404).send({ Message: 'Error al editar el Medidor' });
return res.status(200).send({ Message: 'el medidor con clave: ' + updated.clave + ' ha sido editado', meter: updated });
});
}
function remove(req, res) {
var id = req.params.id;
Meter.findByIdAndRemove(id, (err, deleted) => {
if (err) return res.status(500).send({ Message: 'Error al ejecutar la peticion' });
if (!deleted) return res.status(404).send({ Message: 'No se pudo borrar el medidor' });
return res.status(200).send({ Message: 'El medidor con id: ' + id + ', ha sido borrado con exito!.', deleted });
})
}
function showByClave(req, res) {
var clave = req.params.clave;
Meter.findOne({clave}, (err, resp) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion... Error: ' + err});
if (!resp) return res.status(404).send({Message: 'La peticion no ha devuelto ningun valor...'});
return res.status(200).send({Medidor: resp});
})
}
function UploadImage(req,res) {
var MeterId = req.params.id;
if (req.files) {
var file_path = req.files.image.path;
var file_split = file_path.split('\\');
var file_name = file_split[2];
var ext_split = file_name.split('\.');
var file_ext = ext_split[1];
if (file_ext == 'png' || file_ext == 'jpg' || file_ext == 'jpeg' || file_ext == 'gif') {
// actualizar documento del user
Meter.findByIdAndUpdate(MeterId, { image: file_name }, { new: true }, (err, resp) => {
if (err) return res.status(500).send({ Message: 'Error en la peticion' });
if (!resp) res.status(500).send({ Message: 'No se actualizo el usuario' });
return res.status(200).send({Message: 'Croquis del Medidor Subido', medidor: resp });
});
} else {
return removeFilesOfUpload(res, file_path, 'Ups!, Algo va mal, no se ha podido subir el archivo. Extension no valida.');
}
} else return res.status(404).send({message : 'no se pudo subir la imagen'})
}
function removeFilesOfUpload(res, file_path, message) {
fs.unlink(path, (err) => {
console.log(err);
return res.status(200).send({message})
});
}
function getImage(req, res) {
var image_File = req.params.imageFile;
var path_file = './uploads/meters/' + image_File;
fs.exists(path_file, (exist) => {
if (exist) {
res.sendFile(path.resolve(path_file));
} else {
res.status(404).send({ Message: 'Ups, no encontramos la imagen dentro del servidor' });
};
});
}
module.exports = {
save,
show,
showByUser,
showByRate,
update,
remove,
showByClave,
UploadImage,
getImage,
getMeter
}<file_sep>/models/backups/publication.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var PublicationSchema = Schema({
title: String,
image: String,
document: String,
type: String,
publico: String,
place: String,
text: String,
created_at: String,
user: {
// Definicion del tipo de variable como Object Id para establecer un enlace con la tabla Principal //
type: Schema.ObjectId, ref: 'user'
}
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('Publication', PublicationSchema);<file_sep>/models/register.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var RegisterSchema = Schema({
lecturaAnterior: Number,
lectura: Number,
consumo: Number,
year: Number,
month: Number,
subtotal: Number,
updated_at: String,
excessConsumo: Number,
excessCosto: Number,
excessM3: Number,
base: Number,
cancelado: Boolean,
facturado: Boolean,
bill: {type: Schema.ObjectId, ref: 'Bill'},
meter: {
// Definicion del tipo de variable como Object Id para establecer un enlace con la tabla Principal //
type: Schema.ObjectId, ref: 'Meter'
},
extra: { type: Schema.ObjectId, ref: 'Extra' },
created_at: String,
created_by: { type: Schema.ObjectId, ref: 'user' },
updated_at: String,
updated_by: { type: Schema.ObjectId, ref: 'user' }
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('Register', RegisterSchema);<file_sep>/routes/bill.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var BillController = require('../controllers/bill');
// declaracion del uso de rutas //
var api = express.Router();
// Variable de Autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Post //
api.post('/save', md_auth.ensureAuth, BillController.save);
//========Put //
api.put('/pay/:id', md_auth.ensureAuth, BillController.pagoFactura);
//========Get //
api.get('/get-all', md_auth.ensureAuth, BillController.show);
api.get('/get-conteo', md_auth.ensureAuth, BillController.getConteo);
api.get('/show/:id', md_auth.ensureAuth, BillController.getFactura);
api.get('/show-by-user/:id', md_auth.ensureAuth, BillController.getFacturaByUser);
api.get('/show-by-register/:id', md_auth.ensureAuth, BillController.getFacturaByRegister);
module.exports = api;<file_sep>/controllers/datofactura.js
'use strict'
var DatoFactura = require('../models/datoFactura');
var moment = require('moment');
function save(req,res) {
var datoFactura = new DatoFactura;
var params = req.body;
datoFactura.tipoComp = params.tipoComp ;
datoFactura.ruc = params.ruc ;
datoFactura.tipoAmb = params.tipoAmb ;
datoFactura.serie = params.serie ;
datoFactura.tipEmi = params.tipEmi ;
datoFactura.codNum = params.codNum ;
datoFactura.nombres = params.nombres ;
datoFactura.apellidos = params.apellidos;
datoFactura.created_at = moment().unix();
datoFactura.created_by = req.user.sub;
datoFactura.save((error, response) => {
if (error) return res.status(500).send({Message: 'Error al contactar con la base de datos', Error: error});
if (!response) return resstatus(404).send({Message: 'No se ha podido guardar el dato de facturación'});
return res.status(201).send({Message: 'Exito al guardar los datos de facturación', datoFactura: response});
});
}
function show(req, res) {
DatoFactura.find().populate('created_by').exec((error, response) => {
if (error) return res.status(500).send({Message: 'Error al contactar con la base de datos', Error: error});
if (!response) return resstatus(404).send({Message: 'No se ha podido Obtener el dato de facturación'});
return res.status(200).send({Message: 'Exito al Obtener los datos de facturación', datoFactura: response});
});
}
module.exports = {
save,
show
}<file_sep>/readme.md
# webapp
# Origen: git remote add origin https://github.com/azuls123/meragua3.2.git
# Subir: git push -u origin master
# Detener Servicios: pm2 kill
# Descargar copia: git clone https://github.com/azuls123/meragua3.2.git
# arrancar Servidor: cd /meragua/meragua3.2 | pm2 start index.js
# Listo
<file_sep>/controllers/backups/importeUsuario.js
'use strict'
var ImporteUsuario = require('../models/importeUsuario');
var moment = require('moment');
function save(req, res) {
var params = req.body;
var importeUsuario = new ImporteUsuario;
if (params.medidor && params.importe) {
importeUsuario.detalle = params.detalle;
importeUsuario.medidor = params.medidor;
importeUsuario.importe = params.importe;
importeUsuario.edited_by = req.user.sub;
importeUsuario.edited_at = moment().unix();
ImporteUsuario.find({$and: [
{medidor: params.medidor},
{importe: params.importe}
]}, (err,response) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion de unicidad', Error: err});
if (response.length>=1) return res.status(403).send({Message: 'este tipo de importe ya se ha aplicado...'});
importeUsuario.save((err, responseSave) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion de Ingreso', Error: err});
if (!responseSave) return res.status(404).send({Message: 'El servidor no esta respondiendo o tardo mucho en responder..'});
return res.status(201).send({Message: 'Detalle de Importe de Usuario guardado correctamente!...', ImporteUsuario: responseSave});
})
})
}
}
function show(req,res) {
ImporteUsuario.find().exec((err, response) => {
if (err) return res.status(500).send({Message: 'error al ejectuar la peticion....', Error: err});
if (!response) return res.status(404).send({Message: 'el servidor no responde o ha tardado mucho en responder'});
return res.status(200).send({Message: 'Peticion aceptada... lista de detalles....', ImporteUsuario: response});
})
}
function deletes(req,res) {
var id = req.params.id;
ImporteUsuario.findByIdAndRemove(id, (err, response) => {
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion....', Error: err});
if (!response) return res.status(404).send({Message: 'el servidor no respondio'});
return res.status(200).send({Message: 'el detalle de importeUsuario ha sido eliminado....'});
})
}
function update(req, res) {
var id = req.params.id;
var params = req.body;
ImporteUsuario.findByIdAndUpdate(id, params, (err, response) => {
if (err) return res.status(500).send({ Message: 'Error en la peticion' });
if (!resp) res.status(500).send({ Message: 'No se recibio respuesta del servidor' });
return res.status(200).send({Message: 'Detalle del usuario y sus importes editado correctamente'})
})
}
module.exports = {
save,
update,
deletes,
show
}<file_sep>/routes/detalleFactura.js
'use strict'
var express = require('express');
var DetalleController = require('../controllers/detalleFactura');
var api = express.Router();
var md_aut = require('../middleware/authenticate');
api.post('/save', md_aut.ensureAuth, DetalleController.saveAll);
api.get('/detalle/:id', md_aut.ensureAuth, DetalleController.getDetalle);
api.get('/detalles', md_aut.ensureAuth, DetalleController.getDetalles);
module.exports = api;<file_sep>/routes/statistics.js
'use strict'
var express = require('express');
var StatisticsController = require('../controllers/statistics');
var api = express.Router();
var md_auth = require('../middleware/authenticate');
api.get('/get-statistics-user/:id', StatisticsController.getStaticsByUser);
api.get('/get-bills-numbers', StatisticsController.getBillsNumbers);
api.get('/get-cedulas', StatisticsController.getCedulas);
api.get('/get-sectores', StatisticsController.getStatisticsSectores);
api.get('/get-medidores-sector/:id', StatisticsController.getMetersSectors);
api.get('/get-statistics-global', StatisticsController.getGlobals);
api.get('/get-meters-numbers', StatisticsController.getMeterNumbers);
api.get('/get-globals', md_auth.ensureAuth, StatisticsController.getAll);
module.exports = api;<file_sep>/controllers/backups/user - copia.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable para encriptar la contraseña //
var bcrypt = require('bcrypt-nodejs');
// Variable del esquema del modelo user //
var User = require('../../models/user');
// Variable del esquema del modelo follow //
var Follow = require('../../models/follow');
// Variable de las publicaciones //
var Publications = require('../../models/publication');
// Variable token //
var jwt = require('../../services/jwt');
// Variable de Paginacion de Datos
var mongoosePaginate = require('mongoose-pagination');
// Variable para el sistema de archivos
var fs = require('fs');
// variable para rutas del sistema de archivos
var moment = require('moment');
var path = require('path');
var morgan = require('morgan');
//=================Declaracion de Funciones //
function addAdmin(req, res) {
var params = req.body;
var user = new User;
}
// >> Ingresar Usuario-Simple
function saveUser(req, res) {
// recolectar los parametros enviados
var params = req.body;
// iniciar una nueva variable con el modelo User
var user = new User;
// comprobar si hay un logeo previo
if (!req.user.sub) {
// enviar error Forbiden [prohibido] en caso de que se intente ingresar un usuario sin antes haber iniciado sesion en el sistema
return res.status(403).send({
Message: 'Solo los Empleados pueden ingresar usuarios '
});
// comprobar que el usuario que inicio sesion no se aun usuario normal [ propietario de medidor ]
} else if (req.user.sub && req.user.role_user.toLowerCase() != 'Common') {
// comprobar que existen los datos minimos para un usuario simple [ nombre, apellido, cedula {direccion opcional} ]
if (params.nombre && params.cedula && params.apellido) {
// >> aqui se rellenan las variables que por defecto se quedaran vacias pero se asigna null para evitar fallos en el sistema
user.cuenta = null;
user.contrase = null;
user.correo = null;
// << fin del relleno
// >> se ingresan o dan valor a los campos del modelo de usuario [User]
user.nombre = params.nombre;
user.apellido = params.apellido;
user.cedula = params.cedula;
// >>> Comprobacion si existe direccion ingresada
if (params.direccion) {
// >>>> Si se ingreso direccion se la asigna al modelo del usuario a ingresar
user.direccion = params.direccion;
} else {
// >>>> En caso de que no haya ingresado una direccion se le asigna por defecto como [Sin Direccion]
user.direccion = 'Sin Dirección';
}
user.sexo = params.sexo;
if (user.sexo.toLowerCase() == 'femenino' || user.sexo.toLowerCase() == 'f') {
user.image = 'avatarF.png';
} else if (user.sexo.toLowerCase() == 'masculino' || user.sexo.toLowerCase() == 'm') {
user.image = 'avatarM.png';
} else {
user.image = 'avatarI.png';
}
user.activa = true;
user.updated_at = moment().unix();
// >>> Se asigna el rol de usuario de forma automatica en Usuario //
user.role_user = 'Common';
// >>> Asignacion del usuario que inicio sesion en el campo que registra quien creo al usuario a ingresar
user.edited_by = req.user.sub;
console.log('dentro de save user');
console.log(user);
// >>> revision en el sistema si la cedula ingresada en el sistema no es repetida
User.find({
"cedula": params.cedula
}, (err, resp) => {
// >>>> revision de errores en la peticion a la base de datos
if (err) return res.status(500).send({
Message: 'Error... No se ha podido realizar la peticion',
Error: err
});
// >>>> comprobacion si existe o no la cedula, en caso de que exista se envia un estado 401 [sin autorizacion] y un mensaje de duplicado
if (resp.length >= 1) return res.status(401).send({
Message: 'Usuario Duplicado, revise la cedula'
});
else {
// >>> en caso de que la cedula ingresada se a unica se envia el usuario a la base de datos
user.save((err, userStored) => {
// >>>> Retorno de un error 500: no se pudo realizar la accion
if (err) return res.status(500).send({
Message: 'Error al ejectuar la peticion',
Error: err
});
// >>>> en caso de que el SGBD responda con el valor [usuarioStored] se envia un mensaje 201 de confirmacion de ingreso en la base de datos
if (userStored) {
res.status(200).send({
Message: 'Usuario guardado Exitosamente!!',
user: userStored
});
}
// >>>> si el SGBD no responde o responde algun valor diferente se estima que no se pudo ingresar el usuario
else {
// Se devuelve un error 404 al servidor para advertir que no se pudo registrar el usuario
res.status(404).send({
Message: 'No se pudo Registrar el usuario'
})
}
});
};
})
}
// >> Comprobacion en caso de que no llegasen los campos requeridos
} else {
// >>> se devuelve un error con estado 500 indicando que hay un error en la peticion
return res.status(500).send({
Message: 'error, debe llenar todos los campos..',
usuario: params
});
}
}
// << Ingresar Usuario-Simple
// >> Ingresar Usuario-Usuario //
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var user = new User;
// >>> comprobacion de los valores obligatorios enviados desde el formulario //
if (params.cuenta && params.contrase && params.correo && params.cedula) {
// Asignacion de los parametros al modelo del Controlador //
user.cuenta = params.cuenta;
user.contrase = params.contrase;
user.correo = params.correo;
user.nombre = params.nombre;
user.apellido = params.apellido;
user.cedula = params.cedula;
user.telefono = params.telefono;
user.direccion = params.direccion;
user.fecha_nacimiento = params.fecha_nacimiento;
user.sexo = params.sexo;
if (user.sexo.toLowerCase() == 'femenino' || user.sexo.toLowerCase() == 'f') {
user.image = 'avatarF.png';
} else if (user.sexo.toLowerCase() == 'masculino' || user.sexo.toLowerCase() == 'm') {
user.image = 'avatarM.png';
} else {
user.image = 'avatarI.png';
}
user.activa = true;
user.role_user = params.role_user;
user.edited_by = null;
// Comprobacion de datos Unicos //
User.find({
$or: [{
"correo": user.correo
},
{
"cuenta": user.cuenta
},
{
"cedula": user.cedula
}
]
}).exec((err, users) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion'
})
if (users && users.length >= 1) return res.status(500).send({
Message: 'Duplicado',
contenido: users,
cantidad: users.length,
usuario: user
});
else {
console.log(users);
// Logs de Comprobacion //
console.log("Dentro del traspaso de Parametros");
console.log(user);
// Uso de la libreria bcrypt para encriptar la contraseña //
bcrypt.hash(params.contrase, null, null, (error, hash) => {
user.contrase = hash;
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
user.save((err, userStored) => {
// Log de Error mostrado en la Consola //
console.log(err);
// Retorno de un error 500: no se pudo realizar la accion //
if (err) return res.status(500).send({
Message: 'Error al guardar el User'
});
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (userStored) {
// Se envian los datos del objeto mediante un send con el objeto mismo y un codigo 200 //
res.status(200).send({
User: userStored,
Message: 'Fin del Save'
});
}
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
else {
// Se devuelve un error 404 al cliente indicando que el objeto se encuentra vacio //
res.status(404).send({
Message: 'No se pudo Registrar el usuario'
})
}
});
})
}
});
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
res.status(500).send({
Message: 'Datos faltantes o erroneos'
})
}
}
// << Ingreso Usuario-Usuario
// >> Funcion para ingreso al sistema mediante un login //
function login(req, res) {
// >>> se reciben los datos [parametros] enviados en la peticion
var params = req.body;
// >>> se hace una busqueda en la base de datos con el nombre de la cuenta
User.findOne({
$and: [{
cuenta: params.cuenta
}]
}, (err, user) => {
// >>>> en caso de que la peticion al servidor falle se envia un estado 500 y el error
if (err) return res.status(500).send({
Message: 'error en la peticion... Error: ' + err
});
// >>>> si no se produce ningun fallo y tampoco devuelve respuesta quiere decir que no hay un usuario con esa cuenta
if (!user) return res.status(404).send({
Message: 'el usuario no existe . . . '
});
// >>>> si encuentra una cuent, pero esta no tiene el campo de activa o lo tiene desactivado se envia el mensaje de cuenta desactivada
if (user.activa = false || !user.activa) return res.status(401).send({
Message: 'la cuenta ha sido desactivada . . . '
});
// >>>> en caso de que tenga el campo activa en verdadero [true] se procede a comparar la contraseña
if (user) {
// >>>>> debido a que se utiliza una encriptacion en las contraseñas se encripta la contraseña ingresada y se compara con la almacenada
bcrypt.compare(params.contrase, user.contrase, (err, check) => {
// >>>>>> en caso de que se de un error en la peticion se envia un estado 500 y el mensaje de error
if (err) return res.status(500).send({
Message: 'error al ejecutar la peticion...',
Error: err
});
// >>>>>> en caso de que la comparacion de falsa o no de resultado se estima que la comparacion dio falso y se envia el mensaje de contraseña incorrecta
if (!check) return res.status(403).send({
Message: 'Contraseña incorrecta!...'
});
if (check) {
// >>>>>> en caso de que devuelva la comparacion en positivo se revisa si dentro de los parametros existe el campo GetToken para generar el token correspondiente
if (params.gettoken) {
// >>>>>>> se eliminan los valores del objeto usuario para evitar que si se llegase a robar el token no puedan obtener la contraseña, el estado deactiva y __v
user.contrase = undefined;
user.activa = undefined;
user.__v = undefined;
// >>>>>>> despues de borrar los campos se devuelve un estado 200
return res.status(200).send({
// >>>>>>>> se envia el objeto usuario
user: user,
// >>>>>>>> se envia el token despues de generar el token
token: jwt.createToken(user),
// >>>>>>>> se envia un mensaje de confirmacion
Message: 'Fin del Login con token'
})
// >>>>>>> en caso de que no llegase el campo GetToken
} else {
// >>>>>>> se eliminan los valores del objeto usuario para evitar que si se llegase a robar el token no puedan obtener la contraseña, el estado deactiva y __v
user.contrase = undefined;
user.activa = undefined;
user.__v = undefined;
// >>>>>>> se devuelve un estado 200 con el mensaje de confirmacion y el objeto usuario
return res.status(200).send({
Message: 'Login Realizado',
user: user
})
}
// >>>>>> en caso de que se produzca un error se envia el error y un mensaje
} else if (err) {
return res.status(500).send({
Message: 'Nombre de Cuenta o Contraseña incorrecta!',
Error: err
})
}
})
// >>>> en caso de que no haya respuesta se asume que el usuario no existe y se envia el estado 404 y un mensaje
} else {
return res.status(404).send({
Message: 'No se Encuentra al user'
})
}
})
}
// << Funcion para ingreso al sistema mediante un login
// >> Devolver Usuario [logeado o buscado]
function show(req, res) {
// >>> se establece la variable userId como el usuario logeado
var userId = req.user.sub;
// >>> en caso de que dentro de la URL llegue un id de usuario se substituye userId con el id enviado
if (req.params.id) {
userId = req.params.id;
}
// >>> se hace una busqueda de usuarios con el usuario enviado y que tenga el campo activa en verdadero [true]
User.findOne({
$and: [{
"activa": true
}, {
"_id": userId
}]
}, (err, user) => {
// >>>> en caso de error se envia un estado 500 y el mensaje de error
if (err) return res.status(500).send({
Message: 'Error en la peticion. ',
err
});
// >>>> si no hay respuesta se envia un estado 404 y el mensaje de que no existe el usuario
if (!user) return res.status(404).send({
Message: 'El usuario no existe'
});
// >>>> se hace un llamado a la funcion followThisUser [siguiendo a este usuario] para saber si el usuario logeado esta siguiendo al usuario buscado
followThisUser(req.user.sub, userId).then((value) => {
// >>>>> se devuelve un estado 200, el usuario buscado y los resultados de la funcion followThisUser
return res.status(200).send({
user,
value
});
});
});
}
// << Devolver Usuario [logeado o buscado]
// >> funcion asíncrona para comprobar los seguimientos
async function followThisUser(identity_user_id, user_id) {
// >>> busqueda de siguiendo entre el usuario logeado [user] y buscado [followed], luego se devuelve el resultado
var following = await Follow.findOne({
"user": identity_user_id,
"followed": user_id
}).exec().then((follow) => {
return follow
});
// >>> busqueda de seguidor entre el usuario logeado [followed] y buscado [user], luego se devuelve el resultado
var followed = await Follow.findOne({
"user": user_id,
"followed": identity_user_id
}).exec().then((follow) => {
return follow
});
// >>> se devuelven los valores following y followed
return await {
following,
followed
};
}
// << funcion asíncrona para comprobar los seguimientos
// >> Mostrar usuarios(paginado)
function showUsers(req, res) {
var userId = req.user.sub;
var page = 1;
if (req.params.page) {
page = req.params.page;
}
var itemsPerPage = 5;
User.find().sort('_id').paginate(page, itemsPerPage, (err, users, total) => {
if (err) return res.status(500).send({
Message: 'Error en la peticion'
});
if (!users) return res.status(404).send({
Message: 'No Hay Users'
});
followUsersIds(userId).then((value) => {
return res.status(200).send({
users,
following: value.following,
followed: value.followed,
total,
pages: Math.ceil(total / itemsPerPage)
});
});
})
}
// << Mostrar usuarios (paginado)
// >> Mostrar Usuarios [crudo]
function showRaw(req, res) {
// >>> Asignacion de variables
var userId = req.user.sub;
// >>> comprobacion de usuario logeado
if (!req.user.sub) {
// >>>> en caso de que no haya un usuario logeado se devuelve un error 401 y un mensaje
return res.status(401).send({
Message: 'No se puede Obtener Acceso a Los Registros Sin antes Ingresar al Sistema...'
})
} else {
/// >>>> en caso de que exista un usuario logeado se hace una peticion de la lista de usuarios logueados
User.find().sort([
['apellido', 'asc']
]).select({
'contrase': 0
}).exec((err, resp) => {
// >>>>> en caso de que se produzca un error se envia un estado 500 y un mensaje
if (err) return res.status(500).send({
Message: 'no se pudo obtener la lista de usuarios...',
Error: err
});
// >>>>> en caso de que no se devuelva ningun conjunto de objetos se devuelve un estado 404 y un mensaje
if (!resp) return res.status(404).send({
Message: 'no se obtuvo ningun usuario'
});
// >>>>> en caso de que exista un conjunto de objetos se hace una bisuqeda del usuario en el registro de seguidores
followUsersIds(userId).then((value) => {
// >>>>>> se devuelve un estado 200 y se envia el cojunto de usuarios y el conjunto de seguidores
return res.status(200).send({
Usuarios: resp,
following: value.following,
followed: value.followed
});
});
})
}
}
// << Mostrar Usuarios [crudo]
// >> listado de follows
async function followUsersIds(userId) {
// >>> se realiza una busqueda del usuario igual a [user] en el registro de seguidores
var following = await Follow.find({
"user": userId
}).select({
'_id': 0,
'__v': 0,
'user': 0
}).exec().then((follows) => {
var follows_clean = [];
follows.forEach((follow) => {
follows_clean.push(follow.followed);
});
// >>>> se devuelve un conjunto de objetos con los usuarios seguidos
return follows_clean;
});
// >>> se realiza una busqueda del usuario igual a [followed] en el registro de seguidores
var followed = await Follow.find({
"followed": userId
}).select({
'_id': 0,
'__v': 0,
'followed': 0
}).exec().then((follows) => {
var follows_clean = [];
follows.forEach((follow) => {
follows_clean.push(follow.user);
});
// >>>> se devuelve un conjunto de objetos con los usuarios que lo siguen
return follows_clean;
});
// >>> se devuelven los conjuntos de objetos
return {
following,
followed
};
}
// << listado de follows
// >> Obtener contadores
function showCounters(req, res) {
// >>> se asigna el id del usuario logeado a la variable [userId]
var userId = req.user.sub || '1';
// >>> se hace una comprobacion por si se envio un id de usuario dentro de la URL
if (req.params.id) {
// >>>> en caso de que exista el id enviado se lo asigna a la variable [userId]
userId = req.params.id;
};
// >>> se llama a la funcion getCountFollow enviando la variable [userId]
getCountFollow(userId).then((counters) => {
// >>>> se devuelve el valor retornado por la funcion
return res.status(200).send({
counters: counters
});
});
}
// << Obtener contadores
// >> funcion asíncrona para obtener los contadores de follow
async function getCountFollow(user_id) {
// >>> se ejecuta un conteo de registros en la tabla follow buscando el valor de [user_id] en el campo [user]
var following = await Follow.countDocuments({
"user": user_id
}).exec().then((count) => {
// >>>> se retorna el valor obtenido
return count;
});
// >>> se ejecuta un conteo de registros en la tabla follow buscando el valor de [user_id] en el campo [followed]
var followed = await Follow.countDocuments({
"followed": user_id
}).exec().then((count) => {
// >>>> se retorna el valor obtenido
return count;
});
// >>> se ejecuta un conteo de registros en la tabla Publication buscando el valor de [user_id] en el campo [user]
var publications = await Publications.countDocuments({
"user": user_id
}).exec().then((count) => {
// >>>> se retorna el valor obtenido
return count
})
// >>> se devuelven los conjutos de objetos obtenidos
return {
following,
followed,
publications
}
}
// << funcion asíncrona para obtener los contadores de follow
function updateCommons(req, res) {
var userId = req.params.id;
var update = req.body;
User.find({
'cedula': update.cedula
}, (err, resp) => {
let count = 0;
if (err) return res.status(500).send({
Message: 'Error al comprobar la Unicidad de la Cédula',
Error: err
});
if (resp.length >= 1) {
for (let index = 0; index < resp.length; index++) {
const user = resp[index];
if (user._id == userId) {
count = 1;
}
}
if (count === 0) {
return res.status(304).send({
Message: 'Cedula Duplicada'
})
} else if (count === 1) {
console.log('Cedula Unica');
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, Updated) => {
if (err) return res.status(500).send({
Message: 'Error al Ejecutar la peticion de Edicion, estado: [500 - Internal Server Error]',
Error: err
})
if (!Updated) return res.status(404).send({
Message: 'El servidor no devolvio ninguna respuesta, estado: [404 - not found]'
});
return res.status(200).send({
Message: 'El usuario: ' + update.nombre + ' ' + update.apellido + ', se edito correctamente.',
User: Updated
})
})
}
}
if (!resp || resp.length <= 0) {
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, Updated) => {
if (err) return res.status(500).send({
Message: 'Error al Ejecutar la peticion de Edicion, estado: [500 - Internal Server Error]',
Error: err
})
if (!Updated) return res.status(404).send({
Message: 'El servidor no devolvio ninguna respuesta, estado: [404 - not found]'
});
return res.status(200).send({
Message: 'El usuario: ' + update.nombre + ' ' + update.apellido + ', se editó correctamente.',
User: Updated
})
})
}
})
}
// >> Editar usuario
function update(req, res) {
// >>> asignacion de variables
var userId = req.params.id;
var update = req.body;
// >>>> se elimina el campo contraseña
delete update.contrase;
// >>> se determina si el usuario editado es el mismo que el logeado
if (userId != req.user.sub) {
// >>>> en caso de que no sean los mismos se retorna un estado 401 y el mensaje de sin acceso
return res.status(401).send({
Message: 'Sin Acceso a Edicion de Datos'
})
// >>> si el usuario a editar es el mismo que el logeado
} else {
// >>>> se envian los datos unicos a la funcion unico para comprobar que los datos ingresados no se hayan repetido en otro usuario
unico(userId, update.cuenta, update.correo, update.cedula).then((repetido) => {
// >>>>> se revisa si alguno de los valores dio como resultado alguna repeticion dentro de la base de datos
if (repetido.Correo == 0 || repetido.Cuenta == 0 || repetido.Cedula == 0) {
// >>>>>> en caso de que se hayan repetido se devuelve un estado 401 y el mensaje de datos repetidos
return res.status(401).send({
Message: 'datos repetidos....'
});
// >>>>> en caso de que todos los valores ingresados sean unicos
} else if (repetido.Correo == 1 && repetido.Cuenta == 1 && repetido.Cedula == 1) {
// >>>>>> se realiza una peticion de actualizacion de los datos del usuario
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, userUpdated) => {
// >>>>>>> en caso de que la peticion falle se devuelve un estado 500, un mensaje y el error
if (err) return res.status(500).send({
Message: 'Error en la peticion',
Error: err
});
// >>>>>>> en caso de que no se reciba respuesta se devuelve un estado 500 y el mensaje de no actualizado
if (!userUpdated) res.status(500).send({
Message: 'No se actualizo el usuario'
});
// >>>>>>> si se recibe el usuario actualizado se devuelve un estado 200 y el conjunto de objetos
return res.status(200).send({
user: userUpdated
});
})
// >>>>> en caso de que no se reciba respuesta por parte del SGBD
} else if (!repetido || repetido == null) {
// >>>>>> se envia un estado 500 y el mensaje de que no hubo respuesta
return res.status(500).send({
Message: 'no se obtuvo respuesta de la comprobacion de datos repetidos . . . . . ' + repetido
})
}
})
}
}
// << Editar usuario
// >> funcion asíncrona para comprobar la unicidad del usuario a editar
async function unico(id, cuenta, correo, cedula) {
// >>> se ejecuta una busqueda con el campo correo para comprobar unicidad
var Correo = await User.find({
'correo': correo
}).exec().then((resp) => {
// >>>> se inicializa el conteo de repeticiones en 0
var count = 0;
// >>>> en caso de que el SGBD responda
if (resp) {
// >>>>> si la respuesta contiene menos de 0 objetos
if (resp.length <= 0) {
// >>>>>> se asigna el valor de 1 a la variable de conteo
return count = 1;
// >>>>> en caso de que la respuesta contenga un conjunto objetos de 1 o mas
} else {
// >>>>>> se revisa en cada elemento del conjunto de objetos
resp.forEach(element => {
// >>>>>>> se verifica si el elemento en el que se encuentra es el mismo del usuario que se va a editar
if (element.id == id) {
// >>>>>>>> en caso de que sea el mismo usuario se aumenta en 1 el valor de count
return count = count + 1;
// >>>>>> en caso de que no concuerden los usuarios
} else {
// >>>>>>>> se devuelve el valor actual de count
return count;
}
});
}
};
// >>>> una vez finaliza todas las comparaciones se devuelve el valor actual de count
return count;
});
var Cedula = await User.find({
'cedula': cedula
}).exec().then((resp) => {
var count = 0;
if (resp) {
console.log('entrando en comprobacion de cedula...' + resp.cuenta);
if (resp.length <= 0) {
console.log('solo un registro... o ninguno?');
return count = 1;
} else {
resp.forEach(element => {
if (element.id == id) {
return count = count + 1;
} else {
console.log('cedula Repetida');
return count;
}
});
}
};
return count;
});
var Cuenta = await User.find({
'cuenta': cuenta
}).exec().then((resp) => {
var count = 0;
if (resp) {
console.log('entrando en comprobacion de cuenta...' + resp);
if (resp.length <= 0) {
console.log('solo un registro... o ninguno?');
return Cuenta = 1;
} else {
resp.forEach(element => {
if (element.id == id) {
return count = count + 1;
} else {
console.log('cuenta Repetida');
return count;
}
});
}
};
return count;
});
return {
Correo,
Cuenta,
Cedula
};
}
// subir archivos de imagen
function UploadImageUser(req, res) {
var UserId = req.params.id;
try {
if (req.files) {
var file_path = req.files.image.path;
var file_split = file_path.split('\\');
var file_name = file_split[2];
var ext_split = file_name.split('\.');
var file_ext = ext_split[1];
if (UserId != req.user.sub) {
return removeFilesOfUpload(res, file_path, 'No tienes permiso para editar la imagen de este User');
}
if (file_ext == 'png' || file_ext == 'jpg' || file_ext == 'jpeg' || file_ext == 'gif') {
// actualizar documento del user
User.findByIdAndUpdate(UserId, {
image: file_name
}, {
new: true
}, (err, userUpdated) => {
if (err) return res.status(500).send({
Message: 'Error en la peticion'
});
if (!userUpdated) res.status(500).send({
Message: 'No se actualizo el usuario'
});
return res.status(200).send({
user: userUpdated
});
});
} else {
return removeFilesOfUpload(res, file_path, 'Ups!, Algo va mal, no se ha podido subir el archivo. Extension no valida.');
}
} else {
return res.status(404).send({
Message: 'No se encuentra una imagen'
});
}
} catch (error) {
console.log(error);
}
}
// funcion interna que remueve los archivos del servidor cuando exista algun error
function removeFilesOfUpload(res, file_path, message) {
fs.unlink(file_path, (err) => {
console.log(err);
return res.status(200).send({
message
});
});
}
function getImageFile(req, res) {
var image_File = req.params.imageFile;
var path_file = './uploads/users/' + image_File;
fs.exists(path_file, (exist) => {
if (exist) {
res.sendFile(path.resolve(path_file));
} else {
res.status(200).send({
Message: 'Ups, no encontramos la imagen dentro del servidor'
});
};
});
}
function showByData(req, res) {
var Show = [];
var params = req.body;
if (params.nombre) Show = {
nombre: params.nombre
};
if (params.apellido) Show = {
apellido: params.apellido
};
if (params.cedula) Show = {
cedula: params.cedula
};
User.find(Show, (err, resp) => {
console.log(Show);
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion... Error: ' + err
});
if (!resp) return res.status(404).send({
Message: 'La peticion no ha devuelto ningun valor...'
});
return res.status(200).send({
resp
});
})
}
function removeCompletly(req, res) {
var id = req.params.id;
User.findByIdAndRemove(id, (err, resp) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion . . .' + err
});
if (!resp) return res.status(404).send({
Message: 'la peticion no ha devuelto ningun valor'
});
return res.status(200).send({
Message: 'El usuario ha sido borrado con exito'
});
});
}
function remove(req, res) {
var id = req.params.id;
var activa = false;
User.findByIdAndUpdate(id, activa, (err, resp) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion'
});
if (!resp) return res.status(404).send({
Message: 'La peticion no ha devuelto ningun valor'
});
return res.status(200).send({
Message: 'El usuario ha sido borrado con exito . . . '
});
})
}
module.exports = {
save,
login,
show,
showUsers,
showCounters,
update,
UploadImageUser,
getImageFile,
showByData,
remove,
removeCompletly,
showRaw,
saveUser,
updateCommons
}<file_sep>/controllers/limits.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable del esquema del modelo //
var moment = require('moment');
var Limits = require('../models/limits');
//=================Declaracion de Funciones //
// Funcion de register de datos //
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var limits = new Limits;
// variable de fecha //
var today = new Date();
var currDate = today.getFullYear() + ' - ' + (today.getMonth() + 1) + ' - ' + today.getDate();
// Log de Comprobacion //
console.log("Dentro de save");
// Asignacion de los parametros al modelo del Controlador //
limits.limit_to = params.limit_to;
limits.limit_from = params.limit_from;
limits.cost = params.cost;
limits.percent_cost = params.percent_cost;
limits.created_by = req.user.sub;
limits.created_at = moment().unix();
limits.rate_id = req.params.rate;
// comprobacion de los valores obligatorios enviados desde el formulario //
if (limits.rate_id) {
// Logs de Comprobacion //
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
limits.save((err, limitsStored) => {
// Sentencia 'Si' para comprobar la existencia de errores //
if (err) return res.status(500).send({ Message: 'error al enviar la peticion' });
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (!limitsStored) return res.status(404).send({ Message: 'limite vacio' });
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
return res.status(200).send({ Message: 'limite agregado correctamente', limitsStored });
})
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
res.status(200).send({
Message: 'Datos faltantes o erroneos'
})
}
}
function show(req, res){
var rate = req.params.rate;
Limits.find({rate_id: rate}, (err, resp) =>{
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion al servidor', Error: err})
if (!resp) return res.status(404).send({Message: 'No se encotraron los limites de la tarifa'})
return res.status(200).send({Message: 'Peticion correcta...', Limits: resp});
})
}
function showAll(req, res){
Limits.find().exec((err, resp) =>{
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion al servidor', Error: err})
if (!resp) return res.status(404).send({Message: 'No se encotraron los limites de la tarifa'})
return res.status(200).send({Message: 'Peticion correcta...', Limits: resp})
})
}
// Funcion de Obtencion de Datos //
function shows(req, res) {
var page = 1;
var itemsPerPage = 8;
if (req.params.page) page = req.params.page;
var params = req.body;
if (params.items) itemsPerPage = parseInt(params.items);
Limits.find().paginate(page, itemsPerPage, (err, get, total) => {
if (err) return res.status(500).send({ Message: 'error al procesar la peticion' });
if (!get) return res.status(404).send({ Message: 'no se pudo procesar la peticion, vacia' });
return res.status(200).send({
Total: total,
Pages: Math.ceil(total / itemsPerPage),
Limits: get
})
});
}
// Funcion Editar //
function update(req, res) {
var id = req.params.id;
var updateLimits = req.body;
Limits.findByIdAndUpdate(id, updateLimits, { new: true }, (err, limitsUpdated) => {
if (err) return res.status(500).send({ Message: 'error al ejecutar la peticion... ', Error: err });
if (!limitsUpdated) return res.status(404).send({ Message: 'Error al editar el Limite' });
return res.status(200).send({ Message: 'el limite id: ' + id + ' ha sido editado', limitsUpdated });
});
}
// Funcion Borrar //
function remove(req, res) {
var id = req.params.id;
Limits.find({rate_id: id}, (err, resp) =>{
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion al servidor', Error: err})
if (!resp) return res.status(404).send({Message: 'No se encotraron los limites de la tarifa'})
if (resp) {
removing(resp, resp.length).then((check)=> {
if (check==true) return res.status(200).send({Message: 'Exito al borrar los limites...'});
else return res.status(500).send({Message: 'error en el proceso de borrado de datos' +check , Error: check})
})
}
})
}
function removeLimits(limits, length) {
console.log('Limites: ',length);
for (const limite of limits) {
var id = limite._id;
Limits.findByIdAndDelete(id, (err, deleted) => {
if (err) console.log(err);
if (deleted) console.log(deleted);
})
}
return true;
}
async function removing(limits, length) {
var check = await removeLimits(limits, length)
return check
}
module.exports = {
save,
show,
update,
remove,
showAll
}<file_sep>/routes/backups/importeUsuario.js
'use strict'
var express = require('express');
var ImporteUsuarioController = require('../controllers/importeUsuario');
var api = express.Router();
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Get //
api.get('/show', md_auth.ensureAuth, ImporteUsuarioController.show);
//========Put //
api.put('/update/:id', md_auth.ensureAuth, ImporteUsuarioController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, ImporteUsuarioController.deletes);
//========Post //
api.post('/save',md_auth.ensureAuth, ImporteUsuarioController.save);
module.exports = api;<file_sep>/routes/extra.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var ExtraController = require('../controllers/extra');
// declaracion del uso de rutas //
var api = express.Router();
// importacion ed middleware de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Post //
api.post('/save', md_auth.ensureAuth, ExtraController.save);
//========Get //
api.get('/show',md_auth.ensureAuth, ExtraController.show);
//========Put //
api.put('/update/:id',md_auth.ensureAuth, ExtraController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, ExtraController.remove);
module.exports = api;<file_sep>/models/config.js
'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ConfigSchema = Schema({
logo: String,
updated_at: String,
created_at: String,
updated_by: {type: Schema.ObjectId, ref: 'user'},
created_by: {type: Schema.ObjectId, ref: 'user'}
})<file_sep>/routes/register.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var RegisterController = require('../controllers/register');
// declaracion del uso de rutas //
var api = express.Router();
// importacion ed middleware de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Post //
api.post('/save', md_auth.ensureAuth, RegisterController.save);
//========Get //
api.get('/show/:id',md_auth.ensureAuth, RegisterController.show);
api.get('/get-one/:id',md_auth.ensureAuth, RegisterController.getOne);
api.get('/show-all',md_auth.ensureAuth, RegisterController.showAll);
api.get('/showbymonth/:mes?',md_auth.ensureAuth, RegisterController.showByMonth);
api.get('/showbymeter/:meter?',md_auth.ensureAuth, RegisterController.showByMeter);
api.get('/showbymeter-for-consulting/:meter?', RegisterController.showByMeter);
//========Put //
api.put('/update/:id',md_auth.ensureAuth, RegisterController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, RegisterController.remove);
module.exports = api;<file_sep>/index.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable mongoose para la conexion con MongoDB //
var mongoose = require('mongoose');
// Variable urlmongo para indicar la direccion del servidor //
var urlmongo = 'mongodb://localhost:27017/watercontrol';
// Variable importada de app.js //
var app = require('./app');
// Variables de logos //
var tearDrop = require('./resources/logo/teardrop');
// Variable del puerto para montar el servidor BackEnd //
var port = process.env.PORT || 3800;
// variable de fecha //
var today = new Date();
var currTime = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var currDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
//=================Instrucciones
// Promesa global de la variable mongoose para habilitarla en toda la API //
mongoose.Promise = global.Promise;
//=================Conexion de mongoDB mediante mongoose
// Ejemplo de conexion correcta: mongoose.connect('mongodb://user:password@sample.com:port/dbname', { useNewUrlParser: true }) //
mongoose.connect(
// Declaracion de la direccion URL de la Base de Datos //
urlmongo,
// Sentencia para habilitar la compatibilidad entre mongo y las versiones nuevas y viejas de mongoose //
{
useNewUrlParser: true
}
)
// Callback "Then" confirmar la realizacion de la Instruccion Connect
.then(() => {
// Mensaje en consola de Confirmacion de Coneccion Exitosa
console.log("Conexion Lista!");
console.log("Hoy: " + today + ". Fecha Actual: " + currDate + ". Hora Actual: " + currTime);
//=================Creacion del servidor //
// Llamado a la funcion listen para establecer un puerto de escucha para el servidor //
// Callback seguido de la funcion para mostrar en consola el correcto funcionamiento del servidor //
app.listen(port, () => {
console.log("Servidor Listo!");
// Logo del BackEnd
tearDrop();
// Mensajes de confirmacion del funcionamiento del servidor
console.log("URL del Servidor: http://localhost:" + port + "/");
});
})
// Callback "Catch" para iniciar instrucciones en caso del fallo en la instruccion Connect
.catch(
// Despliegue del error detallado en consola
err => console.log(err)
);
app.set('port', process.env.PORT || 3000);<file_sep>/models/backups/descuentoUsuario.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var DescuentoUsuarioSchema = Schema({
descripcion: String,
descuento: { type: Schema.ObjectId, ref: 'Descuento' },
user: { type: Schema.ObjectId, ref: 'User' },
updated_at: String,
registered_by: { type: Schema.ObjectId, ref: 'User' }
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('DescuentoUsuario', DescuentoUsuarioSchema);<file_sep>/controllers/extra.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de extras //
var Extra = require('../models/extra');
var moment = require('moment');
//=================Declaracion de Funciones //
// Funcion de registro de datos //
function save(req, res){
var params = req.body;
var extra = new Extra;
if (params.date && params.rmuv) {
extra.date = params.date;
extra.rmuv = params.rmuv;
extra.created_at = moment().unix();
extra.created_by = req.user.sub;
extra.save((err, resp) => {
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion...', Error: err});
if (!resp) return res.status(404).send({Message: 'la peticion no devolvio ningun valor'});
return res.status(200).send({Message: 'Se han guardado los Valores'});
})
} else {
return res.status(404).send({Message: 'datos incompletos', Extra: params});
}
}
function update(req, res) {
var id = req.params.id;
var params = req.body;
params.updated_at = moment().unix();
params.updated_by = req.user.sub;
Extra.findByIdAndUpdate(id, params, {new : true}, (err, resp) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion... Error: ' + err});
if (!resp) return res.status(404).send({Message: 'La peticion no ha devuelto ninguna respuesta...'});
return res.status(200).send({Message: 'se han editado los datos correctamente', resp});
})
}
function show(req, res){
Extra.find().sort([['date', 'desc']]).populate('created_by updated_by').exec((err, response) => {
if (err) return res.status(500).send({Message: 'Error al procesar la peticion en el servidor', Error: err});
if (!response) return res.status(404).send({Message: 'La peticion no retorno ninguna respuesta..'});
return res.status(200).send({Message: 'Se han Obetnido los valores de RMUV y Mora Registrados!!...', extra: response});
})
}
function showPaginate(req, res) {
var page = 1;
var itemsPerPage = 5;
if (req.params.page) page = req.params.page;
if (req.body.items) itemsPerPage = req.body.items;
Extra.find().paginate(page, itemsPerPage, (err, resp) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion... Error: ' + err});
if (!resp) return res.status(404).send({Message: 'La peticion no ha devuelto ningun valor...'});
return res.status(200).send({Extras: resp});
})
}
function remove(req,res) {
var id = req.params.id;
Extra.findByIdAndRemove(id, (err, resp) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion.. Error: ' + err});
if (!resp) return res.status(404).send({Message: 'la peticion no ha devuelto ninguna respuesta...'});
return res.status(200).send({Message: 'los valores de iva: ' + resp.iva + ', y rmuv: ' + resp.rmuv + ', se han borrado...'});
})
}
module.exports = {
save,
show,
update,
remove
}<file_sep>/controllers/errorCatcher.js
'use strict'
var ErrorCatcher = require('../models/errorCatcher');
var moment = require('moment');
function saveError(req, res) {
var params = req.body;
let error = new ErrorCatcher;
error.description = params.description;
error.message = params.message;
error.action = params.action;
error.code = params.code + '-' + moment().unix();
error.title = params.title;
error.zone = params.zone;
error.table = params.table;
error.updated_at = moment().unix();
error.repaired = false;
error.registered_by = req.user.sub;
error.solved_by = null;
error.save((err, response) => {
if (err) return res.status(500).send({Message: 'vaya, esto es vergonzoso... se ha producido un error registrando el error...', Error: err, error});
if (!response) return res.staus(404).send({Message: 'ok, esto no deberia pasar..... /.\\ ..... no se ha obtenido una respuesta en el servidor...'});
if (response) return res.status(200).send({Message: 'Oh No!, :( Se ha Producido Un Error... Pero lo Hemos almacenado en el Servidor para Solucionarlo!!, Comunicate con uno de los administradores e indicale éste Código: ' + error.code})
})
}
function workOnIt(req, res) {
var id = req.params.id;
let params;
params.solved_by = req.user.sub;
ErrorCatcher.findByIdAndUpdate(id, params, {new:true}, (err, response) =>{
if (err) return res.status(500).send({Message: 'Ok, esto no deberia pasar..... pero no se pudo registrar la correcion del error :c...'});
if (!response) return res.status(404).send({Message: 'Hmmm... Que raro!, El servidor no dice nada!!'});
return res.status(200).send({Message: 'Listo!.. Ya estas a cargo del error: ' + response.code });
})
}
function solvedError(req, res){
var id = req.params.id;
let params;
params.description = 'Internal Server Error';
params.repaired = true;
params.updated_at = moment().unix();
params.solved_by = req.user.sub;
ErrorCatcher.findByIdAndUpdate(id, params, {new:true}, (err, response) =>{
if (err) return res.status(500).send({Message: 'Ok, esto no deberia pasar..... pero no se pudo registrar la correcion del error :c...'});
if (!response) return res.status(404).send({Message: 'Hmmm... Que raro!, El servidor no dice nada!!'});
return res.status(200).send({Message: 'Listo!... Se registró la Solución de este Error :D'});
})
}
function getErrors(req,res) {
ErrorCatcher.find().sort([['update_at', 'asc']]).exec((err, response) => {
if (err) return res.status(500).send({Message: 'Ups!, Esto no deberia estar pasando!, el servidor devolvio un error :c.. ' , Error: err});
if (!response) return res.status(404).send({Message: 'Todo bien.... o todo mal??!!.... bueno no se, el punto es que no hay registro de errores... espero que no exista ninguno n.n'});
if (response) return res.status(200).send({Message: 'Diablos, me gustaria no tener que decir esto pero bueno... Aquí estan los errores u.u : ', Error: response});
})
}
module.exports = {
saveError,
workOnIt,
solvedError,
getErrors
}<file_sep>/controllers/register.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de registro //
var Register = require('../models/register');
// Variable de medidor //
var Meter = require('../models/meter');
// Variable de tarifa //
var Rate = require('../models/rate');
// Variable de limites //
var Limits = require('../models/limits');
// Variable de Extras //
var Extra = require('../models/extra');
// Variable de Tiempo de registro //
var moment = require('moment');
var morgan = require('morgan');
var register = new Register;
//=================Declaracion de Funciones //
// Funcion de registro de datos //
function saveCompletly(req, res) {
var params = req.body;
var lectura_anterior = 0;
if (params.anio && params.mes) {
params.date = params.anio + '.' + params.mes;
var premonth = params.mes - 1;
if (premonth<=9) premonth = '0'+premonth;
var date_anterior = (params.anio + '.' + premonth);
console.log('hay fecha....' + params.date);
}
Register.find({$and: [
{date: params.date},
{meter: params.meter}
]}, (err, resp) => {
if (err) return res.status(500).send({Message: 'No se pudo ejecutar la peticion... Error: ' + err});
if (resp.length >=1) return res.status(200).send({Message: 'Registro Duplicado,,,,'});
console.log(params.date + params.meter + ' ... ' + resp);
if (resp.length=0 || !resp.length) {
register.lectura = params.lectura;
register.lecturaAnterior = params.lecturaAnterior;
register.facturado = false;
register.date = params.date;
register.cancelado = false;
register.meter = params.meter;
register.extra = params.extra;
if (params.mes > 12) return res.status(500).send({Message: 'La fecha ingresada es incorrecta, recuerde usar el formato de numero 1-12....'})
if (params.lectura && params.date) {
Register.find({meter: params.meter}, (errRegister, varRegister) =>{
register.lectura = params.lectura;
register.date = params.date;
register.cancelado = false;
register.meter = params.meter;
register.extra = params.extra;
if (errRegister) return res.status(500).send({Message: 'Error al ejecutar la peticion . . . . Error: ' + errRegister});
if (varRegister.length == 0) {
register.consumo = 0;
Meter.findById(params.meter, (errMeter, varMeter) => {
if (errMeter) return res.status(500).send({Message: 'no se ha podido ejecutar la peticion.... Error: ' + errMeter});
Rate.findById(varMeter.rate, (errRate, varRate) => {
if (errRate) return res.status(500).send({Message: 'no se ha podido ejectuar la peticion.... Error: ' + errRate});
if (!varRate) return res.status(404).send({Message: 'No se ha podido obtener la tarifa del medidor....'+varMeter.rate});
register.subtotal = varRate.base;
register.save((err, resp) => {
if (err) return res.status(500).send({Message: 'Error al Ejecutar la peticion... Error: '+err});
if (!resp) return res.status(404).send({Message: 'No se pudo guardar el registro....'});
return res.status(200).send({Message: 'hasta aqui todo bien.... primer registro... Clave: ' + varMeter.clave, register});
})
})
})
} else if (varRegister.length >= 1) {
console.log('{meter: ' + params.meter + '}, \n{date: ' + date_anterior + '}');
Register.findOne({$and: [
{meter: params.meter},
{date: date_anterior}
]}, (errReg, varReg)=> {
if (errReg) return res.status(500).send({Message: 'Error al ejecutar la peticion'});
if (!varReg) return res.status(404).send({Message: 'no se encontro el registro anterior, por favor verifique la fecha...'});
register.consumo = register.lectura - varReg.lectura;
if (register.consumo >=0){
Meter.findById(params.meter, (errMeter, varMeter) => {
if (errMeter) return res.status(500).send({Message: 'no se ha podido ejecutar la peticion.... Error: ' + errMeter});
Rate.findById(varMeter.rate, (errRate, varRate) => {
if (errRate) return res.status(500).send({Message: 'no se ha podido ejectuar la peticion.... Error: ' + errRate});
if (!varRate) return res.status(404).send({Message: 'No se ha podido obtener la tarifa del medidor....'+varMeter.rate});
Limits.find({rate_id: varRate.id}, (errLimits, varLimits) => {
if (errLimits) return res.status(500).send({Message: 'Error al ejecutar la peticion . . . . . Error: ' + errLimits});
if (!varLimits) return res.status(404).send({Message: 'No existen limites para la tarifa actual!'});
varLimits.forEach(element => {
if (!element.limit_to | element.limit_to == undefined ) element.limit_to = 999999999;
if ( parseFloat(register.consumo) >= parseInt(element.limit_from) & parseInt(register.consumo) <= parseInt(element.limit_to) ) {
console.log(element);
Extra.findById(params.extra, (err, varExtra)=>{
console.log(varExtra.rmuv);
var exceso = parseFloat(parseFloat(varExtra.rmuv)*(parseFloat(element.excess)/100));
var consumos = parseFloat(register.consumo);
console.log('base: ' + varRate.base + '\nexceso: ' + exceso + '\nconsumo: ' +consumos);
register.subtotal = parseFloat(parseFloat(varRate.base) + (parseFloat(consumos) * parseFloat(exceso)));
console.log('subtotal: '+ register.subtotal);
register.registered_by = req.user.sub;
register.updated_at = moment().unix();
register.save((err, resp) => {
if (err) return res.status(500).send({Message: 'Error al guardar el registro.... Error: '+ err});
if (!resp) return res.status(404).send({Message: 'No se pudo guardar el registro...'});
if (resp) return res.status(200).send({Message: 'hasta aqui todo bien.... agregar registro', register})
})
})
}
});
})
})
})
} else {
return res.status(500).send({Message: 'La lectura registrada es negativa por favor, revise el medidor y el contador'});
}
})
} else {
return res.status(200).send({Message: 'error, no entra en el if..........' + varRegister.length})
}
})
} else {
console.log(params.date);
return res.status(500).send({Message: 'No se ha ingresado fecha.... o lectura'});
}
}
})
}
function save(req, res) {
var params = req.body;
var register = new Register;
if (!req.user.sub) {
// enviar error Forbiden [prohibido] en caso de que se intente ingresar un usuario sin antes haber iniciado sesion en el sistema
return res.status(403).send({Message: 'Solo los Empleados pueden ingresar usuarios '});
// comprobar que el usuario que inicio sesion no se aun usuario normal [ propietario de medidor ]
}
register._id = undefined;
register.lecturaAnterior = params.lecturaAnterior;
register.lectura = params.lectura;
register.consumo = params.consumo;
register.year = params.year;
register.month = params.month;
register.subtotal = params.subtotal;
register.cancelado = false;
register.facturado = false;
register.excessConsumo = params.excessConsumo;
register.excessCosto = params.excessCosto;
register.excessM3 = params.excessM3;
register.base = params.base;
register.created_at = moment().unix();
register.created_by = req.user.sub;
register.meter = params.meter;
register.extra = params.extra;
console.log(register);
// return res.status(300).send({Message: 'Peticion de Guardado....', Register: register});
register.save((err, resp) => {
if (err) return res.status(500).send({Message: 'Error al guardar el registro.... ', Error: err});
if (!resp) return res.status(404).send({Message: 'No se pudo guardar el registro...'});
if (resp) return res.status(200).send({Message: 'Registro agregado con exito', register: register})
})
}
function getOne(req, res) {
var id = req.params.id;
Register.findById(id).populate(
{
path: 'extra meter',
populate: {
path: 'user rate sector',
populate: 'created_by'
},
}
// 'meter extra registered_by user'
).exec((error, response) => {
if (error) return res.status(500).send({Message: 'Error al Obtener el registro.... ', Error: error});
if (!response) return res.status(404).send({Message: 'No se pudo guardar el registro...'});
return res.status(200).send({Message: 'Registro Cargado!.', Register: response});
})
}
function getLast(req, res) {
var id = req.params.id;
Register.find({meter: id}).sort([['lectura', 'asc']]).select({'_id': 0}).exec((error, response)=> {
if (error) return res.status(500).send({Message: 'Error al Obtener el registro.... ', Error: error});
if (!response) return res.status(404).send({Message: 'No se pudo guardar el registro...'});
return res.status(200).send({Message: 'Registro Anterior Cargado!.', Register: response});
})
}
function show(req, res) {
Register.find({meter: req.params.id}).sort([['updated_at', 'desc']]).select({'__v': 0}).exec((err, registers) => {
if (err) return res.status(500).send({Message: 'Hubo un Error al procesar la peticion', Error: err});
if (!registers) return res.status(404).send({Message: 'No existen registros en el servidor, prueba con otro medidor...'})
if (registers.length >= 1 ) return res.status(200).send({Message: 'Peticion Exitosa! se encontraron ' + (registers.length) + ' registros...', registers: registers});
if (registers.length == 0 ) return res.status(200).send({Message: 'No existen registros de este medidor.' + req.params.id});
})
}
function showAll(req, res) {
Register.find().select({ '_id': 0, '__v': 0}).exec((err, registers) => {
if (err) return res.status(500).send({Message: 'Hubo un Error al procesar la peticion', Error: err});
if (!registers) return res.status(404).send({Message: 'No existen registros en el servidor, prueba con otro medidor...'})
return res.status(200).send({Message: 'Peticion Exitosa!', registers: registers});
})
}
function showPaginate(req, res) {
var page = 1;
var itemsPerPage = 4;
var params = req.body;
var Registro = Register.find();
if (req.params.page) page = req.params.page;
if (params.items) itemsPerPage = parseInt(params.items);
if (params.cancelado == "true") Registro = Register.find({cancelado: true});
if (params.cancelado == "false") Registro = Register.find({cancelado: false});
Registro.paginate(page, itemsPerPage, (err, get, total) => {
if (err) return res.status(500).send({ Message: 'error al procesar la peticion' });
if (!get) return res.status(404).send({ Message: 'no se pudo procesar la peticion, vacia' });
return res.status(200).send({
Total: total,
Pages: Math.ceil(total / itemsPerPage),
Register: get
})
});
}
function showSimple(req,res) {
var Registro = Register.find();
if (req.body.cancelado = true) Registro = Register.find({cancelado});
Registro.exec((err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({RegistroTotal: resp});
});
}
function showByMonth(req,res) {
var mes = req.params.mes;
if (!mes) showSimple(req, res); else {
Register.find({mes: mes}, (err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({Mes: mes, Registros: resp});
})
}
}
function showByMeter(req,res) {
var meter = req.params.meter;
if (!meter) showSimple(req, res); else {
Register.find({meter: meter}).populate('updated_by created_by meter extra bill').exec((err, resp) => {
if (err) return res.status(500).send({Message: 'error al procesar la peticion, Error:' + err});
if (!resp) return res.status(404).send({Message: 'no se pudo buscar'});
return res.status(200).send({Medidor: meter, Registros: resp});
})
}
}
function update (req, res) {
var id = req.params.id;
var updateRegister = req.body;
updateRegister.updated_by = req.user.sub;
updateRegister.updated_at = moment().unix();
Register.findByIdAndUpdate(id, updateRegister, { new: true }, (err, updated) => {
if (err) return res.status(500).send({ Message: 'error al ejecutar la peticion... ', Error: err });
if (!updated) return res.status(404).send({ Message: 'Error al editar el registro' });
return res.status(200).send({ Message: 'el medidor: ' + updated.meter + ' ha sido editado', updated });
});
}
function remove (req, res) {
var id = req.params.id;
Register.findByIdAndRemove(id, (err, deleted) => {
if (err) return res.status(500).send({ Message: 'Error al ejecutar la peticion' });
if (!deleted) return res.status(404).send({ Message: 'No se pudo borrar el registro' });
return res.status(200).send({ Message: 'El registro con id: ' + id + ', ha sido borrado con exito!.', deleted });
})
}
module.exports = {
save,
show,
showByMonth,
showByMeter,
update,
remove,
showAll,
getOne
}<file_sep>/models/limits.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var LimitsSchema = Schema({
limit_from: Number,
limit_to: Number,
cost: Number,
percent_cost: Boolean,
updated_at: String,
updated_by: {type: Schema.ObjectId, ref: 'user'},
created_at: String,
created_by: {type: Schema.ObjectId, ref: 'user'},
rate_id: {
// Definicion del tipo de variable como Object Id para establecer un enlace con la tabla Principal //
type: Schema.ObjectId, ref: 'Rate'
}
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('Limit', LimitsSchema);<file_sep>/routes/importe.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var ImporteController = require('../controllers/importe');
// declaracion del uso de rutas //
var api = express.Router();
// controlador de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Gets //
api.get('/show', md_auth.ensureAuth, ImporteController.show );
//========Post //
api.post('/save', md_auth.ensureAuth, ImporteController.save);
//========Put //
api.put('/update/:id', md_auth.ensureAuth, ImporteController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, ImporteController.remove);
module.exports = api;<file_sep>/controllers/sector.js
'use strict'
var Sector = require('../models/sector');
var moment = require('moment');
function save(req, res) {
var params = req.body;
var sector = new Sector;
if (params.nombre) {
sector.nombre = params.nombre;
sector.codigo = params.codigo;
sector.activa = params.activa;
sector.referencia = params.referencia;
sector.created_at = moment().unix();
sector.created_by = req.user.sub;
Sector.find({
$or: [{
"nombre": sector.nombre
},
{
"codigo": sector.codigo
},
{
"referencia": sector.referencia
}
]
}).exec((err, response) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion en el servidor!.', Error: err});
if (response && response.length >=1) return res.status(400).send({Message: 'Datos Duplicados!!!...', sectores: response});
else {
sector.save((errSave, responseSave) => {
if (errSave) return res.status(500).send({Message: 'Error al ejecutar la peticion en el servidor!.', Error: err});
if (!responseSave) return res.status(404).send({Message: 'No se pudo guardar el sector...'});
sector = new Sector;
return res.status(201).send({Message: 'El sector se ha guardado Correctamente!...', sector: responseSave});
})
}
return
})
}
}
function updates(req, res) {
var id = req.params.id;
var params = req.body;
params.updated_at = moment().unix();
params.updated_by = req.user.sub;
Sector.findByIdAndUpdate(id, params, (err, response) => {
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion. . .', Error: err});
if (!response) return res.status(404).send({Message: 'error al actualizar el sector'});
else return res.status(200).send({Message: 'Exito al Actualizar el Sector!!...', sector: params});
})
}
function gets(req, res) {
Sector.find().populate('created_by updated_by').exec((err, response) => {
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion. . .', Error: err});
if (!response) return res.status(404).send({Message: 'error al Devolver la lista de Sectores'});
else return res.status(200).send({Message: 'Exito al Devolver la Lista de Sectores!!...', sectores: response});
})
}
function get(req, res) {
var id = req.params.id;
Sector.findById(id, (err, resp)=> {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion en el servidor!...', Error :err});
if (!resp) return res.status(404).send({Message: 'no se encuentra el sector!!'});
return res.status(200).send({Message: 'Sector Encontrado!...', Sector: resp})
})
}
module.exports = {
save,
updates,
gets,
get
}<file_sep>/models/facturaNumero.js
'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FacturaNumSchema = Schema({
num_min: Number,
num_max: Number,
caduca: String,
estado: Boolean,
codigoTalonario: String,
updated_at: String,
created_at: String,
updated_by: {type: Schema.ObjectId, ref: 'user'},
created_by: {type: Schema.ObjectId, ref: 'user'}
})
module.exports = mongoose.model('FacturaNumeros', FacturaNumSchema);
<file_sep>/routes/limits.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var LimitsController = require('../controllers/limits');
// declaracion del uso de rutas //
var api = express.Router();
// controlador de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Gets //
api.get('/show/:rate', md_auth.ensureAuth, LimitsController.show );
api.get('/show-all', md_auth.ensureAuth, LimitsController.showAll );
//========Post //
api.post('/save/:rate', md_auth.ensureAuth, LimitsController.save);
//========Put //
api.put('/update/:id', md_auth.ensureAuth, LimitsController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, LimitsController.remove);
module.exports = api;<file_sep>/routes/sector.js
'use strict'
var express = require('express');
var SectorController = require('../controllers/sector');
var api = express.Router()
var md_auth = require('../middleware/authenticate');
api.get('/show/:id', md_auth.ensureAuth, SectorController.get);
api.get('/shows', md_auth.ensureAuth, SectorController.gets);
api.post('/save', md_auth.ensureAuth, SectorController.save);
api.put('/update/:id', md_auth.ensureAuth, SectorController.updates);
module.exports = api;<file_sep>/controllers/erasedData.js
'use strict'
var ErasedData = require('../models/erasedData');
var moment = require('moment');
function save (req, res){
var params = req.body;
var erasedData = new ErasedData;
if (req.user.sub) {
erasedData.tabla = params.tabla;
erasedData.contenido = erasedData.contenido;
erasedData.erased_at = moment().unix()
erasedData.erased_by = req.user.sub;
erasedData.save((err, response)=>{
if (err) return res.status(500).send({Message: 'Error en la peticion', Error: err});
if (!response) return res.status(404).send({Message: 'No se ha recibido respuesta por parte del servidor'});
if (response) return res.status(201).send({Message: 'Registrado correctamente..'})
})
}
}
function get(req,res) {
ErasedData.find((err, response)=> {
if (err) return res.status(500).send({Message: 'error en la peticion', Error: err});
if (!response) return res.status(404).send({Message: 'No se recibio respuesta del servidor'});
if (response) return res.status(200).send({Message: 'Lista de Borrados Obtenida', erasedData: response})
})
}
module.exports = {
save, get
}<file_sep>/controllers/rate.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable del esquema del modelo //
var User = require('../models/user');
var Rate = require('../models/rate');
var moment = require('moment');
var Limits = require('../models/limits');
var mongoosePaginate = require('mongoose-pagination');
//=================Declaracion de Funciones //
// Funcion de register de de datos //
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var rate = new Rate;
// Log de Comprobacion //
console.log("Dentro de save");
Rate.find((err, response) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion de comprobacion'});
if (response.Rates) {
for (let index = 0; index < response.Rates.length; index++) {
const element = response.Rates[index];
if (element.tarifa.toLowerCase().replace(' ','').indexOf(params.tarifa.toLowerCase().replace(' ',''))) {
return res.status(500).send({Message: 'Tarifa Registrada Anteriormente.'});
}
}
}
});
// comprobacion de los valores obligatorios enviados desde el formulario //
if (params.tarifa && req.user.sub) {
// Asignacion de los parametros al modelo del Controlador //
rate.tarifa = params.tarifa;
rate.base = params.base
rate.created_by = req.user.sub;
rate.created_at = moment().unix();
rate.percent_cost = params.percent_cost;
// Logs de Comprobacion //
console.log("Dentro del traspaso de Parametros");
console.log(rate);
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
rate.save((err, tarifaStored) => {
// Sentencia 'Si' para comprobar la existencia de errores //
if (err) return res.status(500).send({ Message: 'Error al Guardar la Tarifa' });
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (!tarifaStored) return res.status(404).send({ Message: 'No se pudo ingresar la Tarifa' });
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
return res.status(200).send({ Message: ' Tarifa Ingresada correctamente', Tarifa: tarifaStored });
})
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
res.status(200).send({
Message: 'Datos faltantes o erroneos'
})
}
}
function show(req, res) {
Rate.find({}).populate('created_by updated_by').exec((err, response) => {
if (err) return res.status(500).send({ Message: 'error al obtener las tarifas' });
if (!response) return res.status(404).send({ Message: 'no existen tarifas' });
return res.status(200).send({
Message: 'Listado de Tarifas',
Rates: response
});
})
}
function findRate(req, res) {
const id = req.params.id;
Rate.findById(id).populate('created_by updated_by').exec((error, response)=>{
if (error) return res.status(500).send({Message: 'Error al enviar la peticion....', Error: error});
if (!response) return res.status(404).send({Message: 'No existe esa tarifa...'});
return res.status(200).send({Message: 'Tarifa Econtrada!!..', Rate: response});
})
}
function rateLimits(req, res) {
var rate = req.params.id;
Limits.find({rate_id: rate}, (err, resp) => {
if (err) return res.status(500).send({Message: 'error al ejectuar la peticion'});
if (!resp) return res.status(404).send({Message: 'no se encontraron limites'});
return res.status(200).send({Limites: resp});
})
}
function update(req, res) {
var userId = req.user.sub;
var rate_id = req.params.id;
var tarifa = req.body;
tarifa.updated_by = userId;
tarifa.updated_at = moment().unix();
// var params = [];
// params = {
// tarifa,
// updated_by: userId
// };
// return res.status(200).send({params});
Rate.findOneAndUpdate({ _id: rate_id }, tarifa, { new: true }, (err, rateUpdated) => {
if (err) return res.status(500).send({ Message: 'Error en la peticion' });
if (!rateUpdated) res.status(500).send({ Message: 'No se actualizo la tarifa' });
return res.status(200).send({ Tarifa: rateUpdated });
})
}
function deleteRate(req, res) {
var rateId = req.params.id;
Rate.findOneAndDelete({ '_id': rateId }, (err, delt) => {
if (err) return res.status(500).send({ Message: 'Error al borrar la tarifa' });
if (!delt) return res.status(404).send({ Message: 'No se borro ninguna tarifa' });
return res.status(200).send({ Message: 'tarifa eliminada', delt });
});
}
module.exports = {
save,
show,
update,
deleteRate,
rateLimits,
findRate
}<file_sep>/controllers/facturaNumero.js
'use strict'
var FacturaNumero = require('../models/facturaNumero');
var moment = require('moment');
function save(req, res) {
var params = req.body;
var facturaNumero = new FacturaNumero
facturaNumero.num_min = params.num_min;
facturaNumero.num_max = params.num_max;
facturaNumero.caduca = params.caduca;
facturaNumero.codigoTalonario = params.codigoTalonario;
facturaNumero.estado = params.estado;
facturaNumero.created_at= moment().unix();
facturaNumero.created_by= req.user.sub;
facturaNumero.save((err, response) => {
if (err) return res.status(500).send({Message: 'error al contactar con la base de datos', Error: err});
if (!response) return res.status(404).send({Message: 'no se ha podido guardar el rango de facturas'});
return res.status(201).send({Message: 'exito al guardar el rango de facturas'});
});
}
function update(req, res) {
var id = req.params.id;
var params = req.body;
params.updated_at= moment().unix();
params.updated_by= req.user.sub;
FacturaNumero.findByIdAndUpdate(id, params, {new: true}, (err, updated) => {
if (err) return res.status(500).send({Message: 'Error al contactar con la base de datos'});
if (!updated) return res.status(404).send({Message: 'No se pudo editar el rango de la tarifa'});
return res.status(200).send({Message: 'Edicion exitosa!', updated});
})
}
function gets(req, res) {
FacturaNumero.find().populate('created_by updated_by').exec((error, response) => {
if (error) return res.status(500).send({Message: 'Error al conectar con la Base de Datos'});
if (!response) return res.status(404).send({Message: 'No se pudop obtener los registros del rango de facturas'});
if (response.length <=0) return res.status(200).send({Message: 'no existen rangos de facturas ingresados'});
return res.status(200).send({Message: 'Rangos de facturas obtenidos correctamente...', Numeros: response})
})
}
module.exports = {
save,
update,
gets
}<file_sep>/routes/backups/message.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var MessageController = require('../controllers/message');
// declaracion del uso de rutas //
var api = express.Router();
// importacion del middleware de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Gets //
api.get('/prueba', md_auth.ensureAuth, MessageController.prueba);
api.get('/show-received/:page?',md_auth.ensureAuth,MessageController.showReceiver);
api.get('/show-emitted/:page?',md_auth.ensureAuth, MessageController.showEmitter);
api.get('/unviewed',md_auth.ensureAuth, MessageController.unviewed);
api.get('/viewed',md_auth.ensureAuth, MessageController.viewed);
//========Post //
api.post('/save', md_auth.ensureAuth, MessageController.save);
//========Delete //
module.exports = api;<file_sep>/controllers/user.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable para encriptar la contraseña //
var bcrypt = require('bcrypt-nodejs');
// Variable del esquema del modelo user //
var User = require('../models/user');
// Variable token //
var jwt = require('../services/jwt');
// Variable para el sistema de archivos
var fs = require('fs');
// variable para rutas del sistema de archivos
var path = require('path');
// variable para transformar fecha en numeros
var moment = require('moment');
//=================Declaracion de Funciones //
// >> Ingresar Usuario-Simple
function saveUser(req, res) {
// recolectar los parametros enviados
var params = req.body;
// iniciar una nueva variable con el modelo User
var user = new User;
// comprobar si hay un logeo previo
if (!req.user.sub) {
// enviar error Forbiden [prohibido] en caso de que se intente ingresar un usuario sin antes haber iniciado sesion en el sistema
return res.status(403).send({
Message: 'Solo los Empleados pueden ingresar usuarios '
});
// comprobar que el usuario que inicio sesion no se aun usuario normal [ propietario de medidor ]
} else if (req.user.sub && req.user.role_user.toLowerCase() != 'Common') {
// comprobar que existen los datos minimos para un usuario simple [ nombre, apellido, cedula {direccion opcional} ]
if (params.nombre && params.cedula && params.apellido) {
// >> aqui se rellenan las variables que por defecto se quedaran vacias pero se asigna null para evitar fallos en el sistema
user.cuenta = null;
user.contrase = null;
user.correo = null;
// << fin del relleno
// >> se ingresan o dan valor a los campos del modelo de usuario [User]
user.nombre = params.nombre;
user.apellido = params.apellido;
user.cedula = params.cedula;
// >>> Comprobacion si existe direccion ingresada
if (params.direccion) {
// >>>> Si se ingreso direccion se la asigna al modelo del usuario a ingresar
user.direccion = params.direccion;
} else {
// >>>> En caso de que no haya ingresado una direccion se le asigna por defecto como [Sin Direccion]
user.direccion = 'Sin Dirección';
}
user.sexo = params.sexo;
if (user.sexo.toLowerCase() == 'femenino' || user.sexo.toLowerCase() == 'f') {
user.image = 'avatarF.png';
} else if (user.sexo.toLowerCase() == 'masculino' || user.sexo.toLowerCase() == 'm') {
user.image = 'avatarM.png';
} else {
user.image = 'avatarI.png';
}
user.activa = true;
user.created_at = moment().unix();
// >>> Se asigna el rol de usuario de forma automatica en Usuario //
user.role_user = 'Common';
// >>> Asignacion del usuario que inicio sesion en el campo que registra quien creo al usuario a ingresar
user.created_by = req.user.sub;
console.log('dentro de save user');
console.log(user);
// >>> revision en el sistema si la cedula ingresada en el sistema no es repetida
User.find({
"cedula": params.cedula
}, (err, resp) => {
// >>>> revision de errores en la peticion a la base de datos
if (err) return res.status(500).send({
Message: 'Error... No se ha podido realizar la peticion',
Error: err
});
// >>>> comprobacion si existe o no la cedula, en caso de que exista se envia un estado 401 [sin autorizacion] y un mensaje de duplicado
if (resp.length >= 1) return res.status(401).send({
Message: 'Usuario Duplicado, revise la cedula'
});
else {
// >>> en caso de que la cedula ingresada se a unica se envia el usuario a la base de datos
user.save((err, userStored) => {
// >>>> Retorno de un error 500: no se pudo realizar la accion
if (err) return res.status(500).send({
Message: 'Error al ejectuar la peticion',
Error: err
});
// >>>> en caso de que el SGBD responda con el valor [usuarioStored] se envia un mensaje 201 de confirmacion de ingreso en la base de datos
if (userStored) {
res.status(200).send({
Message: 'Usuario guardado Exitosamente!!',
user: userStored
});
}
// >>>> si el SGBD no responde o responde algun valor diferente se estima que no se pudo ingresar el usuario
else {
// Se devuelve un error 404 al servidor para advertir que no se pudo registrar el usuario
res.status(404).send({
Message: 'No se pudo Registrar el usuario'
})
}
});
};
})
}
// >> Comprobacion en caso de que no llegasen los campos requeridos
} else {
// >>> se devuelve un error con estado 500 indicando que hay un error en la peticion
return res.status(500).send({
Message: 'error, debe llenar todos los campos..',
usuario: params
});
}
}
// << Ingresar Usuario-Simple
// >> Ingresar Usuario-Usuario
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var user = new User;
// >>> comprobacion de los valores obligatorios enviados desde el formulario //
if (params.cuenta && params.contrase && params.correo && params.cedula) {
// Asignacion de los parametros al modelo del Controlador //
user.cuenta = params.cuenta;
user.contrase = params.contrase;
user.correo = params.correo;
user.nombre = params.nombre;
user.apellido = params.apellido;
user.cedula = params.cedula;
user.telefono = params.telefono;
user.direccion = params.direccion;
user.fecha_nacimiento = params.fecha_nacimiento;
user.sexo = params.sexo;
if (user.sexo.toLowerCase() == 'femenino' || user.sexo.toLowerCase() == 'f') {
user.image = 'avatarF.png';
} else if (user.sexo.toLowerCase() == 'masculino' || user.sexo.toLowerCase() == 'm') {
user.image = 'avatarM.png';
} else {
user.image = 'avatarI.png';
}
user.activa = true;
user.role_user = params.role_user;
user.created_at = moment().unix();
user.created_by = null;
if (req.user && req.user.sub) user.created_by = req.user.sub;
// Comprobacion de datos Unicos //
User.find({
$or: [{
"correo": user.correo
},
{
"cuenta": user.cuenta
},
{
"cedula": user.cedula
}
]
}).exec((err, users) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion'
})
if (users && users.length >= 1) return res.status(500).send({
Message: 'Duplicado',
contenido: users,
cantidad: users.length,
usuario: user
});
else {
console.log(users);
// Logs de Comprobacion //
console.log("Dentro del traspaso de Parametros");
console.log(user);
// Uso de la libreria bcrypt para encriptar la contraseña //
bcrypt.hash(params.contrase, null, null, (error, hash) => {
user.contrase = hash;
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
user.save((err, userStored) => {
// Log de Error mostrado en la Consola //
console.log(err);
// Retorno de un error 500: no se pudo realizar la accion //
if (err) return res.status(500).send({
Message: 'Error al comunicarse con el servidor'
});
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (userStored) {
// Se envian los datos del objeto mediante un send con el objeto mismo y un codigo 201 //
return res.status(201).send({
User: userStored,
Message: 'Empleado Guardado'
});
}
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
else {
// Se devuelve un error 404 al cliente indicando que el objeto se encuentra vacio //
return res.status(404).send({
Message: 'No se pudo Registrar el Empleado'
})
}
});
})
}
});
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
return res.status(500).send({
Message: 'Datos faltantes o erroneos'
})
}
}
// << Ingreso Usuario-Usuario
// >> Funcion para ingreso al sistema mediante un login //
function login(req, res) {
// >>> se reciben los datos [parametros] enviados en la peticion
var params = req.body;
// >>> se hace una busqueda en la base de datos con el nombre de la cuenta
User.findOne({
$and: [{
cuenta: params.cuenta
}]
}, (err, user) => {
// >>>> en caso de que la peticion al servidor falle se envia un estado 500 y el error
if (err) return res.status(500).send({
Message: 'error en la peticion... Error: ' + err
});
// >>>> si no se produce ningun fallo y tampoco devuelve respuesta quiere decir que no hay un usuario con esa cuenta
if (!user) return res.status(404).send({
Message: 'el usuario no existe . . . '
});
// >>>> si encuentra una cuent, pero esta no tiene el campo de activa o lo tiene desactivado se envia el mensaje de cuenta desactivada
if (user.activa = false || !user.activa) return res.status(401).send({
Message: 'la cuenta ha sido desactivada . . . '
});
// >>>> en caso de que tenga el campo activa en verdadero [true] se procede a comparar la contraseña
if (user) {
// >>>>> debido a que se utiliza una encriptacion en las contraseñas se encripta la contraseña ingresada y se compara con la almacenada
bcrypt.compare(params.contrase, user.contrase, (err, check) => {
// >>>>>> en caso de que se de un error en la peticion se envia un estado 500 y el mensaje de error
if (err) return res.status(500).send({
Message: 'error al ejecutar la peticion...',
Error: err
});
// >>>>>> en caso de que la comparacion de falsa o no de resultado se estima que la comparacion dio falso y se envia el mensaje de contraseña incorrecta
if (!check) return res.status(403).send({
Message: 'Contraseña incorrecta!...'
});
if (check) {
// >>>>>> en caso de que devuelva la comparacion en positivo se revisa si dentro de los parametros existe el campo GetToken para generar el token correspondiente
if (params.gettoken) {
// >>>>>>> se eliminan los valores del objeto usuario para evitar que si se llegase a robar el token no puedan obtener la contraseña, el estado deactiva y __v
user.contrase = undefined;
user.activa = undefined;
user.__v = undefined;
// >>>>>>> despues de borrar los campos se devuelve un estado 200
return res.status(200).send({
// >>>>>>>> se envia el objeto usuario
user: user,
// >>>>>>>> se envia el token despues de generar el token
token: jwt.createToken(user),
// >>>>>>>> se envia un mensaje de confirmacion
Message: 'Fin del Login con token'
})
// >>>>>>> en caso de que no llegase el campo GetToken
} else {
// >>>>>>> se eliminan los valores del objeto usuario para evitar que si se llegase a robar el token no puedan obtener la contraseña, el estado deactiva y __v
user.contrase = undefined;
user.activa = undefined;
user.__v = undefined;
// >>>>>>> se devuelve un estado 200 con el mensaje de confirmacion y el objeto usuario
return res.status(200).send({
Message: 'Login Realizado',
user: user
})
}
// >>>>>> en caso de que se produzca un error se envia el error y un mensaje
} else if (err) {
return res.status(500).send({
Message: 'Nombre de Cuenta o Contraseña incorrecta!',
Error: err
})
}
})
// >>>> en caso de que no haya respuesta se asume que el usuario no existe y se envia el estado 404 y un mensaje
} else {
return res.status(404).send({
Message: 'No se Encuentra al user'
})
}
})
}
// << Funcion para ingreso al sistema mediante un login
// >> Devolver Usuario [logeado o buscado]
function show(req, res) {
// >>> se establece la variable userId como el usuario logeado
var userId = req.user.sub;
// >>> en caso de que dentro de la URL llegue un id de usuario se substituye userId con el id enviado
if (req.params.id) {
userId = req.params.id;
}
// >>> se hace una busqueda de usuarios con el usuario enviado y que tenga el campo activa en verdadero [true]
User.findOne({
$and: [{
"activa": true
}, {
"_id": userId
}]
}).populate('updated_by created_by').exec((err, user) => {
// >>>> en caso de error se envia un estado 500 y el mensaje de error
if (err) return res.status(500).send({
Message: 'Error en la peticion. ',
err
});
// >>>> si no hay respuesta se envia un estado 404 y el mensaje de que no existe el usuario
if (!user) return res.status(404).send({
Message: 'El usuario no existe'
});
// >>>> se hace un llamado a la funcion followThisUser [siguiendo a este usuario] para saber si el usuario logeado esta siguiendo al usuario buscado
return res.status(200).send({
Message: 'Lista de Usuarios cargada Correctamente!...',
user: user
});
});
}
// << Devolver Usuario [logeado o buscado]
// >> Mostrar usuarios(paginado)
function showUsers(req, res) {
var userId = req.user.sub;
var page = 1;
if (req.params.page) {
page = req.params.page;
}
var itemsPerPage = 5;
User.find().sort('_id').paginate(page, itemsPerPage, (err, users, total) => {
if (err) return res.status(500).send({
Message: 'Error en la peticion'
});
if (!users) return res.status(404).send({
Message: 'No Hay Users'
});
followUsersIds(userId).then((value) => {
return res.status(200).send({
users,
following: value.following,
followed: value.followed,
total,
pages: Math.ceil(total / itemsPerPage)
});
});
})
}
// << Mostrar usuarios (paginado)
// >> Mostrar Usuarios [crudo]
function showRaw(req, res) {
/// >>>> en caso de que exista un usuario logeado se hace una peticion de la lista de usuarios logueados
User.find().sort([
['apellido', 'asc']
]).select({
'contrase': 0
}).populate('updated_by created_by').exec((err, resp) => {
// >>>>> en caso de que se produzca un error se envia un estado 500 y un mensaje
if (err) return res.status(500).send({
Message: 'no se pudo obtener la lista de usuarios...',
Error: err
});
// >>>>> en caso de que no se devuelva ningun conjunto de objetos se devuelve un estado 404 y un mensaje
if (!resp) return res.status(404).send({
Message: 'no se obtuvo ningun usuario'
});
return res.status(200).send({
Message: 'Lista Cargada Correctamente!!...',
Usuarios: resp
})
})
}
// << Mostrar Usuarios [crudo]
// >> Mostrar Usuarios [crudo]
function showForCons(req, res) {
// >>> comprobacion de usuario logeado
if (!req.user.sub) {
// >>>> en caso de que no haya un usuario logeado se devuelve un error 401 y un mensaje
return res.status(401).send({
Message: 'No se puede Obtener Acceso a Los Registros Sin antes Ingresar al Sistema...'
})
} else {
/// >>>> en caso de que exista un usuario logeado se hace una peticion de la lista de usuarios logueados
User.find().sort([
['apellido', 'asc']
]).select({
'contrase': 0
}).populate('updated_by created_by').exec((err, resp) => {
// >>>>> en caso de que se produzca un error se envia un estado 500 y un mensaje
if (err) return res.status(500).send({
Message: 'no se pudo obtener la lista de usuarios...',
Error: err
});
// >>>>> en caso de que no se devuelva ningun conjunto de objetos se devuelve un estado 404 y un mensaje
if (!resp) return res.status(404).send({
Message: 'no se obtuvo ningun usuario'
});
return res.status(200).send({
Message: 'Lista Cargada Correctamente!!...',
Usuarios: resp
})
})
}
}
// << Mostrar Usuarios [crudo]
function updateCommons(req, res) {
var userId = req.params.id;
var update = req.body;
update.updated_at = moment().unix();
update.updated_by = req.user.sub;
User.find({
'cedula': update.cedula
}, (err, resp) => {
let count = 0;
if (err) return res.status(500).send({
Message: 'Error al comprobar la Unicidad de la Cédula',
Error: err
});
if (resp.length >= 1) {
for (let index = 0; index < resp.length; index++) {
const user = resp[index];
if (user._id == userId) {
count = 1;
}
}
if (count === 0) {
return res.status(304).send({
Message: 'Cedula Duplicada'
})
} else if (count === 1) {
console.log('Cedula Unica');
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, Updated) => {
if (err) return res.status(500).send({
Message: 'Error al Ejecutar la peticion de Edicion, estado: [500 - Internal Server Error]',
Error: err
})
if (!Updated) return res.status(404).send({
Message: 'El servidor no devolvio ninguna respuesta, estado: [404 - not found]'
});
return res.status(200).send({
Message: 'El usuario: ' + update.nombre + ' ' + update.apellido + ', se edito correctamente.',
User: Updated
})
})
}
}
if (!resp || resp.length <= 0) {
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, Updated) => {
if (err) return res.status(500).send({
Message: 'Error al Ejecutar la peticion de Edicion, estado: [500 - Internal Server Error]',
Error: err
})
if (!Updated) return res.status(404).send({
Message: 'El servidor no devolvio ninguna respuesta, estado: [404 - not found]'
});
return res.status(200).send({
Message: 'El usuario: ' + update.nombre + ' ' + update.apellido + ', se editó correctamente.',
User: Updated
})
})
}
})
}
// >> Editar usuario
function update(req, res) {
// >>> asignacion de variables
var userId = req.params.id;
var update = req.body;
update.updated_by = req.user.sub;
update.updated_at = moment().unix();
// >>>> se elimina el campo contraseña
// delete update.contrase;
// >>> se determina si el usuario editado es el mismo que el logeado
// if (userId != req.user.sub) {
// // >>>> en caso de que no sean los mismos se retorna un estado 401 y el mensaje de sin acceso
// return res.status(401).send({
// Message: 'Sin Acceso a Edicion de Datos'
// })
// // >>> si el usuario a editar es el mismo que el logeado
// } else {
// >>>> se envian los datos unicos a la funcion unico para comprobar que los datos ingresados no se hayan repetido en otro usuario
unico(userId, update.cuenta, update.correo, update.cedula).then((repetido) => {
// >>>>> se revisa si alguno de los valores dio como resultado alguna repeticion dentro de la base de datos
if (repetido.Correo == 0 || repetido.Cuenta == 0 || repetido.Cedula == 0) {
// >>>>>> en caso de que se hayan repetido se devuelve un estado 401 y el mensaje de datos repetidos
return res.status(401).send({
Message: 'datos repetidos....'
});
// >>>>> en caso de que todos los valores ingresados sean unicos
} else if (repetido.Correo == 1 && repetido.Cuenta == 1 && repetido.Cedula == 1) {
bcrypt.hash(update.contrase, null, null, (error, hash) => {
update.contrase = hash;
// >>>>>> se realiza una peticion de actualizacion de los datos del usuario
User.findByIdAndUpdate(userId, update, {
new: true
}, (err, userUpdated) => {
// >>>>>>> en caso de que la peticion falle se devuelve un estado 500, un mensaje y el error
if (err) return res.status(500).send({
Message: 'Error en la peticion',
Error: err
});
// >>>>>>> en caso de que no se reciba respuesta se devuelve un estado 500 y el mensaje de no actualizado
if (!userUpdated) res.status(500).send({
Message: 'No se actualizo el usuario'
});
// >>>>>>> si se recibe el usuario actualizado se devuelve un estado 200 y el conjunto de objetos
return res.status(200).send({
user: userUpdated
});
})
// >>>>> en caso de que no se reciba respuesta por parte del SGBD
})
} else if (!repetido || repetido == null) {
// >>>>>> se envia un estado 500 y el mensaje de que no hubo respuesta
return res.status(500).send({
Message: 'no se obtuvo respuesta de la comprobacion de datos repetidos . . . . . ' + repetido
})
}
})
// }
}
// << Editar usuario
// >> funcion asíncrona para comprobar la unicidad del usuario a editar
async function unico(id, cuenta, correo, cedula) {
// >>> se ejecuta una busqueda con el campo correo para comprobar unicidad
var Correo = await User.find({
'correo': correo
}).exec().then((resp) => {
// >>>> se inicializa el conteo de repeticiones en 0
var count = 0;
// >>>> en caso de que el SGBD responda
if (resp) {
// >>>>> si la respuesta contiene menos de 0 objetos
if (resp.length <= 0) {
// >>>>>> se asigna el valor de 1 a la variable de conteo
return count = 1;
// >>>>> en caso de que la respuesta contenga un conjunto objetos de 1 o mas
} else {
// >>>>>> se revisa en cada elemento del conjunto de objetos
resp.forEach(element => {
// >>>>>>> se verifica si el elemento en el que se encuentra es el mismo del usuario que se va a editar
if (element.id == id) {
// >>>>>>>> en caso de que sea el mismo usuario se aumenta en 1 el valor de count
return count = count + 1;
// >>>>>> en caso de que no concuerden los usuarios
} else {
// >>>>>>>> se devuelve el valor actual de count
return count;
}
});
}
};
// >>>> una vez finaliza todas las comparaciones se devuelve el valor actual de count
return count;
});
var Cedula = await User.find({
'cedula': cedula
}).exec().then((resp) => {
var count = 0;
if (resp) {
console.log('entrando en comprobacion de cedula...' + resp.cuenta);
if (resp.length <= 0) {
console.log('solo un registro... o ninguno?');
return count = 1;
} else {
resp.forEach(element => {
if (element.id == id) {
return count = count + 1;
} else {
console.log('cedula Repetida');
return count;
}
});
}
};
return count;
});
var Cuenta = await User.find({
'cuenta': cuenta
}).exec().then((resp) => {
var count = 0;
if (resp) {
console.log('entrando en comprobacion de cuenta...' + resp);
if (resp.length <= 0) {
console.log('solo un registro... o ninguno?');
return Cuenta = 1;
} else {
resp.forEach(element => {
if (element.id == id) {
return count = count + 1;
} else {
console.log('cuenta Repetida');
return count;
}
});
}
};
return count;
});
return {
Correo,
Cuenta,
Cedula
};
}
// subir archivos de imagen
function UploadImageUser(req, res) {
var UserId = req.params.id;
try {
if (req.files) {
var file_path = req.files.image.path;
var file_split = file_path.split('/');
var file_name = file_split[2];
var ext_split = file_name.split('\.');
var file_ext = ext_split[1];
if (UserId != req.user.sub) {
return removeFilesOfUpload(res, file_path, 'No tienes permiso para editar la imagen de este User');
}
if (file_ext == 'png' || file_ext == 'jpg' || file_ext == 'jpeg' || file_ext == 'gif') {
// actualizar documento del user
User.findByIdAndUpdate(UserId, {
image: file_name
}, {
new: true
}, (err, userUpdated) => {
if (err) return res.status(500).send({
Message: 'Error en la peticion'
});
if (!userUpdated) res.status(500).send({
Message: 'No se actualizo el usuario'
});
return res.status(200).send({
user: userUpdated
});
});
} else {
return removeFilesOfUpload(res, file_path, 'Ups!, Algo va mal, no se ha podido subir el archivo. Extension no valida.');
}
} else {
return res.status(404).send({
Message: 'No se encuentra una imagen'
});
}
} catch (error) {
console.log(error);
}
}
// funcion interna que remueve los archivos del servidor cuando exista algun error
function removeFilesOfUpload(res, file_path, message) {
fs.unlink(file_path, (err) => {
console.log(err);
return res.status(200).send({
message
});
});
}
function getImageFile(req, res) {
var image_File = req.params.imageFile;
var path_file = './uploads/users/' + image_File;
fs.exists(path_file, (exist) => {
if (exist) {
res.sendFile(path.resolve(path_file));
} else {
res.status(200).send({
Message: 'Ups, no encontramos la imagen dentro del servidor'
});
};
});
}
function removeCompletly(req, res) {
var id = req.params.id;
User.findByIdAndRemove(id, (err, resp) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion . . .' + err
});
if (!resp) return res.status(404).send({
Message: 'la peticion no ha devuelto ningun valor'
});
return res.status(200).send({
Message: 'El usuario ha sido borrado con exito'
});
});
}
function remove(req, res) {
var id = req.params.id;
var activa = false;
User.findByIdAndUpdate(id, {
activa
}, (err, resp) => {
if (err) return res.status(500).send({
Message: 'Error al ejecutar la peticion'
});
if (!resp) return res.status(404).send({
Message: 'La peticion no ha devuelto ningun valor'
});
return res.status(200).send({
Message: 'El usuario ha sido borrado con exito . . . '
});
})
}
function changePassword(req, res) {
var id = req.params.id;
var user = req.user.sub;
var date = moment().unix();
bcrypt.hash(req.body.contrase, null, null, (error, hash) => {
if (error) return res.status(500).send({
Message: 'Error al ejecutar la peticion en el servidor...'
});
if (!hash) return res.status(404).send({
Message: 'Error, el servidor no responde'
});
User.findByIdAndUpdate(id, {
contrase: hash,
updated_by: user,
updated_at: date
}, (err, resp) => {
if (err) return res.status(500).send({
Message: 'error al ejecutar la peticion al servidor',
Error: err
});
if (!resp) return res.status(404).send({
Message: 'el servidor no ha devuelto respuesta!...'
});
return res.status(200).send({
Message: 'La Clave del Usuario ha sido Editada Correctamente!!',
User: resp
});
})
});
}
function passwordConfirm(req, res) {
var id = req.user.sub;
var params = req.body;
User.findById(id, {
contrase: 1
}, (err, response) => {
if (err) return res.status(500).send({
Message: 'Error en el servidor',
Error: err
});
if (!response) return res.status(404).send({
Message: 'el servidor ha tardado mucho en responder...'
});
bcrypt.compare(params.contrase, response.contrase, (error, check) => {
if (error) return res.status(500).send({
Message: 'Error en el servidor',
Error: error
});
if (!check) return res.status(404).send({
Message: 'No se pudo realizar la comprobacion por password'
});
return res.status(200).send({
Message: 'Comprobacion Exitosa!',
check
});
});
});
}
function changeActiva(req, res) {
var id = req.params.id;
var user = req.user.sub;
var date = moment().unix();
var params = req.body;
User.findByIdAndUpdate(id, {
activa: params.activa,
updated_by: user,
updated_at: date
}, (err, response) => {
if (err) return res.status(500).send({
Message: 'Error al ejectuar la peticion!...',
Error: err
});
if (!response) return res.status(404).send({
Message: 'El servidor ha tardado demaciado en responder..'
});
return res.status(200).send({
Message: 'Se ha cambiado el estado del usuario de forma Satisfactoria!!',
user: response
});
})
}
module.exports = {
save,
login,
show,
showUsers,
update,
UploadImageUser,
getImageFile,
remove,
removeCompletly,
showRaw,
saveUser,
updateCommons,
changePassword,
passwordConfirm,
changeActiva,
showForCons
}<file_sep>/routes/mora.js
'use strict'
var express = require('express');
var MoraController = require('../controllers/mora');
var api = express.Router();
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Post //
api.post('/save', md_auth.ensureAuth, MoraController.save);
//========Get //
api.get('/show', md_auth.ensureAuth, MoraController.gets);
//========Put //
api.put('/update/:id', md_auth.ensureAuth, MoraController.update);
//========Delete //
api.delete('/delete/:id', md_auth.ensureAuth, MoraController.deletes);
module.exports = api;<file_sep>/models/detalleFactura.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var DetalleFacturaSchema = Schema({
index: Number,
detalle: String,
factura: { type: Schema.ObjectId, ref: 'Bill' },
importe: { type: Schema.ObjectId, ref: 'Importe' },
costo: Number,
descuento: Boolean,
nombre: String,
percent: Boolean,
subtotal: Number,
total: Number,
updated_by: { type: Schema.ObjectId, ref: 'User' },
updated_at: String,
created_by: { type: Schema.ObjectId, ref: 'User' },
created_at: String
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('DetalleFactura', DetalleFacturaSchema);<file_sep>/routes/rate.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// libreria para la conexion y manipulacion de datos en nodejs //
var express = require('express');
// controlador que se usara en esta ruta //
var RateController = require('../controllers/rate');
// declaracion del uso de rutas //
var api = express.Router();
// controlador de autenticacion //
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Gets //
api.get('/show', md_auth.ensureAuth, RateController.show);
api.get('/show-rate/:id', md_auth.ensureAuth, RateController.rateLimits);
api.get('/get-one/:id', md_auth.ensureAuth, RateController.findRate);
//========Post //
api.post('/save', md_auth.ensureAuth, RateController.save);
//========Put //
api.put('/update/:id', md_auth.ensureAuth, RateController.update);
//========Delete //
api.delete('/delete/:id',md_auth.ensureAuth, RateController.deleteRate);
module.exports = api;<file_sep>/models/backups/importeUsuario.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable de Mongoose //
var mongoose = require('mongoose');
// la variable schema es una parte del modulo mongoose que permite cargar los esquemas a realizar //
var Schema = mongoose.Schema;
// Variable de entidad que da forma a todos los objetos con este esquema //
var ImporteSchema = Schema({
detalle: String,
medidor: {type: Schema.ObjectId, ref: 'Meter'},
importe: {type: Schema.ObjectId, ref: 'Importe'},
edited_by: {type: Schema.ObjectId, ref: 'user'},
edited_at: String
});
// Exportacion del modelo para habilitarlo en toda la aplicacion //
module.exports = mongoose.model('ImporteUsuario', ImporteSchema);<file_sep>/models/erasedData.js
'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var erasedData = Schema({
tabla: String,
contenido: String,
erased_at: String,
erased_by: {type: Schema.ObjectId, ref: 'user'}
});
module.exports = mongoose.model('ErasedData', erasedData);<file_sep>/controllers/statistics.js
'use strict'
var User = require('../models/user');
var Bill = require('../models/bill');
var Meter = require('../models/meter');
var Extra = require('../models/extra');
var Importe = require('../models/importe');
var Rate = require('../models/rate');
var Register = require('../models/register');
var Sector = require('../models/sector');
var Detalle = require('../models/detalleFactura');
function getStaticsByUser(req, res) {
var id = req.params.id;
getCountsGeneratedsByUser(id).then((countsGenerateds) => {
getCountsOnwedByUser(id).then((countsOwneds) => {
getCountsGlobal().then((countGlobal) => {
return res.status(200).send({
Message: 'Lista de Conteos Generada Correctamente!!...',
generateds: countsGenerateds,
owners: countsOwneds,
globals: countGlobal
});
})
})
})
}
async function getCountsGeneratedsByUser(id) {
var users = await User.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
var bills = await Bill.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
var meters = await Meter.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
var extras = await Bill.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
var importes = await Importe.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
var registers = await Register.countDocuments({
updated_by: id
}).exec().then((count) => {
return count;
})
return {
usuarios: users,
facturas: bills,
medidores: meters,
registros: registers,
extras,
importes
}
}
function getGlobals(req, res) {
getCountsGlobal().then( (counts) => {
return res.status(200).send({Message: 'Datos Generales Obtenidos Correctamente!', statistics: counts});
})
}
async function getCountsGlobal() {
var bills = await Bill.countDocuments().exec().then((count) => {
return count;
})
var meters = await Meter.countDocuments().exec().then((count) => {
return count;
})
var rates = await Rate.countDocuments().exec().then((count) => {
return count;
})
var users = await User.countDocuments().exec().then((count) => {
return count;
})
var registers = await Register.countDocuments().exec().then(count => {
return count;
})
var unpayedBills = await Bill.countDocuments({pago: 'debe'}).exec().then((count)=> {
return count;
})
var payedBills = await Bill.find({
$or: [{
"pago": 'efectivo'
},
{
"pago": 'transferencia'
},
{
"pago": 'tarjeta'
}]
}).count().then((count)=> {
return count;
})
var sectors = await Sector.countDocuments().exec().then((count) => {
return count;
})
var avaiableSectors = await Sector.find({activa: true}).count().then((count)=>{
return count;
})
var unavaiableSectors = await Sector.find({activa: false}).count().then((count)=>{
return count;
})
return {
facturas: bills,
facturasPagadas: payedBills,
facturaSinPagar: unpayedBills,
medidores: meters,
tarifas: rates,
usuarios: users,
lecturas: registers,
sectores: sectors,
sectoresActivos: avaiableSectors,
sectoresInactivos: unavaiableSectors
}
}
async function getCountsOnwedByUser(id) {
var bills = await Bill.countDocuments({
usuario: id
}).exec().then((count) => {
return count;
})
var meters = await Meter.countDocuments({
user: id
}).exec().then((count) => {
return count;
})
var costos = await Bill.find({
usuario: id
}, { _id: 1, total: 1 }, (err, response) => {
return response;
})
return {
facturas: bills,
medidores: meters,
costos
}
}
function getBillsNumbers(req, res) {
Bill.find({},{numero: 1, _id: 0}, (err, response) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion de Numeros de Facturas', Error: err});
if (!response) return res.status(404).send({Message: 'No se pudieron cargar los numeros de las facturas'});
if (response.length <=0) return res.status(200).send({Message: 'Aun no hay facturas ingresadas'});
return res.status(200).send({Message: 'Datos de las facturas Obtenidos Correctamente... ', numeros: response});
})
}
function getCedulas(req, res) {
User.find({}, {cedula: 1, cuenta: 1, correo: 1, _id:0}, (err, response) => {
if (err) return res.status(500).send({Message: 'Error al Ejecutar la peticion de cedulas', Error: err});
if (!response) return res.status(404).send({Message: 'Error al devolver las cedulas'});
if (response.length<=0) return res.status(404).send({Message: 'No se registra ninguna cedula'});
return res.status(200).send({Message: 'Cedulas Cargadas correctamente', cedulas: response})
})
}
function getStatisticsSectores (req, res) {
Sector.countDocuments().exec().then((count) => {
return res.status(200).send({Message: 'carga de sectores correcta', sectores: count});
})
}
function getMetersSectors (req, res) {
var sector = req.params.id;
Meter.countDocuments({sector}).exec().then((count)=> {
return res.status(200).send({Message: 'Medidores por Sector correcto', meters: count});
})
}
function getMeterNumbers (req, res) {
Meter.find({}, {clave: 1, _id:0}, (err, response) => {
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion en el servidor', Error: err});
if (!response) return res.status(404).send({Message: 'Error al devolver las claves de medidor'});
if (response.length <=0) return res.status(200).send({Message: 'No hay registros de claves en el sistema!'});
return res.status(200).send({Message: 'Exito al devolver las claves de medidores existentes!', Claves: response});
})
}
function getAll(req, res) {
console.log(req.user.sub);
getOneByOne().then((globals)=> {
return res.status(200).send({Message: 'Todos los Datos', globals})
})
}
async function getOneByOne () {
var medidores = await Meter.find({}, {rate: 1, user: 1, sector: 1, _id: 1},(err, response)=>{
return response;
})
var tarifas = await Rate.find({},{tarifa:1, _id:1},(err, response) => {
return response;
})
var registros = await Register.find({}, {consumo: 1, bill: 1, meter: 1, _id: 1}, (err, response) => {
return response;
})
var facturas = await Bill.find({}, {pago: 1, tarifa: 1, medidor: 1, usuario: 1, registro: 1, _id: 1}, (err, response) => {
return response;
})
var extras = await Extra.find((err, response) => {
return response;
})
var detalles = await Detalle.find((err, response) => {
return response;
})
var sectores = await Sector.find((err, response) => {
return response;
})
var usuarios = await User.find((err, response) => {
return response;
})
return {
medidores,
tarifas,
registros,
facturas,
extras,
detalles,
sectores,
usuarios
}
}
module.exports = {
getStaticsByUser,
getBillsNumbers,
getCedulas,
getStatisticsSectores,
getMetersSectors,
getGlobals,
getMeterNumbers,
getAll
}<file_sep>/routes/errorCatcher.js
'use strict'
var express = require('express');
var ErrorCatcherController = require('../controllers/errorCatcher');
var api = express.Router();
var md_auth = require('../middleware/authenticate');
//=================Rutas //
//========Post //
api.post('/save', md_auth.ensureAuth, ErrorCatcherController.saveError);
//========Put //
api.put('/put-me-on-it/:id', md_auth.ensureAuth, ErrorCatcherController.workOnIt);
api.put('/i-got-it/:id', md_auth.ensureAuth, ErrorCatcherController.solvedError);
//========Get //
api.get('/errors', ErrorCatcherController.getErrors);
module.exports = api;<file_sep>/controllers/tabla.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable del esquema del modelo //
var Tabla = require('../models/tabla');
var moment = require('moment');
//=================Declaracion de Funciones //
// Funcion de register de de datos //
function save(req, res) {
// variable para la recoleccion de datos del formulario //
var params = req.body;
// variable para la definicion del objeto con respecto al modelo //
var tabla = new Tabla;
// Log de Comprobacion //
console.log("Dentro de save");
// comprobacion de los valores obligatorios enviados desde el formulario //
if (params.nombre) {
// Asignacion de los parametros al modelo del Controlador //
tabla.nombre = params.nombre;
// Logs de Comprobacion //
console.log("Dentro del traspaso de Parametros");
console.log(tabla);
tabla.updated_at = moment().unix();
tabla.updated_by = req.user.sub;
tabla.activa = true;
Tabla.find({ nombre: tabla.nombre }).exec((err, tablas) => {
if (err) {
return res.status(500).send({
Message: 'Error al Guardar'
},
console.log(err))
}
if (tablas && tablas.length >= 1) {
return res.status(500).send({ Message: 'duplicado' })
} else {
// Instruccion Save de Mongoose para Guardar los Parametros en MongoDB //
// usando un callback para el 'Catcheo' de Errores //
tabla.save((err, tablaStored) => {
// Sentencia 'Si' para comprobar la existencia de errores //
if (err) {
// Log de Error mostrado en la Consola //
console.log(err);
// Retorno de un error 500: no se pudo realizar la accion //
return res.status(500).send({
Message: 'Error al Guardar',
message2: err
});
}
// Sentencia 'Si' para comprobar la existencia de valores dentro del Objeto //
if (tablaStored) {
// Se envian los datos del objeto mediante un send con el objeto mismo y un codigo 200 //
res.status(200).send({ tabla: tablaStored });
}
// Sentencia 'Entonces' complementaria al 'Si' para identificar un objeto vacio //
else {
// Se devuelve un error 404 al cliente indicando que el objeto se encuentra vacio //
res.status(404).send({
Message: 'Objeto Vacio o Incompleto'
})
}
})
}
})
}
// en caso de que los datos esten incompletos o dañados se envia un mensaje de error //
else {
res.status(200).send({
Message: 'Datos faltantes o erroneos'
})
}
}
function show(req, res){
Tabla.find().populate('updated_by').exec((err, resp)=>{
if (err) return res.status(500).send({ Message: 'error al procesar la peticion' , Error: err});
if (!resp) return res.status(404).send({ Message: 'no se pudo procesar la peticion, vacia' });
return res.status(200).send({
Tabla: resp
})
})
}
function update(req,res) {
var id = req.params.id;
var tablaUpdate = req.body;
tablaUpdate.updated_at = moment().unix();
tablaUpdate.updated_by = req.user.sub;
Tabla.findByIdAndUpdate(id, tablaUpdate, {new : true}, (err, updated) => {
if (err) return res.status(500).send({ Message: 'error al ejecutar la peticion... ', Error: err });
if (!updated) return res.status(404).send({ Message: 'Error al editar, no se encontro la tabla' });
return res.status(200).send({ Message: 'la tabla: ' + updated.nombre + ' ha sido editado', updated });
})
}
function removeCompletly(req,res) {
var id = req.params.id;
Tabla.findByIdAndRemove(id, (err, deleted) => {
if (err) return res.status(500).send({ Message: 'Error al ejecutar la peticion' });
if (!deleted) return res.status(404).send({ Message: 'No se pudo borrar el perfil de Tabla' });
return res.status(200).send({ Message: 'El perfil de tabla: ' + deleted.nombre + ', ha sido borrado con exito!.' });
})
}
function remove(req, res) {
var id = req.params.id;
var activa = false;
Tabla.findByIdAndUpdate(id, activa, (err, resp)=>{
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion. . . Error: ' + err});
if (!resp) return res.status(404).send({Message: 'la peticion no ha devuelto ningun valor . . . '});
return res.status(200).send({Message: 'La tabla se ha borrado correctamente . . . '});
})
}
module.exports = {
save,
show,
update,
remove,
removeCompletly
}<file_sep>/services/jwt.js
'use strict'
// libreria de jwt //
var jwt = require('jwt-simple');
// obtencion de fechas //
var moment = require('moment');
// clave de reconocimiento interna //
var secret = 'clave_token_agua_potable';
exports.createToken = function(user) {
var payload = {
sub: user._id,
cuenta: user.cuenta,
contrase: user.contrase,
correo: user.correo,
activa: user.activa,
role_user: user.role_user,
iat: moment().unix(),
exp: moment().add(5,'days').unix()
};
return jwt.encode(payload, secret)
};
<file_sep>/models/errorCatcher.js
'user strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ErrorSchema = Schema({
description: String,
message: String,
action: String,
code: String,
title: String,
table: String,
zone: String,
updated_at: String,
repaired: Boolean,
registered_by: {type: Schema.ObjectId, ref: 'User' },
solved_by: {type: Schema.ObjectId, ref: 'User' }
})
module.exports = mongoose.model('ErrorCatcher', ErrorSchema);
<file_sep>/controllers/importe.js
'use strict' // Habilita el uso de cualquiera de librerias de forma forzada y el uso de los nuevos standares de JavaScript 6 //
//=================Declaracion de variables //
// Variable del esquema del modelo //
var Importe = require('../models/importe');
var moment = require('moment');
//=================Declaracion de Funciones //
// Funcion de register de datos //
function save(req,res) {
var params = req.body;
var importe = new Importe;
if (params.nombre && params.costo && params.descuento && params.percent) {
importe.nombre = params.nombre;
importe.costo = params.costo;
importe.percent = params.percent;
importe.descuento = params.descuento;
importe.created_at = moment().unix();
importe.created_by = req.user.sub;
importe.save((err, response)=> {
console.log('guardando....');
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion', Error: err});
if (!response) return res.status(404).send({Message: 'el servidor no responde....'});
if (params.descuento === true) {
return res.status(201).send({Message: 'Descuento agregado correctamente', Importe: response});
} else {
return res.status(201).send({Message: 'Importe agregado correctamente', Importe: response});
}
});
} else {
return res.status(404).send({Message: 'Datos Faltantes.... Nombre: ' + params.nombre + ', Costo: ' + params.costo + ', Porcentaje?: ' + params.percent + ', es Descuento?: ' + params.descuento});
}
}
function show(req, res) {
Importe.find().populate('created_by updated_by').exec((err, response)=>{
if (err) return res.status(500).send({Message: 'error al ejecutar la peticion', Error: err});
if (!response) return res.status(404).send({Message: 'el servidor no responde....'});
return res.status(200).send({Message: 'Lista de Importes Cargada..', Importes: response});
});
}
function update(req, res) {
var id = req.params.id;
var params = req.body;
params.updated_at = moment().unix();
params.updated_by = req.user.sub;
Importe.findByIdAndUpdate(id, params, {new: true}, (err, resp)=>{
if (err) return res.status(500).send({Message: 'Error al ejecutar la peticion . . . Error: ' + err});
if (!resp) return res.status(404).send({Message: 'La peticion no ha devuelto ningun valor'});
if (params.descuento === true ) return res.status(200).send({Message: 'El Descuento se ha editado correctamente . . . '});
if (params.descuento === false ) return res.status(200).send({Message: 'El Importe se ha editado correctamente . . . '});
})
}
function remove(req, res) {
var id = req.params.id;
Importe.findByIdAndRemove(id, (err, resp) => {
if (err) return res.status(500).send({Message: 'Error al ejectuar la peticion'})
if (!resp) return res.status(404).send({Message: 'La peticion no ha devuelto ningun valor. . .'});
return res.status(200).send({Message: 'el importe se ha borrado correctamente . . .'});
})
}
module.exports = {
save,
show,
update,
remove
} | 1e4ab921d7c2b8c5df4c8983db7bbca399ce8828 | [
"JavaScript",
"Markdown"
] | 43 | JavaScript | azuls123/meragua3.2 | 61c174b57d997b494c9bb69c68da5acf9f49257f | e3843112edbbb01447feb54c7345bec39f0f95f9 |
refs/heads/master | <file_sep>import { Component } from '@angular/core';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test';
date;
ngOnChanges(){
console.log(this.date);
}
events: string[] = [];
addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
this.events.push(`${type}: ${event.value}`);
}
}
<file_sep>import { Component, OnInit,Input, Output, EventEmitter } from '@angular/core';
import { NavItem } from '../NavItem';
import { element } from 'protractor';
@Component({
selector: 'app-nav-items',
templateUrl: './nav-items.component.html',
styleUrls: ['./nav-items.component.css']
})
export class NavItemsComponent implements OnInit {
@Input() navSubItems:NavItem[];
subMenuItem = false;
@Output() selectedItem = new EventEmitter();
arrow=">";
constructor() { }
ngOnInit() {
console.log(this.navSubItems,"app-nav-items")
// this.navItems.forEach(element => {
// if (typeof(element.Items)=="object"){
// this.subMenuItem = true;
// console.log(this.subMenuItem,"subMenuItem")
// }
// });
}
clicked(id){
this.selectedItem.emit(id);
console.log("clicked"+id);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { navJSON } from '../navJSON';
import { NavItem } from '../NavItem';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
navItemsData = navJSON;
showMenu:Boolean=false;
constructor() { }
ngOnInit() { }
openMenu(){
this.showMenu=!this.showMenu;
}
getSelectedItem(selectedItem){
alert("You selected" + selectedItem);
}
}
<file_sep>export interface NavItem {
Label: string;
Items: NavItem[];
}
| 93b10c1156f8d82f012a7322e29d34d059321fa5 | [
"TypeScript"
] | 4 | TypeScript | Nikita05/MultiLevelDropDown | b90a5d060d38d5cf4523982095aa7186d03b131b | abbe6da67ffcd5a5981fcff63ef2788b17403be1 |
refs/heads/master | <repo_name>karolsidor11/SimpleDesignPaterns<file_sep>/src/main/java/decorator/ChickenPizza.java
package decorator;
import java.math.BigDecimal;
public class ChickenPizza extends PizzaDecorator{
public ChickenPizza(Pizza currentPizza) {
super(currentPizza);
}
@Override
public String description() {
return super.description()+" chicken +";
}
@Override
public BigDecimal price() {
return super.price().add(BigDecimal.valueOf(10));
}
}
<file_sep>/src/main/java/facade/BankLogin.java
package facade;
public class BankLogin {
public static final int DEFAULT_PIN = 1234;
public static final long DEFAULT_CARD_NUMBER = 123456789L;
public boolean identification(Long bankCardNumber, int PIN) {
if (bankCardNumber == DEFAULT_CARD_NUMBER && PIN == DEFAULT_PIN) {
return true;
}
return false;
}
public void webIdentification(String id, String password) {
// Not implemented yet.
}
}
<file_sep>/src/main/java/strategy/CD.java
package strategy;
import java.math.BigDecimal;
public class CD {
private BigDecimal price;
public CD(BigDecimal price) {
this.price = price;
}
public BigDecimal getPrice(Vat vat) {
return price.add(vat.calculateVat(price));
}
}
<file_sep>/src/main/java/strategy/Vat7.java
package strategy;
import java.math.BigDecimal;
public class Vat7 implements Vat {
@Override
public BigDecimal calculateVat(BigDecimal price) {
return price.multiply(BigDecimal.valueOf(0.07));
}
}
<file_sep>/src/main/java/decorator/PizzaDecorator.java
package decorator;
import java.math.BigDecimal;
public abstract class PizzaDecorator implements Pizza {
private Pizza pizza;
public PizzaDecorator(Pizza currentPizza) {
pizza = currentPizza;
}
public String description() {
return pizza.description();
}
public BigDecimal price() {
return pizza.price();
}
}
<file_sep>/src/main/java/facade/BankSystem.java
package facade;
public class BankSystem {
public static final int DEFAULT_CARD_NUMBER = 123456789;
public float checkAccountBalance(Long bankCardNumber) {
if (bankCardNumber == DEFAULT_CARD_NUMBER) {
return 10000f;
}
return 0.00f;
}
public String withdrawCash(Integer amount) {
return "The cash dispensed from the ATM : " + amount + " PLN";
}
public String aktywujKarte(Long bankCardNumber) {
return "Your card number: " + bankCardNumber + " has been activated.";
}
public void webPayments() {
// Not implemented yet.
}
public void paymentsByBankTransfer() {
// Not implemented yet.
}
public void internetPayments() {
// Not implemented yet.
}
}
<file_sep>/src/main/java/observer/TemperatureReader.java
package observer;
public class TemperatureReader {
private int nextNumber;
public TemperatureReader(int nextNumber) {
this.nextNumber = nextNumber;
}
public void update(int temperature) {
System.out.println("Reader with the number : " + nextNumber + " indicates temperature " + temperature);
}
}
<file_sep>/src/main/java/decorator/Pizzeria.java
package decorator;
public class Pizzeria {
public static void main(String[] args) {
CarbonaraPizza carbonaraPizza = new CarbonaraPizza(new ChickenPizza(new BasicPizza()));
System.out.println("Your order :");
System.out.println(carbonaraPizza.description());
System.out.println("To pay : "+ carbonaraPizza.price()+ " PLN");
}
}
<file_sep>/README.md
# Simple Design Patterns
Simple Design Patterns - my own implementation of the most used design patterns in Java.
## Overview
The project created in Java 8 contains the proprietary implementation of the most popular and basic design patterns used in Java.
The project includes the implementation of patterns:
- adapter
- builder
- decorator
- facade
- factory
- observer
- singleton
- strategy
### Building the application
```
mvn clean install
```
| c4b93ee58a04e73c5c8e62ee6c71eda96248043a | [
"Markdown",
"Java"
] | 9 | Java | karolsidor11/SimpleDesignPaterns | 5faf526b4d084fcf1883652c91972055d656b31b | 667849952ac0b0c25eabce3871df69d59f8dce43 |
refs/heads/master | <file_sep>using System;
public class Item{
public string Nome;
public string Desc;
public string Cat;
public int Val;
public int Quant;
public string Atrib;
public Item (string nome, string desc, string cat, int val, int quant, string atrib)
{
this.Nome = nome;
this.Desc = desc;
this.Cat = cat;
this.Val = val;
this.Quant = quant;
this.Atrib = atrib;
}
public void Imprimir()
{
Console.WriteLine("O item {0}",this.Nome);
Console.WriteLine("Descrição : {0}",this.Desc);
Console.WriteLine("é um item {0}",this.Cat);
Console.WriteLine("custa {0}",this.Val);
Console.WriteLine("lhe concede {0} {1}",this.Quant,this.Atrib);
}
}
<file_sep>using System;
class MainClass {
public static void Main (string[] args) {
Persona heroi = new Persona("Herói",100);
Console.WriteLine ("bem vindo a Loja de equipamentos mágicos,{0} ! Selecione os itens que deseja",heroi.Nome);
Loja armazen = new Loja();
armazen.Glossario();
do
{
Console.WriteLine("Seu saldo atual é de {0}, use todo o dinheiro que possui para comprar itens para desafiar o rei demonio",heroi.Din);
Console.WriteLine("favor insira o nome do item que vocÊ deseja");
string slot = Console.ReadLine();
heroi.Comprar(slot,armazen);
Console.WriteLine();
heroi.Transc();
Console.WriteLine();
}while(heroi.Din != 0);
}
}<file_sep>using System;
using System.Collections.Generic;
public class Persona {
public string Nome;
public int Din;
public List<Item> Invent = new List<Item>();
public Persona (string nome, int din)
{
this.Nome = nome;
this.Din = din;
}
public void Comprar(string nome,Loja loja)
{
if(loja.Estoque.ContainsKey(nome))
{
Item itemSelec = loja.Estoque[nome];
if(this.Din >= itemSelec.Val)
{
Console.WriteLine("Tem certeza que deseja prosseguir ? digite 1 para sim ou 2 para não ");
int alt = Convert.ToInt32(Console.ReadLine());
if(alt == 1)
{
this.Din = Din - itemSelec.Val;
this.Invent.Add(itemSelec);
}
}
else
{
Console.WriteLine("saldo insuficiente");
}
}
else
{
Console.WriteLine("esse item não existe, tente de novo");
}
}
public void Transc()
{
Console.WriteLine("os itens que você possui no momento são : ");
foreach(Item i in Invent)
{
Console.WriteLine(i.Nome);
}
}
}<file_sep>using System;
using System.Collections.Generic;
public class Loja
{
public Dictionary<string,Item> Estoque = new Dictionary<string,Item>();
public Loja()
{
Item adaga = new Item("adaga","item comum","Guerreiro",10,5,"de ataque");
this.Estoque.Add(adaga.Nome,adaga);
Item espada = new Item("espada","item raro","Guerreiro",20,15,"de ataque");
this.Estoque.Add(espada.Nome,espada);
Item claymore = new Item("claymore","item epíco","Guerreiro",40,45,"de ataque");
this.Estoque.Add(claymore.Nome,claymore);
Item arco = new Item("arco","item comum","atirador",10,10,"de velocidade de ataque");
this.Estoque.Add(arco.Nome,arco);
Item besta = new Item("besta","item raro","atirador",20,30,"de velocidade de ataque");
this.Estoque.Add(besta.Nome,besta);
Item pistola = new Item("pistola","item epíco","atirador",40,50,"de velocidade de ataque");
this.Estoque.Add(pistola.Nome,pistola);
Item varinha = new Item("varinha","item comum","mago",10,10,"de feitiçaria");
this.Estoque.Add(varinha.Nome,varinha);
Item cajado = new Item("cajado","item raro","mago",20,30,"de feitiçaria");
this.Estoque.Add(cajado.Nome,cajado);
Item grimorio = new Item("grimório","item epíco","mago",40,60,"de feitiçaria");
this.Estoque.Add(grimorio.Nome,grimorio);
Item broquel = new Item("broquel","item normal","tank",10,10,"de armadura");
this.Estoque.Add(broquel.Nome,broquel);
Item escudo = new Item("escudo","item raro","tank",20,15,"de armadura");
this.Estoque.Add(escudo.Nome,escudo);
Item aegis = new Item("aegis","item epíco","tank",40,40,"de armadura");
this.Estoque.Add(aegis.Nome,aegis);
Item capa = new Item("capa mistica","item normal","tank",10,10,"de resistência mágica");
this.Estoque.Add(capa.Nome,capa);
Item tunica = new Item("tunica","item raro","tank",20,15,"de resistência mágica");
this.Estoque.Add(tunica.Nome,tunica);
Item selo = new Item("selo","item raro","tank",40,40,"de resistência mágica");
this.Estoque.Add(selo.Nome,selo);
}
public void Adic(Item item)
{
this.Estoque.Add(item.Nome,item );
}
public void Glossario ()
{
foreach(KeyValuePair<string,Item> i in this.Estoque)
{
i.Value.Imprimir();
Console.WriteLine();
}
}
} | c32d035d8f580a8f9286c651831fdd6c481df187 | [
"C#"
] | 4 | C# | art-ds104/lojamagica | 8f6f3189b1f3377ac421b3c6d63b452760993b30 | 865accca02c605cbca11d1934fac9cb59ec53123 |
refs/heads/master | <repo_name>thivi/phoneBay<file_sep>/src/store.js
import Vue from "vue";
import Vuex from "vuex";
import { read } from "./restService";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
cart: [],
items: []
},
getters: {
cartItems: function(state) {
if (state.cart) {
let c = 0;
state.cart.forEach(item => {
c += parseInt(item.qty);
});
return c;
} else {
return 0;
}
}
},
mutations: {
saveItems(state, payload) {
state.items = [...payload];
},
add(state, payload) {
state.cart.push(payload);
},
remove(state, payload) {
state.cart.pop(payload);
}
},
actions: {
getItems: ({ commit }) => {
read("items")
.then(resp => {
commit("saveItems", resp.data);
})
.catch(err => {
console.error(err);
});
},
addToCart: ({ commit }, { item, qty, callback }) => {
commit("add", { item, qty });
callback();
},
remove({ commit }, index) {
commit("remove", index);
}
}
});
<file_sep>/tests/unit/Home.spec.js
import {shallowMount, createLocalVue} from "@vue/test-utils";
import Home from "../../src/views/Home";
import Vuex from "vuex";
import VueRouter from "vue-router";
const localVue=createLocalVue();
localVue.use(Vuex);
localVue.use(VueRouter);
describe("Testing Home view",()=>{
let state;
let store;
let actions;
beforeEach(()=>{
state={
items:[{name:"Item"},{name:"Item2"}]
}
actions={
getItems:jest.fn()
}
store=new Vuex.Store({state,actions})
})
it("Calling getItems action",()=>{
const wrapper=shallowMount(Home,{
store,localVue,stubs:['router-link']
})
expect(actions.getItems).toHaveBeenCalled();
})
it("Items properly displayed",()=>{
const wrapper=shallowMount(Home,{
store,localVue,stubs:['router-link']
})
expect(wrapper.find(".item").exists()).toBeTruthy();
})
})<file_sep>/tests/unit/Item.spec.js
import {shallowMount, createLocalVue} from "@vue/test-utils";
import Item from "../../src/components/Item";
import Vuex from "vuex";
import VueRouter from "vue-router";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
const localVue=createLocalVue();
localVue.use(Vuex);
localVue.use(VueRouter);
localVue.use(FontAwesomeIcon);
describe("Testing Item component",()=>{
let state;
let store;
let actions;
beforeEach(()=>{
actions={
remove:jest.fn()
}
store=new Vuex.Store({state,actions})
})
it("Checking if Item is displayed properly",()=>{
const wrapper=shallowMount(Item,{
store,localVue,stubs:['router-link','font-awesome-icon'],
propsData:{
"id":1,
"index":1,
"units":0,
"name":"Item",
"description":"desc",
"price":500,
"discount":0.5,
"img":"url",
"qty":5
}
})
expect(wrapper.find(".name").text()).toEqual("Item");
expect(wrapper.find(".desc").text()).toEqual("desc");
expect(wrapper.find(".price").text()).toEqual("500 LKR");
expect(wrapper.find(".disc").text()).toEqual("Discount 50%");
expect(wrapper.find("#pim").attributes('src')).toBe("url");
expect(wrapper.find(".del").exists()).toBeFalsy();
})
it("Deleting an item from the cart",()=>{
const wrapper=shallowMount(Item,{
store,localVue,stubs:['router-link','font-awesome-icon'],
propsData:{
"id":1,
"index":1,
"units":2,
"name":"Item",
"description":"desc",
"price":500,
"discount":0.5,
"img":"url",
"qty":5,
"del":1
}
})
expect(wrapper.find(".del").exists()).toBeTruthy();
expect(wrapper.find(".del").trigger("click"));
expect(actions.remove).toHaveBeenCalled();
})
}) | 37d24f72437703cd6eadf5fc32a1379388a64f45 | [
"JavaScript"
] | 3 | JavaScript | thivi/phoneBay | c9f3a8501f139194093718cbd81fb83233306cf6 | ae94be7cf289a9e008c146102a9762ac9040a1ec |
refs/heads/master | <repo_name>vivekgs2007/todolist-app<file_sep>/routes/index.js
var todo = require('../db').collections.todo;
exports.index = function(req, res){
todo.find().toArray(function(err,docs){
if(err) return res.status(500).send({status: 'Falied to find todo list'});
res.render('index', {
title: 'Todo Application',
todolistheader : 'List of Todo Task',
todolist : docs
});
});
};<file_sep>/README.md
todolist-app
============
| d689387f0dcef152f095324c796f5bbedf46c2fa | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | vivekgs2007/todolist-app | d79fd0fc77530158c51ad72e34fc47d8a5b2c9a7 | 38e9be8e94760c6882d34d842c1e218eeefad758 |
refs/heads/master | <repo_name>kcruthe/Getting-and-Cleaning-Data-Course-Project-1<file_sep>/run_analysis.R
## You should create one R script called run_analysis.R that does the following.
## Merges the training and the test sets to create one data set.
## First, Read the training and the test data set
setwd("D:\\Data specialist\\Getting and Clearing Data\\Week4")
library(data.table)
library(plyr)
library(dplyr)
library(reshape2)
## Extracts only the measurements on the mean and standard deviation for each measurement.
Act <- read.table("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/activity_labels.txt")
Act_label <- as.character(Act$V2)
Fetures <- read.table("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/features.txt")
FeturesWanted <- grep(".*mean.*|.*std.*", Fetures[,2])
FeturesWanted.names <- Fetures[FeturesWanted ,2]
FeturesWanted.names = gsub('-mean', 'Mean', FeturesWanted.names)
FeturesWanted.names = gsub('-std', 'Std', FeturesWanted.names)
FeturesWanted.names <- gsub('[-()]', '', FeturesWanted.names)
## Uses descriptive activity names to name the activities in the data set
Tex <- read.table("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/test/X_test.txt")[FeturesWanted]
Trx <- read.table("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/train/X_train.txt")[FeturesWanted]
a <- intersect(names(Tex), names(Trx))
mrg <- merge(Tex, Trx, by = a, all = TRUE)
colnames(mrg) <- FeturesWanted.names
mrg$id <- c(1:nrow(mrg))
## Uses descriptive activity names to name the activities in the data set
## Appropriately labels the data set with descriptive variable names.(y)
Tey <- fread("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/test/y_test.txt")
colnames(Tey) <- c("activity")
Tey$activity <- as.factor(Tey$activity)
levels(Tey$activity) <- Act_label
Try <- fread("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/train/y_train.txt")
colnames(Try) <- c("activity")
Try$activity <- as.factor(Try$activity)
levels(Try$activity) <- Act_label
is.factor(Try$activity)
Dt <- do.call("rbind",list(Tey,Try))
Dt$id <- c(1:nrow(Dt))
## Appropriately labels the data set with descriptive variable names.(z)
Tez <- fread("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/test/subject_test.txt")
colnames(Tez) <- c("subject")
Trz <- fread("./getdata%2Fprojectfiles%2FUCI HAR Dataset/UCI HAR Dataset/train/subject_train.txt")
colnames(Trz) <- c("subject")
Dt2 <- do.call("rbind",list(Tez,Trz))
Dt2$subject <- as.factor(Dt2$subject)
Dt2$id <- c(1:nrow(Dt2))
## Merge the data
## From the data set in step 4, creates a second,
## independent tidy data set with the average of each variable for each activity and each subject.
Mdata <- merge(Dt,Dt2, by = "id", all=TRUE)
MrData <- merge(mrg, Mdata, by = "id", all = TRUE)
MrData <- MrData[,c(2:length(MrData))]
MrData.melted <- melt(MrData , id = c("subject", "activity"))
MrData.mean <- dcast(MrData.melted, subject + activity ~ variable, mean)
write.table(MrData.mean, "tidy.txt", row.names = FALSE)
| 959df492bc2dc296572dee7421b3f71eecc1ce68 | [
"R"
] | 1 | R | kcruthe/Getting-and-Cleaning-Data-Course-Project-1 | c24ee7a375f4d00e7dc730a8b23f6919c5ed3e3d | 89083a32632facfa322cd0c0cb866ab469a5d460 |
refs/heads/master | <repo_name>LunggaW/CMSV3Restored<file_sep>/Backup1/KBS.KBS.CMSV3/Administration/ParameterManagement/ParameterManagementDetailNew.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
using KBS.KBS.CMSV3.Administration;
namespace KBS.KBS.CMSV3.Administration
{
public partial class ParameterManagementDetailNew : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
OutputMessage message = new OutputMessage();
protected override void OnInit(EventArgs e)
{
if (Session["ParamHeaderID"] == null)
{
Response.Redirect("ParameterManagementHeader.aspx");
}
else
{
LabelMessage.Visible = false;
loadNavBar();
}
}
protected void Page_Load(object sender, EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//ASPxComboBoxUserManagementSite.DataSource = DTSite;
//ASPxComboBoxUserManagementSite.ValueField = "SITECODE";
//ASPxComboBoxUserManagementSite.ValueType = typeof(string);
//ASPxComboBoxUserManagementSite.TextField = "SITENAME";
//ASPxComboBoxUserManagementSite.DataBind();
//DTProfile = CMSfunction.GetAllProfile();
//ASPxComboBoxUserManagementProfile.DataSource = DTProfile;
//ASPxComboBoxUserManagementProfile.ValueField = "PROFILEID";
//ASPxComboBoxUserManagementProfile.ValueType = typeof(string);
//ASPxComboBoxUserManagementProfile.TextField = "PROFILENAME";
//ASPxComboBoxUserManagementProfile.DataBind();
//DTGridViewUser = CMSfunction.GetAllUser();
//ASPxGridViewUserManagementUser.DataSource = DTGridViewUser;
//ASPxGridViewUserManagementUser.KeyFieldName = "USERID";
//ASPxGridViewUserManagementUser.DataBind();
//loadNavBar();
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(Session["SiteProfile"].ToString());
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(Session["SiteProfile"].ToString(),
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
}
i++;
}
}
masterNav.DataBind();
}
protected void SearchBtn_Click(object sender, EventArgs e)
{
//ParameterDetail parDetail = new ParameterDetail();
//parHeader.Lock = !string.IsNullOrWhiteSpace(ASPxTextBoxHeaderBlock.Text) ? ASPxTextBoxHeaderBlock.Text : "";
//parHeader.Comment = !string.IsNullOrWhiteSpace(ASPxTextBoxHeaderComment.Text) ? ASPxTextBoxHeaderComment.Text : "";
//parHeader.Copy = !string.IsNullOrWhiteSpace(ASPxTextBoxHeaderCopy.Text) ? ASPxTextBoxHeaderCopy.Text : "";
//parHeader.ID = !string.IsNullOrWhiteSpace(ASPxTextBoxHeaderID.Text) ? ASPxTextBoxHeaderID.Text : "";
//parHeader.Name = !string.IsNullOrWhiteSpace(ASPxTextBoxHeaderName.Text) ? ASPxTextBoxHeaderName.Text : "";
//DTParameterHeader = CMSfunction.GetParameterHeaderData(parHeader);
//ASPxGridViewDetail.DataSource = DTParameterHeader;
//ASPxGridViewDetail.KeyFieldName = "ID"; ASPxGridViewHeader.DataBind();
}
protected void ClearBtn_Click(object sender, EventArgs e)
{
//ASPxTextBoxHeaderBlock.Text = "";
//ASPxTextBoxHeaderComment.Text = "";
//ASPxTextBoxHeaderCopy.Text = "";
//ASPxTextBoxHeaderID.Text = "";
//ASPxTextBoxHeaderName.Text = "";
//ASPxTextBoxHeaderSClas.Text = "";
}
protected void BackhomeBtn_Click(object sender, EventArgs e)
{
Session.Remove("ParamDetailIDNew");
if (Page.IsCallback)
ASPxWebControl.RedirectOnCallback("ParameterManagementDetail.aspx");
else
Response.Redirect("ParameterManagementDetail.aspx");
//Session.Remove("ParamHeaderID");
}
protected void SaveBtn_Click(object sender, EventArgs e)
{
ProcessInsert();
LabelMessage.ForeColor = message.Code < 0 ? Color.Red : Color.Black;
LabelMessage.Visible = true;
LabelMessage.Text = message.Message;
}
protected void ValidateBtn_Click(object sender, EventArgs e)
{
ProcessInsert();
Response.Redirect("ParameterManagementDetail.aspx");
}
private void ProcessInsert()
{
ParameterDetail parDetail = new ParameterDetail();
parDetail.Entry = ASPxTextBoxDetailEntry.Text;
parDetail.Char1 = ASPxTextBoxDetailParValChar1.Text;
parDetail.Char2 = ASPxTextBoxDetailParValChar2.Text;
parDetail.Char3 = ASPxTextBoxDetailParValChar3.Text;
parDetail.Comment = ASPxMemoComment.Text;
parDetail.SiteClass = Session["ParamHeaderSClass"].ToString();
parDetail.ID = Session["ParamHeaderID"].ToString();
parDetail.LongDescription = ASPxTextBoxDetailLDesc.Text;
parDetail.Number1 = ASPxTextBoxDetailParVal1.Text;
parDetail.Number2 = ASPxTextBoxDetailParVal2.Text;
parDetail.Number3 = ASPxTextBoxDetailParVal3.Text;
parDetail.Number4 = ASPxTextBoxDetailParVal4.Text;
parDetail.ShortDescription = ASPxTextBoxDetailSDesc.Text;
//parDetail.SiteClass = aspxtext.Text;
parDetail.Date1 = ASPxDateEditPar1.Date;
parDetail.Date2 = ASPxDateEditPar2.Date;
parDetail.Date3 = ASPxDateEditPar3.Date;
message = CMSfunction.InsertParameterDetail(parDetail, Session["UserID"].ToString());
}
}
}<file_sep>/KBS.KBS.CMSV3/MasterData/PriceMasterManagement/PriceMasterManagementHeader.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.MasterData
{
public partial class PriceMasterManagementHeader : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTPrice = new DataTable();
private DataTable DTParameterDetail = new DataTable();
private DataTable DTGridViewUser = new DataTable();
private User user;
protected override void OnInit(EventArgs e)
{
if (Session["UserID"] == null)
{
Response.Redirect("~/Account/Logins.aspx");
}
else
{
loadNavBar();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PriceGroup pricegroup = new PriceGroup();
DTPrice = CMSfunction.GetPriceHeaderDataTable(pricegroup);
ASPxGridViewHeader.DataSource = DTPrice;
ASPxGridViewHeader.KeyFieldName = "ITEM ID";
ASPxGridViewHeader.DataBind();
}
SearchBtn_Click();
}
protected void NextBtn_Click(object sender, EventArgs e)
{
if (ASPxGridViewHeader.PageIndex <= ASPxGridViewHeader.PageCount - 1)
{
ASPxGridViewHeader.PageIndex = ASPxGridViewHeader.PageIndex + 1;
}
}
protected void PrevBtn_Click(object sender, EventArgs e)
{
if (ASPxGridViewHeader.PageIndex -1 >= 0)
{
ASPxGridViewHeader.PageIndex = ASPxGridViewHeader.PageIndex - 1;
}
}
protected void LprevBtn_Click(object sender, EventArgs e)
{
ASPxGridViewHeader.PageIndex = 0;
}
protected void LnextBtn_Click(object sender, EventArgs e)
{
ASPxGridViewHeader.PageIndex = ASPxGridViewHeader.PageCount - 1;
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(Session["SiteProfile"].ToString());
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(Session["SiteProfile"].ToString(),
menuGroup.MenuGroupID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuID, null, menuItem.MenuURL);
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxGridViewHeader_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
Session["PriceIDforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "ITEM ID").ToString();
Session["PriceVarforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "VARIANT ID").ToString();
Session["PriceSiteforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "SITE").ToString();
Session["PriceVATforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "VAT").ToString();
Session["PriceforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "PRICE").ToString();
Session["PriceSDateforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "START DATE").ToString();
Session["PriceEDateforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "END DATE").ToString();
if (Page.IsCallback)
ASPxWebControl.RedirectOnCallback("PriceMasterManagementEdit.aspx");
else
Response.Redirect("PriceMasterManagementEdit.aspx");
}
private void SearchBtn_Click()
{
PriceGroup pricegroup = new PriceGroup();
pricegroup.ItemID = !string.IsNullOrWhiteSpace(ITEMIDTXT.Text) ? ITEMIDTXT.Text : "";
pricegroup.VariantID = !string.IsNullOrWhiteSpace(VARIANTTXT.Text) ? VARIANTTXT.Text : "";
pricegroup.Site = !string.IsNullOrWhiteSpace(SITETXT.Text) ? SITETXT.Text : "";
pricegroup.Price = !string.IsNullOrWhiteSpace(PRICETXT.Text) ? PRICETXT.Text : "";
pricegroup.VAT = !string.IsNullOrWhiteSpace(VATTXT.Text) ? VATTXT.Text : "";
pricegroup.Edate = EDATE.Date != DateTime.MinValue ? (DateTime?)EDATE.Date : null;
pricegroup.SDate = SDATE.Date != DateTime.MinValue ? (DateTime?)SDATE.Date : null;
DTPrice = CMSfunction.GetPriceHeaderDataTable(pricegroup);
ASPxGridViewHeader.DataSource = DTPrice;
ASPxGridViewHeader.KeyFieldName = "ITEM ID";
ASPxGridViewHeader.DataBind();
}
protected void SearchBtn_Click(object sender, EventArgs e)
{
SearchBtn_Click();
}
protected void ClearBtn_Click(object sender, EventArgs e)
{
ITEMIDTXT.Text = "";
VARIANTTXT.Text = "";
SITETXT.Text = "";
PRICETXT.Text = "";
VATTXT.Text = "";
EDATE.Value = "";
SDATE.Value = "";
EDATE.Text = "";
SDATE.Text = "";
}
//protected void ASPxButtonEntry_Click(object sender, EventArgs e)
//{
// if (ASPxGridViewHeader.FocusedRowIndex != -1)
// {
// Session["BrandIDforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "ID").ToString();
// Session["BrandDescforUpdate"] = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "BRAND DESC").ToString();
// Response.Redirect("BrandDetailMasterManagement.aspx");
// }
//}
protected void AddBtn_Click(object sender, EventArgs e)
{
Response.Redirect("PriceMasterManagementNew.aspx");
}
protected void DelBtn_Click(object sender, EventArgs e)
{
if (ASPxGridViewHeader.FocusedRowIndex != -1)
{
PriceGroup pricegroup = new PriceGroup();
String ITEMID = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "ITEM ID").ToString();
String VARIANTID = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "VARIANT ID").ToString();
String SITE = ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "SITE").ToString();
DateTime SDATE = Convert.ToDateTime(ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "START DATE").ToString());
OutputMessage message = new OutputMessage();
message = CMSfunction.DeletePrice(ITEMID, VARIANTID, SITE, SDATE);
LabelMessage.ForeColor = message.Code < 0 ? Color.Red : Color.Black;
LabelMessage.Visible = true;
LabelMessage.Text = message.Message;
}
Response.Redirect("PriceMasterManagementHeader.aspx");
}
}
}<file_sep>/KBS.KBS.CMSV3/SalesManagement/SalesInput/SalesDetailInputNew.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
using KBS.KBS.CMSV3.Administration;
namespace KBS.KBS.CMSV3.SalesManagement.SalesInput
{
public partial class SalesDetailInputNew : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTDetailInput = new DataTable();
OutputMessage message = new OutputMessage();
protected override void OnInit(EventArgs e)
{
if (Session["INPUTSALESID"] != null)
{
if (Session["UserID"] == null)
{
Response.Redirect("~/Account/Logins.aspx");
}
else
{
loadNavBar();
}
}
else
{
Response.Redirect("~/Account/Logins.aspx");
}
}
protected void BarcodeCek(object sender, EventArgs e)
{
TransferOrderDetail transferorderdetail = new TransferOrderDetail();
transferorderdetail.BARCODE = BARCODETXT.Text;
transferorderdetail = CMSfunction.GetBarcodeTransferDetail(transferorderdetail);
ITEMTXT.Text = transferorderdetail.ITEMID;
VID.Text = transferorderdetail.VARIANT;
BARCODETXT.Text = transferorderdetail.BARCODE;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["SearchVariantforUpdate"] == null)
{
Session["SearchVariantforUpdate"] = "";
}
if (Session["SearchItemIDforUpdate"] == null)
{
Session["SearchItemIDforUpdate"] = "";
}
if (Session["SearchBarcodeforUpdate"] == null)
{
Session["SearchBarcodeforUpdate"] = "";
}
ITEMTXT.Text = Session["SearchItemIDforUpdate"].ToString();
VID.Text = Session["SearchVariantforUpdate"].ToString();
BARCODETXT.Text = Session["SearchBarcodeforUpdate"].ToString();
}
DTDetailInput = CMSfunction.GetSKULinkBox(Session["DefaultSite"].ToString());
SKUBOX.DataSource = DTDetailInput;
SKUBOX.ValueField = "VALUE";
SKUBOX.ValueType = typeof(string);
SKUBOX.TextField = "DESCRIPTION";
SKUBOX.DataBind();
}
protected void Search(object sender, EventArgs e)
{
Session["SearchRedirect"] = "SalesDetailInputNew.aspx";
Response.Redirect("SearchItemMaster.aspx");
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(Session["SiteProfile"].ToString());
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(Session["SiteProfile"].ToString(),
menuGroup.MenuGroupID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuID, null, menuItem.MenuURL);
}
i++;
}
}
masterNav.DataBind();
}
protected void ClearBtn_Click(object sender, EventArgs e)
{
ITEMTXT.Text = "";
VID.Text = "";
BARCODETXT.Text = "";
QTYTXT.Text = "";
}
protected void BackhomeBtn_Click(object sender, EventArgs e)
{
//Session.Remove("ParamHeaderIDforUpdate");
if (Page.IsCallback)
ASPxWebControl.RedirectOnCallback("SalesDetailInput.aspx");
else
Response.Redirect("SalesDetailInput.aspx");
//Session.Remove("ParamHeaderID");
}
protected void SaveBtn_Click(object sender, EventArgs e)
{
ProcessInsert();
ASPxLabelMessage.ForeColor = message.Code < 0 ? Color.Red : Color.Black;
ASPxLabelMessage.Visible = true;
ASPxLabelMessage.Text = message.Message;
}
protected void ValidateBtn_Click(object sender, EventArgs e)
{
ProcessInsert();
Response.Redirect("SalesDetailInput.aspx");
}
private void ProcessInsert()
{
SalesInputDetail salesinputdetail = new SalesInputDetail();
salesinputdetail.SALESID = Session["INPUTSALESID"].ToString();
salesinputdetail.IID = Session["INPUTIID"].ToString();
salesinputdetail.NOTA = Session["INPUTNOTA"].ToString();
salesinputdetail.RECEIPTID = Session["INPUTRECEIPTID"].ToString();
salesinputdetail.DATE = DateTime.Parse(Session["INPUTDATE"].ToString());
salesinputdetail.SITE = Session["INPUTSITE"].ToString();
salesinputdetail.ITEMID = ITEMTXT.Text;
salesinputdetail.VARIANTID = VID.Text;
salesinputdetail.BARCODE = BARCODETXT.Text;
salesinputdetail.SALESQTY= QTYTXT.Text;
salesinputdetail.SALESPRICE = PRICETXT.Text;
salesinputdetail.COMMENT = COMMENTXT.Text;
salesinputdetail.SKUID = SKUBOX.Value.ToString();
ITEMTXT.Text = "";
VID.Text = "";
BARCODETXT.Text = "";
QTYTXT.Text = "";
PRICETXT.Text = "";
SKUBOX.Text = "";
SKUBOX.Value = 0;
Session["SearchVariantforUpdate"] = "";
Session["SearchItemIDforUpdate"] = "";
Session["SearchBarcodeforUpdate"] = "";
message = CMSfunction.InsertSalesInputDetail(salesinputdetail, Session["UserID"].ToString());
}
}
}<file_sep>/Backup1/KBS.KBS.CMSV3/Administration/ProfileManagement.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.Administration
{
public partial class ProfileManagement : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTProfile = new DataTable();
private DataTable DTSiteAvailable = new DataTable();
private DataTable DTMenuAvailable = new DataTable();
private DataTable DTSiteAssigned = new DataTable();
private DataTable DTMenuAssigned = new DataTable();
private DataTable DTGridViewUser = new DataTable();
private User user;
private String ProfileId;
protected override void OnInit(EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//loadNavBar();
}
protected void Page_Load(object sender, EventArgs e)
{
LabelMessage.Visible = false;
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//DTProfile = CMSfunction.GetAllProfile();
//ASPxListBoxProfileList.DataSource = DTProfile;
//ASPxListBoxProfileList.ValueField = "PROFILEID";
//ASPxListBoxProfileList.ValueType = typeof(string);
//ASPxListBoxProfileList.TextField = "PROFILENAME";
//ASPxListBoxProfileList.DataBind();
//ASPxPageControlProfileManagement.ActiveTabPage = ASPxPageControlProfileManagement.TabPages.FindByName("TabProfileManagementProfileList");
//loadNavBar();
}
protected void ASPxButtonUserManagementInsert_Click(object sender, EventArgs e)
{
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(user.MenuProfile);
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(user.MenuProfile,
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].HeaderStyle.BackColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].HeaderStyle.BorderColor = ColorTranslator.FromHtml("#6076B4");
//masterNav.Groups[i].HeaderStyle.ForeColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxListBoxProfileList_SelectedIndexChanged(object sender, EventArgs e)
{
Session["CurrProfileId"] = ASPxListBoxProfileList.SelectedItem.Value.ToString();
}
protected void ASPxPageControlProfileManagement_ActiveTabChanged(object source, TabControlEventArgs e)
{
if (Session["CurrProfileId"] == null)
{
string message = "Message from server side";
//ScriptManager.RegisterStartupScript(this, GetType(), "Show Modal Popup", "showmodalpopup();", true);
ASPxPageControlProfileManagement.ActiveTabPage =
ASPxPageControlProfileManagement.TabPages.FindByName("TabProfileManagementProfileList");
LabelMessage.Visible = true;
LabelMessage.Text = "Profile is empty, please choose one of the profile";
}
else
{
LabelMessage.Visible = false;
if (ASPxPageControlProfileManagement.ActiveTabPage == ASPxPageControlProfileManagement.TabPages.FindByName("TabProfileManagementProfileList"))
{
}
else if (ASPxPageControlProfileManagement.ActiveTabPage ==
ASPxPageControlProfileManagement.TabPages.FindByName("TabProfileManagementSiteList"))
{
DTSiteAvailable = CMSfunction.GetSiteDataExcludeByProfileID(Session["CurrProfileId"].ToString());
ASPxListBoxSiteAvailableList.DataSource = DTSiteAvailable;
ASPxListBoxSiteAvailableList.ValueField = "SITECODE";
ASPxListBoxSiteAvailableList.ValueType = typeof(string);
ASPxListBoxSiteAvailableList.TextField = "SITENAME";
ASPxListBoxSiteAvailableList.DataBind();
DTSiteAssigned = CMSfunction.GetSiteDataByProfileID(Session["CurrProfileId"].ToString());
ASPxListBoxSiteAssignedList.DataSource = DTSiteAssigned;
ASPxListBoxSiteAssignedList.ValueField = "SITECODE";
ASPxListBoxSiteAssignedList.ValueType = typeof(string);
ASPxListBoxSiteAssignedList.TextField = "SITENAME";
ASPxListBoxSiteAssignedList.DataBind();
}
else
{
DTMenuAvailable = CMSfunction.GetMenuDataExcludeByProfileID(Session["CurrProfileId"].ToString());
ASPxListBoxMenuAvailableList.DataSource = DTMenuAvailable;
ASPxListBoxMenuAvailableList.ValueField = "MENUID";
ASPxListBoxMenuAvailableList.ValueType = typeof(string);
ASPxListBoxMenuAvailableList.TextField = "MENUNAME";
ASPxListBoxMenuAvailableList.DataBind();
DTMenuAssigned = CMSfunction.GetMenuDataByProfileID(Session["CurrProfileId"].ToString());
ASPxListBoxMenuAssignedList.DataSource = DTMenuAssigned;
ASPxListBoxMenuAssignedList.ValueField = "MENUID";
ASPxListBoxMenuAssignedList.ValueType = typeof(string);
ASPxListBoxMenuAssignedList.TextField = "MENUNAME";
ASPxListBoxMenuAssignedList.DataBind();
}
}
}
protected void ASPxButtonSiteAssign_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
if (!string.IsNullOrWhiteSpace(ASPxListBoxSiteAvailableList.SelectedItem.Value.ToString()) ||
!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
CMSfunction.insertSiteByProfileID(ASPxListBoxSiteAvailableList.SelectedItem.Value.ToString(), Session["CurrProfileId"].ToString(), User.Identity.Name);
}
}
}
protected void ASPxButtonSiteUnassign_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
if (!string.IsNullOrWhiteSpace(ASPxListBoxSiteAssignedList.SelectedItem.Value.ToString()) ||
!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
CMSfunction.deleteSiteByProfileID(ASPxListBoxSiteAssignedList.SelectedItem.Value.ToString(), Session["CurrProfileId"].ToString());
}
}
}
protected void ASPxButtonMenuAssign_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
if (!string.IsNullOrWhiteSpace(ASPxListBoxMenuAvailableList.SelectedItem.Value.ToString()) ||
!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
CMSfunction.insertMenuByProfileID(ASPxListBoxMenuAvailableList.SelectedItem.Value.ToString(), Session["CurrProfileId"].ToString(), User.Identity.Name);
}
}
}
protected void ASPxButtonMenuUnassign_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
if (!string.IsNullOrWhiteSpace(ASPxListBoxMenuAssignedList.SelectedItem.Value.ToString()) ||
!string.IsNullOrWhiteSpace(Session["CurrProfileId"].ToString()))
{
CMSfunction.deleteMenuByProfileID(ASPxListBoxMenuAssignedList.SelectedItem.Value.ToString(), Session["CurrProfileId"].ToString());
}
}
}
protected void ASPxButtonNewProfile_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(CMSfunction.GetDuplicateProfileName(ASPxTextBoxNewProfile.Text)))
{
try
{
CMSfunction.insertProfile(ASPxTextBoxNewProfile.Text, User.Identity.Name);
}
catch (Exception ex)
{
logger.Error(ex.Message);
}
}
else
{
}
}
}
}<file_sep>/KBS.KBS.CMSV3/Administration/ParameterManagement.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.Administration
{
public partial class ParameterManagement : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTParameterHeader= new DataTable();
private DataTable DTSite = new DataTable();
private DataTable DTGridViewUser = new DataTable();
private Member user;
protected override void OnInit(EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//loadNavBar();
}
protected void Page_Load(object sender, EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
DTParameterHeader = CMSfunction.GetParameterHeaderData();
ASPxGridViewHeader.DataSource = DTParameterHeader;
ASPxGridViewHeader.KeyFieldName = "ID";
ASPxGridViewHeader.DataBind();
//ASPxComboBoxUserManagementSite.DataSource = DTSite;
//ASPxComboBoxUserManagementSite.ValueField = "SITECODE";
//ASPxComboBoxUserManagementSite.ValueType = typeof(string);
//ASPxComboBoxUserManagementSite.TextField = "SITENAME";
//ASPxComboBoxUserManagementSite.DataBind();
//DTProfile = CMSfunction.GetAllProfile();
//ASPxComboBoxUserManagementProfile.DataSource = DTProfile;
//ASPxComboBoxUserManagementProfile.ValueField = "PROFILEID";
//ASPxComboBoxUserManagementProfile.ValueType = typeof(string);
//ASPxComboBoxUserManagementProfile.TextField = "PROFILENAME";
//ASPxComboBoxUserManagementProfile.DataBind();
//DTGridViewUser = CMSfunction.GetAllUser();
//ASPxGridViewUserManagementUser.DataSource = DTGridViewUser;
//ASPxGridViewUserManagementUser.KeyFieldName = "USERID";
//ASPxGridViewUserManagementUser.DataBind();
//loadNavBar();
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(user.MenuProfile);
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(user.MenuProfile,
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
masterNav.Groups[i].HeaderStyle.BackColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].HeaderStyle.BorderColor = ColorTranslator.FromHtml("#6076B4");
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxGridViewHeader_FocusedRowChanged(object sender, EventArgs e)
{
}
protected void ASPxButtonRefreshTextbox_Click(object sender, EventArgs e)
{
if (ASPxGridViewHeader.FocusedRowIndex != -1)
{
ASPxTextBoxHeaderID.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "ID").ToString();
ASPxTextBoxHeaderName.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "NAME").ToString();
ASPxTextBoxHeaderSClas.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "SCLAS").ToString();
ASPxTextBoxHeaderCopy.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "COPY").ToString();
ASPxTextBoxHeaderComment.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "COMMENT").ToString();
ASPxTextBoxHeaderBlock.Text =
ASPxGridViewHeader.GetRowValues(ASPxGridViewHeader.FocusedRowIndex, "BLOCK").ToString();
//StringBuilder sbScript = new StringBuilder();
//sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
//sbScript.Append("<!--\n");
//sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
//sbScript.Append("// -->\n");
//sbScript.Append("</script>\n");
//this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
}
}
protected void ASPxButtonInsert_Click(object sender, EventArgs e)
{
ParameterHeader parHeader = new ParameterHeader();
parHeader.ID = Int32.Parse(ASPxTextBoxHeaderID.Text);
parHeader.Name = ASPxTextBoxHeaderName.Text;
parHeader.Block = Int32.Parse(ASPxTextBoxHeaderBlock.Text);
parHeader.Comment = ASPxTextBoxHeaderComment.Text;
parHeader.Copy = Int32.Parse(ASPxTextBoxHeaderCopy.Text);
parHeader.SClass = Int32.Parse(ASPxTextBoxHeaderSClas.Text);
OutputMessage outputMsg = new OutputMessage();
outputMsg = CMSfunction.insertParameterHeader(parHeader, "TestUser");
}
}
}<file_sep>/KBS.KBS.CMSV3/MasterData/Assortment/Copy of ItemSearch.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
using KBS.KBS.CMSV3.Administration;
namespace KBS.KBS.CMSV3.MasterData.Assortment
{
public partial class ItemSearch : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTItemVariant = new DataTable();
private DataTable DTItemType = new DataTable();
private DataTable DTBrand = new DataTable();
private string ItemID;
protected override void OnInit(EventArgs e)
{
if (Session["UserID"] == null)
{
Response.Redirect("~/Account/logins.aspx");
}
else if (Session["SearchReturnURL"] == null)
{
Response.Redirect("~/Default.aspx");
}
else
{
loadNavBar();
}
}
protected void Page_Load(object sender, EventArgs e)
{
RefreshDataGridItemVariant();
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(Session["SiteProfile"].ToString());
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(Session["SiteProfile"].ToString(),
menuGroup.MenuGroupID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuID, null, menuItem.MenuURL);
}
i++;
}
}
masterNav.DataBind();
}
protected void SearchBtn_Click(object sender, EventArgs e)
{
RefreshDataGridItemVariant();
}
protected void ClearBtn_Click(object sender, EventArgs e)
{
//ASPxTextBoxHeaderBlock.Text = "";
//ASPxTextBoxHeaderComment.Text = "";
//ASPxTextBoxHeaderCopy.Text = "";
//ASPxTextBoxHeaderID.Text = "";
//ASPxTextBoxHeaderName.Text = "";
//ASPxTextBoxHeaderSClas.Text = "";
}
protected void ASPxGridViewDetail_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
//Session["ItemIDExSearch"] = ASPxGridViewItemVariant.GetRowValues(Convert.ToInt32(e.Parameters), "ITEM ID").ToString();
//Session["VariantIDExSearch"] = ASPxGridViewItemVariant.GetRowValues(Convert.ToInt32(e.Parameters), "VARIANT ID").ToString();
//if (Page.IsCallback)
// ASPxWebControl.RedirectOnCallback(Session["SearchReturnURL"].ToString());
//else
// Response.Redirect(Session["SearchReturnURL"].ToString());
}
protected void BackhomeBtn_Click(object sender, EventArgs e)
{
// Session.Remove("ParamHeaderID");
// if (Page.IsCallback)
// ASPxWebControl.RedirectOnCallback("ParameterManagementHeader.aspx");
// else
// Response.Redirect("ParameterManagementHeader.aspx");
}
protected void AddBtn_Click(object sender, EventArgs e)
{
}
protected void DelBtn_Click(object sender, EventArgs e)
{
}
private void RefreshDataGridItemVariant()
{
ItemVariant itemVariant = new ItemVariant();
itemVariant.ItemIDExternal = !string.IsNullOrWhiteSpace(TextBoxItemIdExternal.Text) ? TextBoxItemIdExternal.Text : "";
itemVariant.VariantIDExternal = !string.IsNullOrWhiteSpace(TextBoxVariantIdExternal.Text) ? TextBoxVariantIdExternal.Text : "";
itemVariant.ShortDesc = !string.IsNullOrWhiteSpace(TextBoxShortDescription.Text) ? TextBoxShortDescription.Text : "";
itemVariant.LongDesc = !string.IsNullOrWhiteSpace(TextBoxLongDescription.Text) ? TextBoxLongDescription.Text : "";
DTItemVariant = CMSfunction.GetItemVarianFiltered(itemVariant);
ASPxGridViewItemVariant.DataSource = DTItemVariant;
ASPxGridViewItemVariant.KeyFieldName = "ITEM ID";
ASPxGridViewItemVariant.DataBind();
}
#region Grid Navigation Button
protected void NextBtn_Click(object sender, EventArgs e)
{
if (ASPxGridViewItemVariant.PageIndex <= ASPxGridViewItemVariant.PageCount - 1)
{
ASPxGridViewItemVariant.PageIndex = ASPxGridViewItemVariant.PageIndex + 1;
}
}
protected void PrevBtn_Click(object sender, EventArgs e)
{
if (ASPxGridViewItemVariant.PageIndex - 1 >= 0)
{
ASPxGridViewItemVariant.PageIndex = ASPxGridViewItemVariant.PageIndex - 1;
}
}
protected void LprevBtn_Click(object sender, EventArgs e)
{
ASPxGridViewItemVariant.PageIndex = 0;
}
protected void LnextBtn_Click(object sender, EventArgs e)
{
ASPxGridViewItemVariant.PageIndex = ASPxGridViewItemVariant.PageCount - 1;
}
#endregion
protected void ASPxButtonSearch_Click(object sender, EventArgs e)
{
if (ASPxGridViewItemVariant.FocusedRowIndex != -1)
{
Session["ItemIDExAssortment"] = ASPxGridViewItemVariant.GetRowValues(ASPxGridViewItemVariant.FocusedRowIndex, "ITEM ID").ToString();
Session["VariantIDExAssortment"] = ASPxGridViewItemVariant.GetRowValues(ASPxGridViewItemVariant.FocusedRowIndex, "VARIANT ID").ToString();
Response.Redirect(Session["SearchReturnURL"].ToString());
}
}
}
}<file_sep>/KBS.KBS.CMSV3/Administration/UserManagement.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.Administration
{
public partial class UserManagement : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTProfile = new DataTable();
private DataTable DTSite = new DataTable();
private DataTable DTGridViewUser = new DataTable();
private Member user;
protected override void OnInit(EventArgs e)
{
user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
loadNavBar();
}
protected void Page_Load(object sender, EventArgs e)
{
user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
DTSite = CMSfunction.GetSiteDataByProfileID(user.MenuProfile);
ASPxComboBoxUserManagementSite.DataSource = DTSite;
ASPxComboBoxUserManagementSite.ValueField = "SITECODE";
ASPxComboBoxUserManagementSite.ValueType = typeof(string);
ASPxComboBoxUserManagementSite.TextField = "SITENAME";
ASPxComboBoxUserManagementSite.DataBind();
DTProfile = CMSfunction.GetAllProfile();
ASPxComboBoxUserManagementProfile.DataSource = DTProfile;
ASPxComboBoxUserManagementProfile.ValueField = "PROFILEID";
ASPxComboBoxUserManagementProfile.ValueType = typeof(string);
ASPxComboBoxUserManagementProfile.TextField = "PROFILENAME";
ASPxComboBoxUserManagementProfile.DataBind();
DTGridViewUser = CMSfunction.GetAllUser();
ASPxGridViewUserManagementUser.DataSource = DTGridViewUser;
ASPxGridViewUserManagementUser.KeyFieldName = "USERID";
ASPxGridViewUserManagementUser.DataBind();
//loadNavBar();
}
protected void ASPxButtonUserManagementInsert_Click(object sender, EventArgs e)
{
ASPxTextBoxUserManagementUserID.Text = String.Empty;
ASPxTextBoxUserManagementUserName.Text = String.Empty;
ASPxTextBoxUserManagementPassword.Text = String.Empty;
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(user.MenuProfile);
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(user.MenuProfile,
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
masterNav.Groups[i].HeaderStyle.BackColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].HeaderStyle.BorderColor = ColorTranslator.FromHtml("#6076B4");
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxGridViewUserManagementUser_FocusedRowChanged(object sender, EventArgs e)
{
}
protected void ASPxButtonUpdate_Click(object sender, EventArgs e)
{
if (ASPxGridViewUserManagementUser.FocusedRowIndex != -1)
{
ASPxTextBoxUserManagementUserID.ReadOnly = true;
ASPxTextBoxUserManagementUserID.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERID").ToString();
ASPxTextBoxUserManagementUserName.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERNAME").ToString();
ASPxTextBoxUserManagementPassword.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "PASSWORD").ToString();
ASPxComboBoxUserManagementProfile.SelectedItem =
ASPxComboBoxUserManagementProfile.Items.FindByText(
ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "PROFILE")
.ToString());
}
}
protected void ASPxButtonDelete_Click(object sender, EventArgs e)
{
if (ASPxGridViewUserManagementUser.FocusedRowIndex != -1)
{
ASPxTextBoxUserManagementUserID.ReadOnly = true;
ASPxTextBoxUserManagementUserID.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERID").ToString();
ASPxTextBoxUserManagementUserName.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERNAME").ToString();
ASPxTextBoxUserManagementPassword.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "<PASSWORD>").ToString();
ASPxComboBoxUserManagementProfile.SelectedItem =
ASPxComboBoxUserManagementProfile.Items.FindByText(
ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "PROFILE")
.ToString());
}
}
}
}<file_sep>/Backup1/KBS.KBS.CMSV3/MasterData/ItemManagement.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.MasterData
{
public partial class ItemManagement : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTBrand = new DataTable();
private DataTable DTSite = new DataTable();
private DataTable DTVariant = new DataTable();
private DataTable DTGridViewItem = new DataTable();
private User user;
private ItemMaster itemMaster;
protected override void OnInit(EventArgs e)
{
// user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
itemMaster = new ItemMaster();
loadNavBar();
}
protected void Page_Load(object sender, EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
////DTSite = CMSfunction.GetSiteDataByProfileID(user.ProfileID);
////ASPxComboBoxUserManagementSite.DataSource = DTSite;
////ASPxComboBoxUserManagementSite.ValueField = "SITECODE";
////ASPxComboBoxUserManagementSite.ValueType = typeof(string);
////ASPxComboBoxUserManagementSite.TextField = "SITENAME";
////ASPxComboBoxUserManagementSite.DataBind();
//DTBrand = CMSfunction.GetAllBrandByProfileID(user.MenuProfile);
//ASPxComboBoxBrand.DataSource = DTBrand;
//ASPxComboBoxBrand.ValueField = "BRANDCODE";
//ASPxComboBoxBrand.ValueType = typeof(string);
//ASPxComboBoxBrand.TextField = "BRANDNAME";
//ASPxComboBoxBrand.DataBind();
//DTVariant = CMSfunction.GetAllVariant(user.MenuProfile);
//ASPxComboBoxVariant.DataSource = DTVariant;
//ASPxComboBoxVariant.ValueField = "VARIANTCODE";
//ASPxComboBoxVariant.ValueType = typeof(string);
//ASPxComboBoxVariant.TextField = "VARIANTNAME";
//ASPxComboBoxVariant.DataBind();
//DTGridViewItem = CMSfunction.GetItemMaster();
//ASPxGridViewItem.DataSource = DTGridViewItem;
//ASPxGridViewItem.KeyFieldName = "ID";
//ASPxGridViewItem.DataBind();
////loadNavBar();
//RefreshDataGrid();
////RefreshInputField();
}
protected void ASPxButtonUserManagementInsert_Click(object sender, EventArgs e)
{
//ASPxTextBoxUserManagementUserID.Text = String.Empty;
// ASPxTextBoxUserManagementUserName.Text = String.Empty;
// ASPxTextBoxUserManagementPassword.Text = String.Empty;
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(user.MenuProfile);
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(user.MenuProfile,
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
masterNav.Groups[i].HeaderStyle.BackColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].HeaderStyle.BorderColor = ColorTranslator.FromHtml("#6076B4");
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxButtonCommit_Click(object sender, EventArgs e)
{
itemMaster = new ItemMaster();
itemMaster.Barcode = ASpXTextBoxBarcode.Text;
itemMaster.ItemID = ASPxTextBoxID.Text;
itemMaster.Name = ASPxTextBoxName.Text;
itemMaster.Size = ASpXTextBoxSize.Text;
itemMaster.Brand = ASPxComboBoxBrand.SelectedItem.Value.ToString();
itemMaster.Status = ASPxComboBoxStatus.SelectedItem.Value.ToString();
itemMaster.Variant = ASPxComboBoxVariant.SelectedItem.Value.ToString();
CMSfunction.insertItemMasterByProfileID(itemMaster, user.MenuProfile, user.Username);
RefreshDataGrid();
RefreshInputField();
}
protected void RefreshDataGrid()
{
DTGridViewItem = CMSfunction.GetItemMaster();
ASPxGridViewItem.DataSource = DTGridViewItem;
ASPxGridViewItem.KeyFieldName = "ID";
ASPxGridViewItem.DataBind();
}
protected void RefreshInputField()
{
ASpXTextBoxBarcode.Text = "";
ASPxComboBoxBrand.SelectedIndex = -1;
ASPxTextBoxID.Text = "";
ASPxTextBoxName.Text = "";
ASpXTextBoxSize.Text = "";
ASPxComboBoxStatus.SelectedIndex = -1;
ASPxComboBoxVariant.SelectedIndex = -1;
}
protected void ASPxButtonUpdate_Click(object sender, EventArgs e)
{
if (ASPxGridViewItem.FocusedRowIndex != -1)
{
itemMaster.ID = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "ID").ToString();
}
itemMaster.Barcode = ASpXTextBoxBarcode.Text;
itemMaster.ItemID = ASPxTextBoxID.Text;
itemMaster.Name = ASPxTextBoxName.Text;
itemMaster.Size = ASpXTextBoxSize.Text;
itemMaster.Brand = ASPxComboBoxBrand.SelectedItem.Value.ToString();
itemMaster.Status = ASPxComboBoxStatus.SelectedItem.Value.ToString();
itemMaster.Variant = ASPxComboBoxVariant.SelectedItem.Value.ToString();
CMSfunction.UpdateItemMaster(itemMaster, user.Username);
RefreshInputField();
RefreshDataGrid();
}
protected void ASPxButtonNew_Click(object sender, EventArgs e)
{
RefreshInputField();
}
protected void ASPxGridViewItem_FocusedRowChanged(object sender, EventArgs e)
{
if (ASPxGridViewItem.FocusedRowIndex != -1)
{
itemMaster = new ItemMaster();
ASpXTextBoxBarcode.Text = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "BARCODE").ToString();
ASpXTextBoxSize.Text = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "SIZE").ToString();
ASPxTextBoxID.Text = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "ITEMID").ToString();
ASPxTextBoxName.Text = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "NAME").ToString();
itemMaster.ID = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "ID").ToString();
ASPxComboBoxBrand.SelectedItem =
ASPxComboBoxBrand.Items.FindByValue(
ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "BRAND").ToString());
ASPxComboBoxStatus.SelectedItem =
ASPxComboBoxStatus.Items.FindByText(
ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "STATUS").ToString());
ASPxComboBoxVariant.SelectedItem =
ASPxComboBoxVariant.Items.FindByValue(
ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "VARIANT").ToString());
}
}
protected void ASPxButtonDelete_Click(object sender, EventArgs e)
{
if (ASPxGridViewItem.FocusedRowIndex != -1)
{
itemMaster.ID = ASPxGridViewItem.GetRowValues(ASPxGridViewItem.FocusedRowIndex, "ID").ToString();
CMSfunction.DeleteItemMasterByID(itemMaster.ID);
}
RefreshInputField();
RefreshDataGrid();
}
}
}<file_sep>/Backup1/KBS.KBS.CMSV3/Administration/SPGSPVManagement.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using KBS.KBS.CMSV3.DATAMODEL;
using KBS.KBS.CMSV3.FUNCTION;
using Menu = KBS.KBS.CMSV3.DATAMODEL.Menu;
namespace KBS.KBS.CMSV3.Administration
{
public partial class SPGSPVManagement : System.Web.UI.Page
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private function CMSfunction = new function();
private DataTable DTSuperior = new DataTable();
private DataTable DTSite = new DataTable();
private DataTable DTGridViewSPGSPV = new DataTable();
private User user;
protected override void OnInit(EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//loadNavBar();
}
protected void Page_Load(object sender, EventArgs e)
{
//user = CMSfunction.SelectUserDataFromUserID(User.Identity.Name);
//DTSite = CMSfunction.GetSiteDataByProfileID(user.MenuProfile);
//ASPxComboBoxSite.DataSource = DTSite;
//ASPxComboBoxSite.ValueField = "SITECODE";
//ASPxComboBoxSite.ValueType = typeof(string);
//ASPxComboBoxSite.TextField = "SITENAME";
//ASPxComboBoxSite.DataBind();
//DTGridViewSPGSPV = CMSfunction.GetAllSPGSPV();
//ASPxGridViewSPGSPV.DataSource = DTGridViewSPGSPV;
//ASPxGridViewSPGSPV.KeyFieldName = "USERID";
//ASPxGridViewSPGSPV.DataBind();
//loadNavBar();
}
private void loadNavBar()
{
List<Menu> listMenuGroup = CMSfunction.SelectMenuGroupByProfileID(user.MenuProfile);
int i = 0;
ASPxSplitter sp = Master.Master.FindControl("ASPxSplitter1").FindControl("Content").FindControl("ContentSplitter") as ASPxSplitter;
ASPxNavBar masterNav = sp.FindControl("ASPxNavBar1") as ASPxNavBar;
if (masterNav != null)
{
foreach (var menuGroup in listMenuGroup)
{
masterNav.Groups.Add(menuGroup.MenuGroupName, menuGroup.MenuGroupNameID);
List<Menu> listMenu = CMSfunction.SelectMenuByProfileIDandMenuGroup(user.MenuProfile,
menuGroup.MenuGroupNameID);
foreach (var menuItem in listMenu)
{
masterNav.Groups[i].Items.Add(menuItem.MenuName, menuItem.MenuNameID, null, menuItem.MenuGroupURL);
masterNav.Groups[i].HeaderStyle.BackColor = ColorTranslator.FromHtml("#6076B4");
masterNav.Groups[i].HeaderStyle.BorderColor = ColorTranslator.FromHtml("#6076B4");
}
i++;
}
}
masterNav.DataBind();
}
protected void ASPxGridViewUserManagementUser_FocusedRowChanged(object sender, EventArgs e)
{
}
protected void ASPxButtonUpdate_Click(object sender, EventArgs e)
{
//if (ASPxGridViewUserManagementUser.FocusedRowIndex != -1)
//{
// ASPxTextBoxUserManagementUserID.ReadOnly = true;
// ASPxTextBoxUserManagementUserID.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERID").ToString();
// ASPxTextBoxUserManagementUserName.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERNAME").ToString();
// ASPxTextBoxUserManagementPassword.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "<PASSWORD>").ToString();
// ASPxComboBoxUserManagementProfile.SelectedItem =
// ASPxComboBoxUserManagementProfile.Items.FindByText(
// ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "PROFILE")
// .ToString());
//}
}
protected void ASPxButtonDelete_Click(object sender, EventArgs e)
{
//if (ASPxGridViewUserManagementUser.FocusedRowIndex != -1)
//{
// ASPxTextBoxUserManagementUserID.ReadOnly = true;
// ASPxTextBoxUserManagementUserID.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERID").ToString();
// ASPxTextBoxUserManagementUserName.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "USERNAME").ToString();
// ASPxTextBoxUserManagementPassword.Text = ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "<PASSWORD>").ToString();
// ASPxComboBoxUserManagementProfile.SelectedItem =
// ASPxComboBoxUserManagementProfile.Items.FindByText(
// ASPxGridViewUserManagementUser.GetRowValues(ASPxGridViewUserManagementUser.FocusedRowIndex, "PROFILE")
// .ToString());
//}
}
protected void ASPxDateEditStart_DateChanged(object sender, EventArgs e)
{
}
protected void ASPxButtonCommit_Click(object sender, EventArgs e)
{
}
protected void ASPxComboBoxPosition_SelectedIndexChanged(object sender, EventArgs e)
{
DTSuperior = CMSfunction.GetSuperiorByPosition(ASPxComboBoxPosition.SelectedItem.Value.ToString());
ASPxComboBoxSuperior.DataSource = DTSuperior;
ASPxComboBoxSuperior.ValueField = "USERNAME";
ASPxComboBoxSuperior.ValueType = typeof(string);
ASPxComboBoxSuperior.TextField = "USERNAME";
ASPxComboBoxSuperior.DataBind();
}
}
} | 5d302ea41685d58e79515f13912131055f8ff37b | [
"C#"
] | 9 | C# | LunggaW/CMSV3Restored | 83b4f0b7b4d6419cb3b774c1acc2278a2ad3a1b0 | cb2f118d07d7e60d721f7501b98bf9a553078960 |
refs/heads/master | <repo_name>hxn8439/BinarySearch<file_sep>/test_lab1.c
//<NAME> 1000538439
// *** command for compiling ***
// gcc test_lab1.c
// a.out < lab1fall19.a.dat
// a.out < lab1fall19.b.dat
// a.out < lab1fall19.c.dat
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX 100
void ranksByMerge(int a, int b, int tableA[], int tableB[], int yRank[], int zRank[]);
int binarySearch(int arr[], int l, int r, int x);
void interactive();
int main (int argc, char *argv[])
{
interactive();
}
void interactive()
{
char raw[1000];
int i=0;
int j;
//int d;
int a, b, c;
int integer[1000];
i=0;
scanf("%d %d %d", &a, &b, &c);
int yRank[a];
int zRank[b];
int tableA[a+2];
int tableB[b+2];
int tablequery[c];
while(fgets(raw, 255, stdin))
{
sscanf(raw,"%d",&integer[i]);
++i;
}
tableA[0] = -99999999;
tableB[0] = -99999999;
j =1;
for(i=1; i<a+1; i++)
{
tableA[j] = integer[i];
++j;
}
j =1;
for(i=a+1; i<(a+b)+1; i++)
{
tableB[j] = integer[i];
++j;
}
j =0;
for(i=a+b+1; i<(a+b+c)+1; i++)
{
tablequery[j] = integer[i];
++j;
}
tableA[a+1]=99999999;
tableB[b+1]=99999999;
ranksByMerge(a, b, tableA, tableB, yRank, zRank);
for(i=0; i<c;i++)
{
if(tablequery[i]!=0)
{
int q = tablequery[i];
int n = sizeof(yRank)/sizeof(yRank[0]);
int n1 = sizeof(zRank)/sizeof(zRank[0]);
int result = binarySearch(yRank, 0, n+7, q);
if(result == -1)
{
int result1 = binarySearch(zRank, 0, n1+7, q);
//finding desired i
int index = q-result1;
int low = 0;
int high = sizeof(tableA)/sizeof(tableA[0]);
while (low <= high)
{
int middle = low + (high - low) / 2;
// Check if x is present at middle, note that index is a true target for rank
if (middle == index)
{
if(tableA[middle] <= tableB[result1] && tableB[result1] < tableA[middle+1])
{
printf("\nlow %d high %d i %d j %d a[%d]=%d b[%d]=%d a[%d]=%d\n", low, high, middle, result1, middle, tableA[middle],result1,tableB[result1],middle+1, tableA[middle+1]);
printf("b[%d]=%d has rank %d", result1,tableB[result1],q);
}
}
// If x greater, ignore left half
if (middle < index)
{
int propindex= q-middle;
if(tableA[middle] <= tableB[propindex] && propindex>0 && tableB[propindex] > tableA[middle+1])
{
printf("\nlow %d high %d i %d j %d a[%d]=%d b[%d]=%d a[%d]=%d", low, high, middle, propindex, middle, tableA[middle],propindex,tableB[propindex],middle+1, tableA[middle+1]);
}
low = middle + 1;
}
// If x is smaller, ignore right half
else
{
int propindex= q-middle;
if(tableA[middle] <= tableB[propindex] && propindex>0 && tableB[propindex] > tableA[middle+1])
{
printf("\nlow %d high %d i %d j %d a[%d]=%d b[%d]=%d a[%d]=%d", low, high, middle, propindex, middle, tableA[middle],propindex,tableB[propindex],middle+1, tableA[middle+1]);
}
high = middle - 1;
}
}
}
else
{
//finding desired j
int index = q-result;
int low = 0;
int high = sizeof(tableB)/sizeof(tableB[0]);
while (low <= high)
{
int middle = low + (high - low) / 2;
// Check if x is present at mid
if (middle == index)
{
if(tableB[middle] < tableA[result] && tableA[result]<= tableB[middle+1])
{
printf("\nlow %d high %d i %d j %d b[%d]=%d a[%d]=%d b[%d]=%d\n", low, high, result, middle, middle, tableB[middle],result,tableA[result],middle+1, tableB[middle+1]);
printf("a[%d]=%d has rank %d", result,tableA[result],q);
}
}
// If x greater, ignore left half
if (middle < index)
{
int propindex= q-middle;
if(tableB[middle] < tableA[propindex] && propindex>0 && tableA[result] > tableB[middle+1] && middle!=0)
{
printf("\nlow %d high %d i %d j %d b[%d]=%d a[%d]=%d b[%d]=%d", low, high, propindex, middle, middle, tableB[middle],propindex,tableA[propindex],middle+1, tableB[middle+1]);
}
low = middle + 1;
}
// If x is smaller, ignore right half
else
{
int propindex= q-middle;
if(tableB[middle] < tableA[propindex] && propindex>0 && tableA[result] > tableB[middle+1] && middle!=0)
{
printf("\nlow %d high %d i %d j %d b[%d]=%d a[%d]=%d b[%d]=%d", low, high, propindex, middle, middle, tableB[middle],propindex,tableA[propindex],middle+1, tableB[middle+1]);
}
high = middle - 1;
}
}
}
}
}
printf("\n");
}
void ranksByMerge(int a, int b, int tableA[], int tableB[], int yRank[], int zRank[])
{
int i,j,k;
i=j=k=1;
while(i<=a && j<=b)
if(tableA[i]<=tableB[j])
yRank[i++]=k++;
else
zRank[j++]=k++;
while(i<=a)
yRank[i++]=k++;
while(j<=b)
zRank[j++]=k++;
}
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
<file_sep>/readme.txt
Goal:
Application of binary searches to determine (in a logarithmic number of steps) which element in a pair of monotonically
increasing sequences has a particular rank.
Requirements:
1.
a. Write a C program to read the two ordered integer input sequences and then a sequence of ranks (queries). For each
rank you should trace the binary search (one line per “probe”) and then indicate which element of which sequence has the
desired rank. The first line of the input file will give m, n, and p where m is the number of elements in the first sequence,
n is the number of elements in the second sequence, and p is the number of ranks (queries) for which binary searches will
be performed. The integer input sequence elements will be in the range 0 . . . 999,999, inclusive. The ranks will be in the
range 1 . . . m + n.
b. The output line for each Θ(1) time probe should include the values of low, high, i, and j. You may also include
other debugging information, such as the result of the probe.
Getting Started:
1. Your program should read the input files via Linux shell redirection (e.g. a.out < lab1.dat on omega.uta.edu,
https://en.wikipedia.org/wiki/Standard_streams). Do NOT prompt for file names! You should
dynamically allocate tables for storing the input. To simplify the binary search code, it is recommended that the first
sequence be stored in subscripts 1 . . . m of its table (a) and that subscripts 0 and m + 1 store “low” and “high” sentinel
values, respectively. The second sequence (b) would be stored similarly.
2. The rank of an element in one of the two sequences is the index of the position that it would occupy if the two sequences
were merged into one monotonically increasing sequence. Should equal-valued elements appear, those in the first
sequence are copied to the output before those in the second sequence. The following (linear-time) code will compute
(and store) the ranks for all elements if stored as suggested in (1.):
void ranksByMerge()
{
int i,j,k;
i=j=k=1;
while (i<=m && j<=n)
if (a[i]<=b[j])
aRank[i++]=k++;
else
bRank[j++]=k++;
while (i<=m)
aRank[i++]=k++;
while (j<=n)
bRank[j++]=k++;
}
These tables of ranks will allow testing your code in an exhaustive fashion, e.g. for all ranks in the range 1 . . . m + n.
The aRank and bRank tables should NOT be computed in the version you submit.
3. For a given rank, the corresponding element could be in either of the two input sequences. If stored as suggested in (1.),
the following (symmetric) observations allow a binary search to be used:
a. If the corresponding element is at a[i], then there must be an index j such that all of the following hold:
1. i + j == rank,
2. b[j] < a[i], and
3. a[i] <= b[j+1]
b. If the corresponding element is at b[j], then there must be an index i such that all of the following hold:
1. i + j == rank,
2. a[i] <= b[j], and
3. b[j] < a[i+1]
So, a probe consists of: a) compute i as the middle of the search range of the first table, b) determine whether 3.a.2 or
3.b.2 applies, and c) determine whether the desired element has been found or make an appropriate adjustment in the
search range.
4. Be careful in initializing the search range of the first table (e.g. low and high). Otherwise, slots outside of the tables
could be referenced.
5. Recursion should not be used.
i a[i] aRank[i]
0 -99999999 0
1 1 2
2 1 3
3 1 4
4 1 5
5 2 7
6 5 12
7 6 14
8 8 17
9 8 18
10 9 22
11 99999999 0
j b[j] bRank[j]
0 -99999999 0
1 0 1
2 1 6
3 2 8
4 3 9
5 4 10
6 4 11
7 5 13
8 6 15
9 7 16
10 8 19
11 8 20
12 8 21
13 9 23
14 9 24
15 9 25
16 99999999 0
// *** command for compiling ***
// gcc test_lab1.c
// a.out < lab1.dat
// a.out < lab1-2.dat
// a.out < lab1-3.dat
| 9230c76a8a5b865046549f60a7d1598a297fab16 | [
"C",
"Text"
] | 2 | C | hxn8439/BinarySearch | 44a10298db125aef71790d01d4ce5f5c41f3ec53 | bca6050515db9793bfec59b2bb7036d9ab4603d1 |
refs/heads/main | <repo_name>Krabator/ToME-Fr<file_sep>/mod-boot.lua
------------------------------------------------
section "mod-boot/data/birth/descriptors.lua"
t("Destroyer", "Destructeur", "birth descriptor name")
t("Acid-maniac", "Maniaque de l'acide", "birth descriptor name")
-- texte non traduit
--[==[
t("base", "base", "birth descriptor name")
--]==]
------------------------------------------------
section "mod-boot/data/damage_types.lua"
t("Kill!", "Tue!", "_t")
------------------------------------------------
section "mod-boot/data/general/grids/basic.lua"
t("floor", "sol", "entity type")
t("floor", "sol", "entity subtype")
t("floor", "sol", "entity name")
t("wall", "mur", "entity type")
t("wall", "mur", "entity name")
t("door", "porte", "entity name")
t("open door", "porte ouverte", "entity name")
------------------------------------------------
section "mod-boot/data/general/grids/forest.lua"
t("floor", "sol", "entity type")
t("grass", "herbe", "entity subtype")
t("grass", "herbe", "entity name")
t("wall", "mur", "entity type")
t("tree", "arbre", "entity name")
t("flower", "fleur", "entity name")
------------------------------------------------
section "mod-boot/data/general/grids/underground.lua"
t("wall", "mur", "entity type")
t("underground", "souterrain", "entity subtype")
t("crystals", "cristaux", "entity name")
t("floor", "sol", "entity type")
t("floor", "sol", "entity name")
------------------------------------------------
section "mod-boot/data/general/grids/water.lua"
t("floor", "sol", "entity type")
t("water", "eau", "entity subtype")
t("deep water", "eau profonde", "entity name")
------------------------------------------------
section "mod-boot/data/general/npcs/canine.lua"
t("canine", "canin", "entity subtype")
t("wolf", "loup", "entity name")
t("Lean, mean, and shaggy, it stares at you with hungry eyes.", "Maigre, méchant et grincheux, il vous regarde avec des yeux affamés.", "_t")
t("white wolf", "loup blanc", "entity name")
t("A large and muscled wolf from the northern wastes. Its breath is cold and icy and its fur coated in frost.", "Un grand loup musclé provenant des friches du nord. Son souffle est froid et glacé, et sa fourrure est recouverte de givre.", "_t")
t("warg", "loup géant", "entity name")
t("It is a large wolf with eyes full of cunning.", "C'est un grand loup avec des yeux pleins de ruse.", "_t")
t("fox", "renard", "entity name")
t("The quick brown fox jumps over the lazy dog.", "Le rapide renard brun saute par-dessus le chien paresseux.", "_t")
-- texte non traduit
--[==[
t("animal", "animal", "entity type")
--]==]
------------------------------------------------
section "mod-boot/data/general/npcs/skeleton.lua"
t("undead", "mort-vivant", "entity type")
t("skeleton", "squelette", "entity subtype")
t("degenerated skeleton warrior", "guerrier squelette dégénéré", "entity name")
t("skeleton warrior", "guerrier squelette", "entity name")
t("skeleton mage", "mage squelette", "entity name")
t("armoured skeleton warrior", "guerrier squelette en armure", "entity name")
------------------------------------------------
section "mod-boot/data/general/npcs/troll.lua"
t("giant", "géant", "entity type")
t("forest troll", "troll des forêts", "entity name")
t("Green-skinned and ugly, this massive humanoid glares at you, clenching wart-covered green fists.", "Très laid, cet humanoïde massif à peau verte vous regarde, serrant ses poings verts couverts de verrues.", "_t")
t("stone troll", "troll de pierre", "entity name")
t("A giant troll with scabrous black skin. With a shudder, you notice the belt of dwarf skulls around his massive waist.", "Un troll géant à la peau noire et scabreuse. Après un frisson, vous remarquez la ceinture de crânes nains autour de sa taille massive.", "_t")
t("cave troll", "troll des cavernes", "entity name")
t("This huge troll wields a massive spear and has a disturbingly intelligent look in its piggy eyes.", "Cet énorme troll manie une lance massive et a un regard désagréablement intelligent dans ses yeux de cochon.", "_t")
t("mountain troll", "troll des montagnes", "entity name")
t("A large and athletic troll with an extremely tough and warty hide.", "Un grand troll athlétique à la peau extrêmement dure et verruqueuse.", "_t")
t("mountain troll thunderer", "troll-tonnerre des montagnes", "entity name")
-- texte non traduit
--[==[
t("troll", "troll", "entity subtype")
--]==]
------------------------------------------------
section "mod-boot/data/talents.lua"
t("misc", "divers", "talent category")
t("Kick", "Coup de pied", "talent name")
t("Acid Spray", "Vaporisation d'acide", "talent name")
t("Manathrust", "Poussée de mana", "talent name")
t("Flame", "Flamme", "talent name")
t("Fireflash", "Eclat de feu", "talent name")
t("Lightning", "Foudre", "talent name")
t("Sunshield", "Bouclier étincelant", "talent name")
t("Flameshock", "Choc de flammes", "talent name")
------------------------------------------------
section "mod-boot/data/timed_effects.lua"
t("Burning from acid", "Brûle par l'acide", "_t")
t("#Target# is covered in acid!", "#Target# est recouvert d'acide!", "_t")
t("+Acid", "+Acide", "_t")
t("#Target# is free from the acid.", "#Target# n'est plus recouvert d'acide.", "_t")
t("-Acid", "-Acide", "_t")
t("Sunshield", "Bouclier étincelant", "_t")
------------------------------------------------
section "mod-boot/data/zones/dungeon/zone.lua"
t("Forest", "Forêt", "_t")
------------------------------------------------
section "mod-boot/mod/class/Game.lua"
t("Welcome to T-Engine and the Tales of Maj'Eyal", "Bienvenue sur le T-Engine et Tales of Maj'Eyal", "_t")
t([[#GOLD#"Tales of Maj'Eyal"#WHITE# is the main game, you can also install more addons or modules by going to https://te4.org/
When inside a module remember you can press Escape to bring up a menu to change keybindings, resolution and other module specific options.
Remember that in most roguelikes death is usually permanent so be careful!
Now go and have some fun!]], [[#GOLD#"Tales of Maj'Eyal"#WHITE# est le jeu principal, vous pouvez également installer d'autres addons ou modules en allant sur https://te4.org/
Lorsque vous vous trouvez dans un module, n'oubliez pas que vous pouvez appuyer sur la touche Echap pour faire apparaître un menu permettant de modifier les raccourcis clavier, la résolution et d'autres options spécifiques au module.
N'oubliez pas que dans la plupart des roguelikes, la mort est généralement permanente, alors faites attention!
Maintenant, partez et allez vous amuser!]], "_t")
t("Upgrade to 1.0.5", "Mise à jour vers la 1.0.5", "_t")
t([[The way the engine manages saving has been reworked for v1.0.5.
The background saves should no longer lag horribly and as such it is highly recommended that you use the option. The upgrade turned it on for you.
For the same reason the save per level option should not be used unless you have severe memory problems. The upgrade turned it off for you.
]], [[La façon dont le moteur gère les sauvegardes a été retravaillée pour la v1.0.5.
Les sauvegardes en arrière-plan ne devraient plus être aussi lentes qu'auparavant et il est donc fortement recommandé d'utiliser cette option. La mise à jour l'a activée pour vous.
Pour la même raison, l'option de sauvegarde par niveau ne devrait pas être utilisée, sauf si vous avez de graves problèmes de mémoire. La mise à jour l'a désactivée pour vous.
]], "_t")
t("Safe Mode", "Mode sans échec", "_t")
t([[Oops! Either you activated safe mode manually or the game detected it did not start correctly last time and thus you are in #LIGHT_GREEN#safe mode#WHITE#.
Safe Mode disabled all graphical options and sets a low FPS. It is not advisable to play this way (as it will be very painful and ugly).
Please go to the Video Options and try enabling/disabling options and then restarting until you do not get this message.
A usual problem is shaders and thus should be your first target to disable.]], [[Oups! Soit vous avez activé le mode sans échec manuellement, soit le jeu a détecté qu'il ne démarrait pas correctement la dernière fois et vous êtes donc en #LIGHT_GREEN#mode sans échec#WHITE#.
Le mode sans échec a désactivé toutes les options graphiques et fixe un taux de rafraichissement réduit. Il n'est pas conseillé de jouer de cette manière (car cela sera très douloureux et très laid).
Veuillez vous rendre dans les options vidéo et essayer d'activer/désactiver les options, puis redémarrer jusqu'à ce que vous ne receviez plus ce message.
Les shaders sont généralement la source des problèmes et devraient donc être les options à désactiver en priorité.]], "_t")
t("Duplicate Addon", "Addon en double", "_t")
t([[Oops! It seems like you have the same addon/dlc installed twice.
This is unsupported and would make many things explode. Please remove one of the copies.
Addon name: #YELLOW#%s#LAST#
Check out the following folder on your computer:
%s
%s
]], [[Oups! Il semble que vous ayez le même addon/dlc installé deux fois.
Ce n'est pas supporté et cela va faire planter beaucoup de choses. Veuillez supprimer l'une des copies.
Nom de l'addon: #YELLOW#%s#LAST#
Consultez le dossier suivant sur votre ordinateur:
%s
%s
]], "_t")
t("Updating addon: #LIGHT_GREEN#%s", "Mise à jour de l'addon: #LIGHT_GREEN#%s", "tformat")
t("Quit", "Quitter", "_t")
t("Really exit T-Engine/ToME?", "Vraiment quitter T-Engine/ToME?", "_t")
t("Continue", "Continuer", "_t")
t([[Welcome to #LIGHT_GREEN#Tales of Maj'Eyal#LAST#!
Before you can start dying in many innovative ways we need to ask you about online play.
This is a #{bold}#single player game#{normal}# but it also features many online features to enhance your gameplay and connect you to the community:
* Play from several computers without having to copy unlocks and achievements.
* Talk ingame to other fellow players, ask for advice, share your most memorable moments...
* Keep track of your kill count, deaths, most played classes...
* Cool statistics for to help sharpen your gameplay style
* Install official expansions and third-party addons directly from the game, hassle-free
* Access your purchaser / donator bonuses if you have bought the game or donated on https://te4.org/
* Help the game developers balance and refine the game
You will also have a user page on #LIGHT_BLUE#https://te4.org/#LAST# to show off to your friends.
This is all optional, you are not forced to use this feature at all, but the developer would thank you if you did as it will make balancing easier.]], [[Bienvenue sur #LIGHT_GREEN#Tales of Maj'Eyal#LAST#!
Avant que vous puissiez commencer à mourir de nombreuses façons incroyablement innovantes, nous devons vous interroger sur le jeu en ligne.
Il s'agit d'un #{bold}#jeu solo#{normal}# mais il comporte également de nombreuses fonctionnalités en ligne pour améliorer votre gameplay et vous connecter à la communauté:
* Jouer depuis plusieurs ordinateurs sans avoir à copier les choses déblocables et les succès.
* Parler en jeu avec d'autres joueurs, demander des conseils, partager vos moments les plus mémorables...
* Garder une trace de votre nombre de morts, des décès, des classes les plus jouées...
* Des statistiques intéressantes pour vous aider à affiner votre style de jeu
* Installer les extensions officielles et les addons tiers directement à partir du jeu, sans problème
* Accéder à vos bonus d'acheteur / de donateur si vous avez acheté le jeu ou fait un don sur https://te4.org/
* Aider les développeurs du jeux à équilibrer et à affiner le jeu
Vous aurez également une page utilisateur sur #LIGHT_BLUE#https://te4.org/#LAST# pour frimer devant vos amis.
Tout cela est facultatif, vous n'êtes pas du tout obligé d'utiliser cette fonctionnalité, mais le développeur vous en remerciera car cela facilitera l'équilibrage.]], "_t")
t("Please wait...", "Attendez s'il vous plait...", "_t")
t("Profile logged in!", "Profil connecté!", "_t")
t("Your online profile is now active. Have fun!", "Votre profil en ligne est maintenant activé. Amusez vous bien!", "_t")
t("Login failed!", "Connexion échouée!", "_t")
t("Check your login and password or try again in in a few moments.", "Vérifier vos identifiant et mot de passe et réessayer dans quelques instants.", "_t")
t("Registering...", "Enregistrement...", "_t")
t("Registering on https://te4.org/, please wait...", "Enregistrement sur https://te4.org/, attendez s'il vous plait...", "_t")
t("Logged in!", "Connecté!", "_t")
t("Profile created!", "Profil créé!", "_t")
t("Profile creation failed!", "La création de profil a échouée!", "_t")
t("Creation failed: %s (you may also register on https://te4.org/)", "La création a échouée: %s (vous pouvez aussi vous enregistrer sur https://te4.org/)", "tformat")
t("Try again in in a few moments, or try online at https://te4.org/", "Essayez de nouveau dans quelques instants, ou essayez en ligne sur https://te4.org/", "_t")
-- nouveau texte
--[==[
t("Logging in...", "Logging in...", "_t")
--]==]
-- texte non traduit
--[==[
t("Message", "Message", "_t")
--]==]
-- ancien texte traduit
t("Login in...", "Connexion...", "_t")
------------------------------------------------
section "mod-boot/mod/class/Player.lua"
t("%s available", "%s disponible", "tformat")
t("#00ff00#Talent %s is ready to use.", "#00ff00#Le talent %s est prêt a être utilisé.", "log")
t("LEVEL UP!", "NIVEAU SUPERIEUR!", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/Addons.lua"
t("Configure Addons", "Configuration des Addons", "_t")
t("You can get new addons at #LIGHT_BLUE##{underline}#Te4.org Addons#{normal}#", "Vous pouvez obtenir de nouveaux addons sur: #LIGHT_BLUE##{underline}#Te4.org Addons#{normal}#", "_t")
t(" and #LIGHT_BLUE##{underline}#Te4.org DLCs#{normal}#", " et #LIGHT_BLUE##{underline}#Te4.org DLCs#{normal}#", "_t")
t("You can get new addons on #LIGHT_BLUE##{underline}#Steam Workshop#{normal}#", "Vous pouvez obtenir de nouveaux addons sur: #LIGHT_BLUE##{underline}#Steam Workshop#{normal}#", "_t")
t(", #LIGHT_BLUE##{underline}#Te4.org Addons#{normal}#", ", #LIGHT_BLUE##{underline}#Addons de Te4.org#{normal}#", "_t")
t("Show incompatible", "Montrer les incompatibles", "_t")
t("Auto-update on start", "Mise à jour automatique au démarrage", "_t")
t("Game Module", "Module de jeu", "_t")
t("Active", "Activé", "_t")
t("#GREY#Developer tool", "#GREY#Outil de développement", "_t")
t("#LIGHT_RED#Donator Status: Disabled", "#LIGHT_RED#Statut de donateur: Désactivé", "_t")
t("#LIGHT_GREEN#Manual: Active", "#LIGHT_GREEN#Manuel: Activé", "_t")
t("#LIGHT_RED#Manual: Disabled", "#LIGHT_RED#Manuel: Désactivé", "_t")
t("#LIGHT_GREEN#Auto: Active", "#LIGHT_GREEN#Auto: Activé", "_t")
t("Addon Version", "Version de l'addon", "_t")
t("Game Version", "Version du jeu", "_t")
-- texte non traduit
--[==[
t("Version", "Version", "_t")
t("Addon", "Addon", "_t")
t("#LIGHT_RED#Auto: Incompatible", "#LIGHT_RED#Auto: Incompatible", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/dialogs/Credits.lua"
t("Project Lead", "Chef de projet", "_t")
t("Lead Coder", "Développeur principal", "_t")
t("World Builders", "Concepteurs de monde", "_t")
t("Graphic Artists", "Artistes graphique", "_t")
t("Expert Shaders Design", "Expert en conception de Shaders", "_t")
t("Soundtracks", "Bande son", "_t")
t("Sound Designer", "Concepteur sonore", "_t")
t("Lore Creation and Writing", "Création et écriture du Lore", "_t")
t("Community Managers", "Community manager", "_t")
t("Text Editors", "Editeurs de texte", "_t")
t("The Community", "La Communauté", "_t")
t("Others", "Autres", "_t")
-- texte non traduit
--[==[
t("Code Heroes", "Code Heroes", "_t")
t("Chinese Translation Lead", "Chinese Translation Lead", "_t")
t("Chinese Translators", "Chinese Translators", "_t")
t("Korean Translation", "Korean Translation", "_t")
t("Japanese Translation", "Japanese Translation", "_t")
--]==]
-- ancien texte traduit
t("Code Helpers", "Aides au code", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/FirstRun.lua"
t("Welcome to Tales of Maj'Eyal", "Bienvenue sur Tales of Maj'Eyal", "_t")
t("Register now!", "Enregistrez vous maintenant!", "_t")
t("Login existing account", "Connexion à un compte existant", "_t")
t("Maybe later", "Peut-être plus tard", "_t")
t("#RED#Disable all online features", "#RED#Désactiver toutes les fonctions en ligne", "_t")
t("Disable all connectivity", "Désactiver toute connectivité", "_t")
t([[You are about to disable all connectivity to the network.
This includes, but is not limited to:
- Player profiles: You will not be able to login, register
- Characters vault: You will not be able to upload any character to the online vault to show your glory
- Item's Vault: You will not be able to access the online item's vault, this includes both storing and retrieving items.
- Ingame chat: The ingame chat requires to connect to the server to talk to other players, this will not be possible.
- Purchaser / Donator benefits: The base game being free, the only way to give donators their bonuses fairly is to check their online profile. This will thus be disabled.
- Easy addons downloading & installation: You will not be able to see ingame the list of available addons, nor to one-click install them. You may still do so manually.
- Version checks: Addons will not be checked for new versions.
- Discord: If you are a Discord user, Rich Presence integration will also be disabled by this setting.
- Ingame game news: The main menu will stop showing you info about new updates to the game.
#{bold}##CRIMSON#This is an extremely restrictive setting. It is recommended you only activate it if you have no other choice as it will remove many fun and acclaimed features.#{normal}#
If you disable this option you can always re-activate it in the Online category of the Game Options menu later on.]], [[Vous êtes sur le point de désactiver toute connectivité au réseau.
Cela inclut, mais n'est pas limité à:
- Les profils de joueur: Vous ne pourrez pas vous connecter, vous inscrire
- Chambre forte des personnages: Vous ne pourrez pas télécharger de personnage dans la chambre forte en ligne pour montrer votre gloire
- Coffre-fort des objets: vous ne pourrez pas accéder au coffre-fort des objets en ligne, ce qui inclut le stockage et la récupération des objets.
- Tchat en jeu: Le tchat en jeu nécessite de se connecter au serveur pour parler aux autres joueurs, ce qui ne sera pas possible.
- Avantages d'acheteur / de donateur: Le jeu de base étant gratuit, la seule façon de donner aux donateurs leurs bonus de manière équitable est de vérifier leur profil en ligne. Ceux-ci seront donc désactivés.
- Téléchargement et installation faciles des addons: Vous ne pourrez pas voir dans le jeu la liste des addons disponibles, ni les installer en un clic. Vous pouvez toujours le faire manuellement.
- Vérification des versions: Les addons ne seront pas vérifiés si il y a de nouvelles versions.
- Discord: Si vous êtes un utilisateur de Discord, la fonctionnalité Discord "Rich Presence" sera également désactivée par ce paramètre.
- Nouvelles du jeu en jeu: Le menu principal cessera de vous montrer des informations sur les nouvelles mises à jour du jeu.
#{bold}##CRIMSON#Il s'agit d'un paramètre extrêmement restrictif. Il est recommandé de ne l'activer que si vous n'avez pas d'autre choix, car il supprimera de nombreuses fonctionnalités amusantes et très appréciées.#{normal}#
Si vous désactivez cette option, vous pouvez toujours la réactiver plus tard dans la catégorie En ligne du menu Options du jeu.]], "_t")
t("Cancel", "Annuler", "_t")
t("#RED#Disable all!", "#RED#Tout désactiver!", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/LoadGame.lua"
t("Load Game", "Charger une partie", "_t")
t("Show older versions", "Montrer les anciennes versions", "_t")
t("Ignore unloadable addons", "Ignorer les addons non chargeable", "_t")
t(" Play! ", " Jouer! ", "_t")
t("Delete", "Supprimer", "_t")
t([[#{bold}##GOLD#%s: %s#WHITE##{normal}#
Game version: %d.%d.%d
Requires addons: %s
%s]], [[#{bold}##GOLD#%s: %s#WHITE##{normal}#
Version du jeu: %d.%d.%d
Addons requis: %s
%s]], "tformat")
t("You can simply grab an older version of the game from where you downloaded it.", "Vous pouvez simplement prendre une ancienne version du jeu là où vous l'avez téléchargée.", "_t")
t("You can downgrade the version by selecting it in the Steam's \"Beta\" properties of the game.", "Vous pouvez rétrograder la version du jeu en la sélectionnant dans les propriétés \"Beta\" du jeu sur Steam", "_t")
t("Original game version not found", "Version original du jeu non trouvée", "_t")
t([[This savefile was created with game version %s. You can try loading it with the current version if you wish but it is recommended you play it with the old version to ensure compatibility
%s]], [[Ce fichier de sauvegarde a été créé avec la version %s du jeu. Vous pouvez essayer de le charger avec la version actuelle si vous le souhaitez, mais il est recommandé de jouer avec l'ancienne version pour assurer la compatibilité
%s]], "tformat")
t("Cancel", "Annuler", "_t")
t("Run with newer version", "Lancer avec la nouvelle version", "_t")
t("Developer Mode", "Mode développeur", "_t")
t("#LIGHT_RED#WARNING: #LAST#Loading a savefile while in developer mode will permanently invalidate it. Proceed?", "#LIGHT_RED#ATTENTION: #LAST#Charger une sauvegarde en mode développeur l'invalidera de façon permanente. Poursuivre?", "_t")
t("Load anyway", "Charger quand même", "_t")
t("Delete savefile", "Supprimer la sauvegarde", "_t")
t("Really delete #{bold}##GOLD#%s#WHITE##{normal}#", "Vraiment supprimer #{bold}##GOLD#%s#WHITE##{normal}#", "tformat")
t("Old game data", "Anciennes données du jeu", "_t")
t("No data available for this game version.", "Pas de données disponibles pour cette version du jeu", "_t")
t("Downloading old game data: #LIGHT_GREEN#", "Téléchargement d'anciennes données du jeu: #LIGHT_GREEN#", "_t")
t("Old game data for %s correctly installed. You can now play.", "Les anciennes données pour %s sont correctement installées. Maintenant vous pouvez jouer.", "tformat")
t("Failed to install.", "Installation échouée", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/MainMenu.lua"
t("Main Menu", "Menu principal", "_t")
t("New Game", "Nouvelle partie", "_t")
t("Load Game", "Charger une partie", "_t")
t("Game Options", "Options de jeu", "_t")
t("Credits", "Crédits", "_t")
t("Exit", "Quitter", "_t")
t("Reboot", "Relancer le jeu", "_t")
t("Disable animated background", "Désactiver les animations en arrière-plan", "_t")
t("#{bold}##B9E100#T-Engine4 version: %d.%d.%d", "#{bold}##B9E100#T-Engine4 :%d.%d.%d", "tformat")
t([[#{bold}##GOLD#Ashes of Urh'Rok - Expansion#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#Many in Maj'Eyal have heard of "demons", sadistic creatures who appear seemingly from nowhere, leaving a trail of suffering and destruction wherever they go.#{normal}##LAST#
#{bold}#Features#{normal}#:
#LIGHT_UMBER#New class:#WHITE# Doombringers. These avatars of demonic destruction charge into battle with massive two-handed weapons, cutting swaths of firey devastation through hordes of opponents. Armed with flame magic and demonic strength, they delight in fighting against overwhelming odds
#LIGHT_UMBER#New class:#WHITE# Demonologists. Bearing a shield and the magic of the Spellblaze itself, these melee-fighting casters can grow demonic seeds from their fallen enemies. Imbue these seeds onto your items to gain a wide array of new talents and passive benefits, and summon the demons within them to fight!
#LIGHT_UMBER#New race:#WHITE# Doomelves. Shalore who've taken to the demonic alterations especially well, corrupting their typical abilities into a darker form.
#LIGHT_UMBER#New artifacts, lore, zones, events...#WHITE# For your demonic delight!
]], [[#{bold}##GOLD#Ashes of Urh'Rok - Extension#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#Beaucoup de personnes dans Maj'Eyal ont entendu parler des "démons", des créatures sadiques qui apparaissent apparemment de nulle part, laissant une traînée de souffrance et de destruction partout où elles vont.#{normal}##DERNIER#
#{bold}#Modifications#{normal}#:
#LIGHT_UMBER#Nouvelle classe:#WHITE# Avatar de la ruine. Ces avatars de la destruction démoniaque se lancent dans la bataille avec de massives armes à deux mains, faisant des ravages par le feu en découpant des hordes d'adversaires. Armés de la magie des flammes et de leur force démoniaque, ils prennent plaisir à se battre contre des obstacles insurmontables
#LIGHT_UMBER#Nouvelle classe:#WHITE# Démonologues. Utilisant un bouclier et la magie de la Brûlure magique elle-même, ces combattants au corps-à-corps peuvent faire pousser des graines démoniaques du cadavres de leurs ennemis. Incorporez ces graines à vos objets pour obtenir un large éventail de nouveaux talents et d'avantages passifs, et invoquez les démons qui s'y trouvent pour combattre!
#LIGHT_UMBER#Nouvelle race:#WHITE# Elfes de la ruine. Des Shalore qui ont particulièrement bien pris les altérations démoniaques, corrompant leurs capacités typiques en une forme plus sombre.
#LIGHT_UMBER#Nouveaux artefacts, histoires, zones, événements...#WHITE# Pour votre plaisir démoniaque!
]], "_t")
t("#LIGHT_GREEN#Installed", "#LIGHT_GREEN#Installé", "_t")
t("#YELLOW#Not installed - Click to download / purchase", "#YELLOW#Non installé - Cliquez pour télécharger / acheter", "_t")
t([[#{bold}##GOLD#Embers of Rage - Expansion#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#One year has passed since the one the Orcs call the "Scourge from the West" came and single-handedly crushed the Orc Prides of Grushnak, Vor, Gorbat, and Rak'Shor. The Allied Kingdoms, now linked by farportal to their distant, long-lost Sunwall allies, have helped them conquer most of Var'Eyal. The few remnants of the ravaged Prides are caged... but one Pride remains.#{normal}##LAST#
#{bold}#Features#{normal}#:
#LIGHT_UMBER#A whole new campaign:#WHITE# Set one year after the events of the main game, the final destiny of the Orc Prides is up to you. Discover the Far East like you never knew it.
#LIGHT_UMBER#New classes:#WHITE# Sawbutchers, Gunslingers, Psyshots, Annihilators and Technomanchers. Harness the power of steam to power deadly contraptions to lay waste to all those that oppose the Pride!
#LIGHT_UMBER#New races:#WHITE# Orcs, Yetis, Whitehooves. Discover the orcs and their unlikely 'allies' as you try to save your Pride from the disasters caused by the one you call 'The Scourge from the West'.
#LIGHT_UMBER#Tinker system:#WHITE# Augment your items with powerful crafted tinkers. Attach rockets to your boots, gripping systems to your gloves and many more.
#LIGHT_UMBER#Salves:#WHITE# Bound to the tinker system, create powerful medical salves to inject into your skin, replacing the infusions§runes system.
#LIGHT_UMBER#A ton#WHITE# of artifacts, lore, zones, events...
]], [[#{bold}##GOLD#Embers of Rage - Extension#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#Une année s'est écoulée depuis que celui que les Orcs appellent le "Fléau de l'Ouest" est venu écraser à lui seul les Clans Orcs de Grushnak, Vor, Gorbat et Rak'Shor. Les royaumes alliés, désormais liés par un portail lointain à leurs alliés, depuis longtemps perdu, du Mur du Soleil, les ont aidés à conquérir la plus grande partie du Var'Eyal. Les quelques restes des Clans ravagées sont en cage... mais un Clan demeure.#{normal}##LAST#
#{bold}#Modifications#{normal}#:
#LIGHT_UMBER#Une toute nouvelle campagne:#WHITE# Se déroulant un an après les événements du jeu principal, le destin final des Clans Orcs dépend de vous. Découvrez l'Extrême Orient comme vous ne l'avez jamais connu.
#LIGHT_UMBER#Nouvelles classes:#WHITE# Démembreur, Flingueur, Tireur psychique, Annihilateurs et Technomanciens. Exploitez la puissance de la vapeur pour faire fonctionner des engins mortels afin de mettre à sac tous ceux qui s'opposent au Clan!
#LIGHT_UMBER#Nouvelles races:#WHITE# Orcs, Yétis, Sabots blancs. Découvrez les orcs et leurs improbables 'alliés' alors que vous essayez de sauver votre Clan des désastres causés par celui que vous appelez 'le fléau de l'Ouest'.
#LIGHT_UMBER#Système de bricolage:#WHITE# Augmentez vos objets avec de puissantes améliorations. Attachez des fusées à vos bottes, des systèmes de préhension à vos gants et bien d'autres choses encore.
#LIGHT_UMBER#Salves:#WHITE# Lié au système de bricolage, créez de puissantes pommades médicales à injecter sous votre peau, en remplacement du système d'infusion§runes.
#LIGHT_UMBER#Une tonne#WHITE# d'artefacts, d'histoires, de zones, d'événements...
]], "_t")
t([[#{bold}##GOLD#Forgotten Cults - Expansion#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#Not all adventurers seek fortune, not all that defend the world have good deeds in mind. Lately the number of sightings of horrors have grown tremendously. People wander off the beaten paths only to be found years later, horribly mutated and partly insane, if they are found at all. It is becoming evident something is stirring deep below Maj'Eyal. That something is you.#{normal}##LAST#
#{bold}#Features#{normal}#:
#LIGHT_UMBER#New class:#WHITE# Writhing Ones. Give in to the corrupting forces and turn yourself gradually into an horror, summon horrors to do your bidding, shed your skin and melt your face to assault your foes. With your arm already turned into a tentacle, what creature can stop you?
#LIGHT_UMBER#New class:#WHITE# Cultists of Entropy. Using its insanity and control of entropic forces to unravel the normal laws of physic this caster class can turn healing into attacks and call upon the forces of the void to reduce its foes to dust.
#LIGHT_UMBER#New race:#WHITE# Drems. A corrupt subrace of dwarves, that somehow managed to keep a shred of sanity to not fully devolve into mindless horrors. They can enter a frenzy and even learn to summon horrors.
#LIGHT_UMBER#New race:#WHITE# Krogs. Ogres transformed by the very thing that should kill them. Their powerful attacks can stun their foes and they are so strong they can dual wield any one handed weapons.
#LIGHT_UMBER#Many new zones:#WHITE# Explore the Scourge Pits, fight your way out of a giant worm (don't ask how you get *in*), discover the wonders of the Occult Egress and many more strange and tentacle-filled zones!
#LIGHT_UMBER#New horrors:#WHITE# You liked radiant horrors? You'll love searing horrors! And Nethergames. And Entropic Shards. And ... more
#LIGHT_UMBER#Sick of your own head:#WHITE# Replace it with a nice cozy horror!
#LIGHT_UMBER#A ton#WHITE# of artifacts, lore, events...
]], [[#{bold}##GOLD#Forgotten Cults - Extension#LAST##{normal}#
#{italic}##ANTIQUE_WHITE#Tous les aventuriers ne cherchent pas la fortune, tous ceux qui défendent le monde n'ont pas de bonnes actions en tête. Ces derniers temps, le nombre d'horreurs observées a énormément augmenté. Les gens sortent des sentiers battus pour être retrouvés des années plus tard, horriblement mutés et en partie fous, si tant est qu'on les retrouve. Il devient évident que quelque chose bouge dans les profondeurs de Maj'Eyal. Ce quelque chose, c'est vous.#{normal}##LAST#
#{bold}#Modifications#{normal}#:
#LIGHT_UMBER#Nouvelle classe:#WHITE# Grouillants. Cédez aux forces corrompues et transformez-vous progressivement en une horreur, invoquez des horreurs pour faire votre travail, perdez votre peau et faites fondre votre visage pour agresser vos ennemis. Avec votre bras déjà transformé en tentacule, quelle créature peut vous arrêter?
#LIGHT_UMBER#Nouvelle classe:#WHITE# Cultistes entropique. En utilisant sa folie et le contrôle des forces entropiques pour démêler les lois normales de la physique, cette classe de lanceur de sortilèges peut transformer les guérisons en attaques et faire appel aux forces du vide pour réduire ses ennemis en poussière.
#LIGHT_UMBER#Nouvelle race:#WHITE# Drems. Une sous-race de nains corrompus, qui a réussi à garder une once de bon sens pour ne pas se transformer complètement en horreurs sans âme. Ils peuvent entrer dans une frénésie et même apprendre à invoquer des horreurs.
#LIGHT_UMBER#Nouvelle race:#WHITE# Krogs. Des ogres transformés par la chose même qui devrait les tuer. Leurs puissantes attaques peuvent étourdir leurs ennemis et ils sont si forts qu'ils peuvent manier à deux mains n'importe quelle arme.
#LIGHT_UMBER#Beaucoup de nouvelles zones:#WHITE# Explorez les fosses à fléaux, combattez pour sortir d'un ver géant (ne demandez pas comment vous y êtes entré), découvrez les merveilles de l'occulte Egress et bien d'autres zones étranges et remplies de tentacules!
#LIGHT_UMBER#Nouvelles horreurs:#WHITE# Vous avez aimé les horreurs rayonnantes? Vous aimerez les horreurs brûlantes! Et les jeux d'en bas. Et les tessons entropiques. Et ... plus
#LIGHT_UMBER#Lassé de votre propre tête:#WHITE# Remplacez-la par une autre bien plus horrible!
#LIGHT_UMBER#Une tonne#WHITE# d'artefacts, d'histoires, d'événements...
]], "_t")
t("#GOLD#Online Profile", "#GOLD#Profil en ligne", "_t")
t("Login", "Connexion", "_t")
t("Register", "Inscription", "_t")
t("Username: ", "Pseudonyme: ", "_t")
t("Password: ", "Mot de passe: ", "_t")
t("Login with Steam", "Connexion avec Steam", "_t")
t("#GOLD#Online Profile#WHITE#", "#GOLD#Profil en ligne#WHITE#", "_t")
t("#LIGHT_BLUE##{underline}#Logout", "#LIGHT_BLUE##{underline}#Déconnexion", "_t")
t("Username", "Pseudonyme", "_t")
t("Your username is too short", "Votre pseudonyme est trop court", "_t")
t("Password", "Mot de passe", "_t")
t("Your password is too short", "Votre mot de passe est trop court", "_t")
t("Login...", "Connexion...", "_t")
t("Steam client not found.", "Client Steam non trouvé", "_t")
-- nouveau texte
--[==[
t("Logging in your account, please wait...", "Logging in your account, please wait...", "_t")
--]==]
-- texte non traduit
--[==[
t("Addons", "Addons", "_t")
t("Options", "Options", "_t")
t("#LIGHT_BLUE##{underline}#%s#LAST##{normal}#", "#LIGHT_BLUE##{underline}#%s#LAST##{normal}#", "tformat")
--]==]
-- ancien texte traduit
t("Login in your account, please wait...", "Connexion à votre compte, attendez s'il vous plaît...", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/NewGame.lua"
t("New Game", "Nouvelle partie", "_t")
t("Show all versions", "Montrer toutes les versions", "_t")
t("Show incompatible", "Montrer les incompatibles", "_t")
t([[You can get new games at
#LIGHT_BLUE##{underline}#https://te4.org/games#{normal}#]], [[Vous pouvez avoir de nouveaux jeu sur
#LIGHT_BLUE##{underline}#https://te4.org/games#{normal}#]], "_t")
t("Game Module", "Module de jeu", "_t")
t("Enter your character's name", "Entrer le nom de votre personnage", "_t")
t("Overwrite character?", "Écraser un personnage?", "_t")
t("There is already a character with this name, do you want to overwrite it?", "Il y a déjà un personnage avec ce nom, voulez-vous l'écraser?", "_t")
t("No", "Non", "_t")
t("Yes", "Oui", "_t")
t("This game is not compatible with your version of T-Engine, you can still try it but it might break.", "Ce jeu n'est pas compatible avec votre version du T-Engine, vous pouvez quand même essayer mais ca peut planter.", "_t")
-- texte non traduit
--[==[
t("Version", "Version", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/dialogs/Profile.lua"
t("Player Profile", "Profil du joueur", "_t")
t("Logout", "Déconnexion", "_t")
t("You are logged in", "Vous êtes connecté", "_t")
t("Do you want to log out?", "Voulez-vous vous déconnecter?", "_t")
t("Log out", "Déconnexion", "_t")
t("Cancel", "Annuler", "_t")
t("Login", "Connexion", "_t")
t("Create Account", "Créer un compte", "_t")
------------------------------------------------
section "mod-boot/mod/dialogs/ProfileLogin.lua"
t("Online profile ", "Profil en ligne ", "_t")
t("Username: ", "Pseudonyme: ", "_t")
t("Password: ", "Mot de passe: ", "_t")
t("Login", "Connexion", "_t")
t("Cancel", "Annuler", "_t")
t("Password again: ", "Mot de passe, encore: ", "_t")
t("Accept to receive #{bold}#very infrequent#{normal}# (a few per year) mails about important game events from us.", "Accepter de recevoir #{bold}#rarement#{normal}# (quelques fois par an) des mails sur les événements que nous lançons.", "_t")
t("You at least 16 years old, or have parental authorization to play the game.", "Vous devez avoir au moins 16 ans, ou une autorisation parental pour jouer au jeu.", "_t")
t("Create", "Créer", "_t")
t("Privacy Policy (opens in browser)", "Politique de confidentialité (s'ouvre dans votre navigateur)", "_t")
t("Password", "Mot de passe", "_t")
t("Password mismatch!", "Mot de passe incorrect!", "_t")
t("Username", "Pseudonyme", "_t")
t("Your username is too short", "Votre pseudonyme est trop court", "_t")
t("Your password is too short", "Votre mot de passe est trop court", "_t")
t("Your email seems invalid", "Votre email semble invalide", "_t")
t("Age Check", "Vérification d'âge", "_t")
t("You need to be 16 years old or more or to have parental authorization to play this game.", "Vous devez avoir au moins 16 ans, ou une autorisation parental pour jouer au jeu.", "_t")
-- texte non traduit
--[==[
t("Email: ", "Email: ", "_t")
t("Email", "Email", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/dialogs/ProfileSteamRegister.lua"
t("Steam User Account", "Compte Steam de l'Utilisateur", "_t")
t([[Welcome to #GOLD#Tales of Maj'Eyal#LAST#.
To enjoy all the features the game has to offer it is #{bold}#highly#{normal}# recommended that you register your steam account.
Luckily this is very easy to do: you only require a profile name and optionally an email (we send very few email, maybe two a year at most).
]], [[Bienvenu sur #GOLD#Tales of Maj'Eyal#LAST#.
Pour profiter de toutes les fonctionnalités du jeu, il est #{bold}#hautement#{normal}# recommandé d'enregistrer votre compte steam.
Heureusement, c'est très facile à faire: vous n'avez besoin que d'un nom de profil et éventuellement d'un e-mail (nous envoyons très peu d'e-mails, peut-être deux par an tout au plus).
]], "_t")
t("Username: ", "Pseudonyme: ", "_t")
t("Accept to receive #{bold}#very infrequent#{normal}# (a few per year) mails about important game events from us.", "Accepter de recevoir #{bold}#rarement#{normal}# (quelques fois par an) des mails sur les événements que nous lançons.", "_t")
t("You at least 16 years old, or have parental authorization to play the game.", "Vous devez avoir au moins 16 ans, ou une autorisation parental pour jouer au jeu.", "_t")
t("Register", "Inscription", "_t")
t("Cancel", "Annuler", "_t")
t("Privacy Policy (opens in browser)", "Politique de confidentialité (s'ouvre dans votre navigateur)", "_t")
t("Username", "Pseudonyme", "_t")
t("Your username is too short", "Votre pseudonyme est trop court", "_t")
t("Your email does not look right.", "Votre Email semble défectueux", "_t")
t("Age Check", "Vérification d'âge", "_t")
t("You need to be 16 years old or more or to have parental authorization to play this game.", "Vous devez avoir au moins 16 ans, ou une autorisation parental pour jouer au jeu.", "_t")
t("Registering...", "Enregistrement...", "_t")
t("Registering on https://te4.org/, please wait...", "Enregistrement sur https://te4.org/, attendez s'il vous plait...", "_t")
t("Steam client not found.", "Client Steam non trouvé", "_t")
t("Error", "Erreur", "_t")
t("Username or Email already taken, please select an other one.", "Pseudonyme ou Email déjà pris, s'il vous plaît, sélectionnez en un autre", "_t")
-- texte non traduit
--[==[
t("Email: ", "Email: ", "_t")
t("Email", "Email", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/dialogs/UpdateAll.lua"
t("Update all game modules", "Mise à jour de tous les modules du jeu", "_t")
t([[All those components will be updated:
]], [[Tous ces composants vont être mis à jour:
]], "_t")
t("Component", "Composant", "_t")
t("Nothing to update", "Rien à mettre à jour", "_t")
t("All your game modules are up to date.", "Tous vos modules sont à jour", "_t")
t("Game: #{bold}##GOLD#", "Jeu: #{bold}##GOLD#", "_t")
t("Engine: #{italic}##LIGHT_BLUE#", "Moteur: #{italic}##LIGHT_BLUE#", "_t")
t("Error!", "Erreur!", "_t")
t([[There was an error while downloading:
]], [[Il y a eu une erreur pendant le téléchargement:
]], "_t")
t("Downloading: ", "Téléchergement: ", "_t")
t("Update", "Mise à jour", "_t")
t("All updates installed, the game will now restart", "Toutes les mises à jour sont installées, le jeu va maintenant redémarrer", "_t")
-- texte non traduit
--[==[
t("Version", "Version", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/dialogs/ViewHighScores.lua"
t("View High Scores", "Voir les meilleurs scores", "_t")
t("Game Module", "Module de jeu", "_t")
t("World", "Monde", "_t")
t([[#{bold}##GOLD#%s#GREEN# High Scores#WHITE##{normal}#
]], [[#{bold}##GOLD#%s#GREEN# Meilleurs Scores#WHITE##{normal}#
]], "tformat")
t([[#{bold}##GOLD#%s(%s)#GREEN# High Scores#WHITE##{normal}#
]], [[#{bold}##GOLD#%s(%s)#GREEN# Meilleurs Scores#WHITE##{normal}#
]], "tformat")
-- texte non traduit
--[==[
t("Version", "Version", "_t")
--]==]
------------------------------------------------
section "mod-boot/mod/init.lua"
t("Tales of Maj'Eyal Main Menu", "Menu Principal de Tales of Maj'Eyal", "init.lua long_name")
t([[Bootmenu!
]], [[Menu de démarrage!
]], "init.lua description")
------------------------------------------------
section "mod-boot/mod/load.lua"
t("Strength", "Force", "stat name")
t("str", "for", "stat short_name")
t("Dexterity", "Dextérité", "stat name")
-- texte non traduit
--[==[
t("dex", "dex", "stat short_name")
t("Constitution", "Constitution", "stat name")
t("con", "con", "stat short_name")
--]==]
<file_sep>/tome-addon-dev.lua
------------------------------------------------
section "tome-addon-dev/init.lua"
-- new text
--[==[
t("ToME Addon's Development Tools", "ToME Addon's Development Tools", "init.lua long_name")
t("Provides tools to develop and publish addons.", "Provides tools to develop and publish addons.", "init.lua description")
--]==]
------------------------------------------------
section "tome-addon-dev/overload/engine/i18nhelper/ArrangeText.lua"
-- new text
--[==[
t([[[WARNING]Mismatched translation for %s(%s):
Last occurance: %s (from section %s)
Current occurance: %s (from section %s)
]], [[[WARNING]Mismatched translation for %s(%s):
Last occurance: %s (from section %s)
Current occurance: %s (from section %s)
]], "log")
t("Success", "Success", "_t")
t([[Translation text checked.
Logs written to %s]], [[Translation text checked.
Logs written to %s]], "tformat")
t("\
-- new text\
", "\
-- new text\
", "_t")
t("\
-- untranslated text\
", "\
-- untranslated text\
", "_t")
t("\
-- old translated text\
", "\
-- old translated text\
", "_t")
t([[Translation text rearranged.
Logs written to %s]], [[Translation text rearranged.
Logs written to %s]], "tformat")
--]==]
------------------------------------------------
section "tome-addon-dev/overload/engine/i18nhelper/Extractor.lua"
-- new text
--[==[
t("Luafish parse error on file %s: %s", "Luafish parse error on file %s: %s", "log")
t("Error writing file %s", "Error writing file %s", "log")
t("MD5 matched for part %s, skipped.", "MD5 matched for part %s, skipped.", "log")
t("Extracting text", "Extracting text", "_t")
t("Processing source code of %s", "Processing source code of %s", "tformat")
t("Success", "Success", "_t")
t("Translation text extracted.", "Translation text extracted.", "_t")
--]==]
------------------------------------------------
section "tome-addon-dev/overload/engine/i18nhelper/FSHelper.lua"
-- new text
--[==[
t("Error %s", "Error %s", "log")
t("Calculating MD5", "Calculating MD5", "_t")
t("Calculating MD5 for %s", "Calculating MD5 for %s", "tformat")
--]==]
------------------------------------------------
section "tome-addon-dev/superload/mod/dialogs/debug/AddonDeveloper.lua"
t("Connecting to server", "Connexion au serveur", "_t")
t("unknown", "inconnu", "_t")
t("Later", "Plus tard", "_t")
t("Name", "Nom", "_t")
-- new text
--[==[
t("Addon Developer", "Addon Developer", "_t")
t([[- Your profile has been enabled for addon uploading, you can go to #{italic}##LIGHT_BLUE#https://te4.org/addons/tome#LAST##{normal}# and upload your addon.
]], [[- Your profile has been enabled for addon uploading, you can go to #{italic}##LIGHT_BLUE#https://te4.org/addons/tome#LAST##{normal}# and upload your addon.
]], "_t")
t("Archive for %s", "Archive for %s", "tformat")
t([[Addon archive created:
- Addon file: #LIGHT_GREEN#%s#LAST# in folder #{bold}#%s#{normal}#
- Addon MD5: #LIGHT_BLUE#%s#LAST# (this was copied to your clipboard)
%s
]], [[Addon archive created:
- Addon file: #LIGHT_GREEN#%s#LAST# in folder #{bold}#%s#{normal}#
- Addon MD5: #LIGHT_BLUE#%s#LAST# (this was copied to your clipboard)
%s
]], "_t")
t("Registering new addon", "Registering new addon", "_t")
t("Addon init.lua must contain a tags table, i.e: tags={'foo', 'bar'}", "Addon init.lua must contain a tags table, i.e: tags={'foo', 'bar'}", "_t")
t("Addon init.lua must contain a description field", "Addon init.lua must contain a description field", "_t")
t("Addon: %s", "Addon: %s", "tformat")
t("Addon #LIGHT_GREEN#%s#LAST# registered. You may now upload a version for it.", "Addon #LIGHT_GREEN#%s#LAST# registered. You may now upload a version for it.", "tformat")
t("Addon #LIGHT_RED#%s#LAST# not registered: %s", "Addon #LIGHT_RED#%s#LAST# not registered: %s", "tformat")
t("unknown reason", "unknown reason", "_t")
t("Uploading addon", "Uploading addon", "_t")
t("Addon #LIGHT_GREEN#%s#LAST# uploaded, players may now play with it!", "Addon #LIGHT_GREEN#%s#LAST# uploaded, players may now play with it!", "tformat")
t("Addon #LIGHT_RED#%s#LAST# not upload: %s", "Addon #LIGHT_RED#%s#LAST# not upload: %s", "tformat")
t("Steam Workshop: %s", "Steam Workshop: %s", "tformat")
t("Update error: %s", "Update error: %s", "tformat")
t("Uploading addon to Steam Workshop", "Uploading addon to Steam Workshop", "_t")
t("There was an error uploading the addon.", "There was an error uploading the addon.", "_t")
t([[Addon succesfully uploaded to the Workshop.
You need to accept Steam Workshop Agreement in your Steam Client before the addon is visible to the community.]], [[Addon succesfully uploaded to the Workshop.
You need to accept Steam Workshop Agreement in your Steam Client before the addon is visible to the community.]], "_t")
t("Go to Workshop", "Go to Workshop", "_t")
t("Addon succesfully uploaded to the Workshop.", "Addon succesfully uploaded to the Workshop.", "_t")
t("Uploading addon preview to Steam Workshop", "Uploading addon preview to Steam Workshop", "_t")
t("There was an error uploading the addon preview.", "There was an error uploading the addon preview.", "_t")
t("Addon update & preview succesfully uploaded to the Workshop.", "Addon update & preview succesfully uploaded to the Workshop.", "_t")
t("Addon update succesfully uploaded to the Workshop.", "Addon update succesfully uploaded to the Workshop.", "_t")
t("Choose an addon for MD5", "Choose an addon for MD5", "_t")
t("MD5 for %s", "MD5 for %s", "tformat")
t([[Addon MD5: #LIGHT_BLUE#%s#LAST# (this was copied to your clipboard).
However you should'nt need that anymore, you can upload your addon directly from here.]], [[Addon MD5: #LIGHT_BLUE#%s#LAST# (this was copied to your clipboard).
However you should'nt need that anymore, you can upload your addon directly from here.]], "tformat")
t("Choose an addon to archive", "Choose an addon to archive", "_t")
t("Choose an addon to register", "Choose an addon to register", "_t")
t("Choose an addon to publish", "Choose an addon to publish", "_t")
t("Name for this addon's release", "Name for this addon's release", "_t")
t("Choose an addon to publish to Steam Workshop (needs to have been published to te4.org first)", "Choose an addon to publish to Steam Workshop (needs to have been published to te4.org first)", "_t")
t("Addon preview", "Addon preview", "_t")
t([[Addons on Steam Workshop need a "preview" image for the listing.
The game has generated a default one, however it is best if you make a custom one and place it in the folder #LIGHT_GREEN#%s#LAST# named #LIGHT_BLUE#%s#LAST# (512x512 is a good size for it)
You can still upload now and place it later.]], [[Addons on Steam Workshop need a "preview" image for the listing.
The game has generated a default one, however it is best if you make a custom one and place it in the folder #LIGHT_GREEN#%s#LAST# named #LIGHT_BLUE#%s#LAST# (512x512 is a good size for it)
You can still upload now and place it later.]], "_t")
t("Upload now", "Upload now", "_t")
t("Wait", "Wait", "_t")
t("Generate Addon's MD5", "Generate Addon's MD5", "_t")
t("Register new Addon", "Register new Addon", "_t")
t("Publish Addon to te4.org", "Publish Addon to te4.org", "_t")
t("Publish Addon to Steam Workshop", "Publish Addon to Steam Workshop", "_t")
--]==]
------------------------------------------------
section "tome-addon-dev/superload/mod/dialogs/debug/DebugMain.lua"
-- new text
--[==[
t("Addon Developer", "Addon Developer", "_t")
t("Translation Tool", "Translation Tool", "_t")
--]==]
------------------------------------------------
section "tome-addon-dev/superload/mod/dialogs/debug/ExampleAddonMaker.lua"
t("Cancel", "Annuler", "_t")
-- new text
--[==[
t("DEBUG -- Create Translation Addon", "DEBUG -- Create Translation Addon", "_t")
t("", "", "_t")
t("#LIGHT_GREEN#Locale Code:#LAST# ", "#LIGHT_GREEN#Locale Code:#LAST# ", "_t")
t("#LIGHT_GREEN#Language Name:#LAST# ", "#LIGHT_GREEN#Language Name:#LAST# ", "_t")
t("Finish", "Finish", "_t")
t("Failure", "Failure", "_t")
t("Addon %s already exists", "Addon %s already exists", "tformat")
t([[Fail when copying file to /addons/%s:
%s]], [[Fail when copying file to /addons/%s:
%s]], "tformat")
t([[Addon %s successfully created
Newly created addon is stored in %s]], [[Addon %s successfully created
Newly created addon is stored in %s]], "tformat")
t("Success", "Success", "_t")
t("\
ToME4 is about to relaunch and change locale to %s, proceed?", "\
ToME4 is about to relaunch and change locale to %s, proceed?", "tformat")
--]==]
------------------------------------------------
section "tome-addon-dev/superload/mod/dialogs/debug/ReleaseTranslation.lua"
-- new text
--[==[
t("Choose addon", "Choose addon", "_t")
t("Choose the addon you want to copy translation file to.", "Choose the addon you want to copy translation file to.", "_t")
t("Failure", "Failure", "_t")
t([[Fail when copying file to %s:
%s]], [[Fail when copying file to %s:
%s]], "tformat")
t("Success", "Success", "_t")
t([[Translation text copied to %s
Logs written to %s]], [[Translation text copied to %s
Logs written to %s]], "tformat")
--]==]
------------------------------------------------
section "tome-addon-dev/superload/mod/dialogs/debug/TranslationTool.lua"
-- new text
--[==[
t("Translation Toolkit", "Translation Toolkit", "_t")
t("Change locale", "Change locale", "_t")
t("Enter locale code", "Enter locale code", "_t")
t("Change working locale (current: %s)", "Change working locale (current: %s)", "tformat")
t("Create translation addon", "Create translation addon", "_t")
t("Extract text index", "Extract text index", "_t")
t("Rearrange translation files", "Rearrange translation files", "_t")
t("Check translation files", "Check translation files", "_t")
t("Release translation as addon", "Release translation as addon", "_t")
--]==]
<file_sep>/_tdef_append.lua
------------------------------------------------
section ".always_merge"
tDef(0, "3-head")
tDef(0, "3-headed hydra")
tDef(0, "Agrimley the hermit")
tDef(0, "Allied Kingdoms")
tDef(0, "Angolwen")
tDef(0, "Assassin lair")
tDef(0, "Control Room")
tDef(0, "Cosmic Fauna")
tDef(0, "Dreadfell")
tDef(0, "Enemies")
tDef(0, "Experimentation Room")
tDef(0, "Exploratory Farportal")
tDef(0, "FINGER")
tDef(0, "Fearscape")
tDef(0, "Hall of Reflection")
tDef(0, "Horrors")
tDef(0, "Iron Throne")
tDef(0, "Keepers of Reality")
tDef(0, "MAINHAND")
tDef(0, "Marus of Elvala")
tDef(0, "OFFHAND")
tDef(0, "Orc Pride")
tDef(0, "Portal Room")
tDef(0, "Rhalore")
tDef(0, "Sandworm Burrowers")
tDef(0, "Shalore")
tDef(0, "Shasshhiy'Kaish")
tDef(0, "Sher'Tul")
tDef(0, "Slavers")
tDef(0, "Sorcerers")
tDef(0, "Stire of Derth")
tDef(0, "Storage Room")
tDef(0, "Sunwall")
tDef(0, "Temple of Creation")
tDef(0, "Thalore")
tDef(0, "The Way")
tDef(0, [[Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.
The time is %02d:%02d.]])
tDef(0, "Undead")
tDef(0, "Ungrol of Last Hope")
tDef(0, "Vargh Republic")
tDef(0, "Victim")
tDef(0, "Water lair")
tDef(0, "Zigur")
tDef(0, "absolute")
tDef(0, "armours")
tDef(0, "bomb")
tDef(0, "bonestaff")
tDef(0, "cannister")
tDef(0, "charged")
tDef(0, "combat")
tDef(0, "daikara")
tDef(0, "default")
tDef(0, "demon")
tDef(0, "dragon")
tDef(0, "dream")
tDef(0, "east")
tDef(0, "exit")
tDef(0, "harmonystaff")
tDef(0, "humanoid")
tDef(0, "humanoid/orc")
tDef(0, "husk")
tDef(0, "hydra")
tDef(0, "image")
tDef(0, "injured seer")
tDef(0, "kinetic")
tDef(0, "living")
tDef(0, "lone alchemist")
tDef(0, "lost defiler")
tDef(0, "lost sun paladin")
tDef(0, "lost warrior")
tDef(0, "magestaff")
tDef(0, "magical")
tDef(0, "mainhand")
tDef(0, "melee")
tDef(0, "mental")
tDef(0, "mountain chain")
tDef(0, "movement")
tDef(0, "north")
tDef(0, "northeast")
tDef(0, "northwest")
tDef(0, "offhand")
tDef(0, "portal")
tDef(0, "portal back")
tDef(0, "ranged")
tDef(0, "repented thief")
tDef(0, "rimebark")
tDef(0, "seed")
tDef(0, "south")
tDef(0, "southeast")
tDef(0, "southwest")
tDef(0, "spell")
tDef(0, "standard")
tDef(0, "standby")
tDef(0, "starstaff")
tDef(0, "steambot")
tDef(0, "stone golem")
tDef(0, "summon")
tDef(0, "summoned")
tDef(0, "tank")
tDef(0, "temporal explorer")
tDef(0, "temporal hound")
tDef(0, "thermal")
tDef(0, "throwing")
tDef(0, "turtle")
tDef(0, "unarmed")
tDef(0, "undead")
tDef(0, "unliving")
tDef(0, "unnatural")
tDef(0, "unseen")
tDef(0, "vilestaff")
tDef(0, "volcanic mountains")
tDef(0, "war hound")
tDef(0, "weapons")
tDef(0, "west")
tDef(0, "worried loremaster")
<file_sep>/engine.lua
------------------------------------------------
section ".always_merge"
t("3-head", "3 têtes", "nil")
t("3-headed hydra", "hydre à 3 têtes", "nil")
t("Agrimley the hermit", "Agrimley l'ermite", "nil")
t("Allied Kingdoms", "Royaumes alliés", "nil")
t("Assassin lair", "Repaire des assassins", "nil")
t("Control Room", "Salle de contrôle", "nil")
t("Cosmic Fauna", "Faune cosmique", "nil")
t("Dreadfell", "Tombeffroie", "nil")
t("Enemies", "Ennemis", "nil")
t("Experimentation Room", "Salle d'expérimentation", "nil")
t("Exploratory Farportal", "Portail lointain exploratoire", "nil")
t("FINGER", "DOIGT", "nil")
t("Fearscape", "Plan de la peur", "nil")
t("Hall of Reflection", "Salle des possibles", "nil")
t("Horrors", "Horreurs", "nil")
t("Iron Throne", "Trône de fer", "nil")
t("Keepers of Reality", "Gardiens de la réalité", "nil")
t("MAINHAND", "MAIN PRINCIPALE", "nil")
t("Marus of Elvala", "Marus d'Elvala", "nil")
t("OFFHAND", "MAIN SECONDAIRE", "nil")
t("Orc Pride", "La horde Orque", "nil")
t("Portal Room", "Salle du portail", "nil")
t("Sandworm Burrowers", "Vers des sables fouisseurs", "nil")
t("Slavers", "Esclavagistes", "nil")
t("Sorcerers", "Sorciers", "nil")
t("Stire of Derth", "Aiguille de Derth", "nil")
t("Storage Room", "Entrepôt", "nil")
t("Sunwall", "Mur du soleil", "nil")
t("Temple of Creation", "Temple de la création", "nil")
t("The Way", "La Voie", "nil")
t([[Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.
The time is %02d:%02d.]], [[Aujourd'hui nous sommes le %s %s de la %s année de l'Ère de l'Ascension de Maj'Eyal.
Il est %02d:%02d。]], "nil", {3,2,1,4,5})
t("Undead", "Mort-vivant", "nil")
t("Ungrol of Last Hope", "Ungrol de Dernier Espoir", "nil")
t("Vargh Republic", "Republique de Vargh", "nil")
t("Victim", "Victime", "nil")
t("Water lair", "Repaire aquatique", "nil")
t("absolute", "absolue", "nil")
t("armours", "armures", "nil")
t("bomb", "bombe", "nil")
t("bonestaff", "bâton en os", "nil")
t("cannister", "canister", "nil")
t("charged", "chargé", "nil")
t("default", "défaut", "nil")
t("demon", "démon", "nil")
t("dream", "rêve", "nil")
t("east", "à l'est", "nil")
t("exit", "sortie", "nil")
t("harmonystaff", "bâton harmonieux", "nil")
t("humanoid", "humanoïde", "nil")
t("humanoid/orc", "humanoïde/orc", "nil")
t("husk", "enveloppe", "nil")
t("hydra", "hydre", "nil")
t("injured seer", "Devin blessé", "nil")
t("kinetic", "cinétique", "nil")
t("living", "vivant", "nil")
t("lone alchemist", "alchimiste solitaire", "nil")
t("lost defiler", "profanateur perdu", "nil")
t("lost sun paladin", "paladin solaire perdu", "nil")
t("lost warrior", "guerrier perdu", "nil")
t("magestaff", "bâton de mage", "nil")
t("magical", "magique", "nil")
t("mainhand", "main principale", "nil")
t("melee", "mêlée", "nil")
t("mental", "mentale", "nil")
t("mountain chain", "chaîne de montagne", "nil")
t("movement", "mouvement", "nil")
t("north", "au nord", "nil")
t("northeast", "au nord-est", "nil")
t("northwest", "au nord-ouest", "nil")
t("offhand", "main secondaire", "nil")
t("portal", "portail", "nil")
t("portal back", "portail de retour", "nil")
t("ranged", "distance", "nil")
t("repented thief", "voleur repentie", "nil")
t("rimebark", "givrécorce", "nil")
t("seed", "graine", "nil")
t("south", "au sud", "nil")
t("southeast", "au sud-est", "nil")
t("southwest", "au sud-ouest", "nil")
t("spell", "sort", "nil")
t("standby", "en attente", "nil")
t("starstaff", "bâton des étoiles", "nil")
t("steambot", "robot à vapeur", "nil")
t("stone golem", "golem de pierre", "nil")
t("summon", "invocation", "nil")
t("summoned", "invoqué", "nil")
t("tank", "réservoir", "nil")
t("temporal explorer", "explorateur temporel", "nil")
t("temporal hound", "chien de chasse temporel", "nil")
t("thermal", "thermique", "nil")
t("throwing", "lancer", "nil")
t("turtle", "tortue", "nil")
t("unarmed", "désarmé", "nil")
t("undead", "mort-vivant", "nil")
t("unliving", "non vivant", "nil")
t("unnatural", "contre nature", "nil")
t("unseen", "inaperçu", "nil")
t("vilestaff", "bâton ignoble", "nil")
t("volcanic mountains", "montagnes volcaniques", "nil")
t("war hound", "chien de guerre", "nil")
t("weapons", "armes", "nil")
t("west", "à l'ouest", "nil")
t("worried loremaster", "chroniqueur soucieux", "nil")
-- texte non traduit
--[==[
t("Angolwen", "Angolwen", "nil")
t("Rhalore", "Rhalore", "nil")
t("Shalore", "Shalore", "nil")
t("Shasshhiy'Kaish", "Shasshhiy'Kaish", "nil")
t("Sher'Tul", "Sher'Tul", "nil")
t("Thalore", "Thalore", "nil")
t("Zigur", "Zigur", "nil")
t("combat", "combat", "nil")
t("daikara", "daikara", "nil")
t("dragon", "dragon", "nil")
t("image", "image", "nil")
t("standard", "standard", "nil")
--]==]
------------------------------------------------
section "engine/data/keybinds/actions.lua"
t("Go to next/previous level", "Aller au niveau suivant/précédant", "_t")
t("Levelup window", "Fenêtre de montée en niveau", "_t")
t("Use talents", "Utiliser vos talents", "_t")
t("Show quests", "Voir les quêtes", "_t")
t("Rest for a while", "Se reposer un moment", "_t")
t("Save game", "Sauvegarder la partie", "_t")
t("Quit game", "Quitter le jeu", "_t")
t("Tactical display on/off", "Affichage tactique on/off", "_t")
t("Look around", "Regarder aux alentours", "_t")
t("Center the view on the player", "Centrer la vue sur le joueur", "_t")
t("Toggle minimap", "Afficher la carte", "_t")
t("Show game calendar", "Voir le calendrier", "_t")
t("Show character sheet", "Voir la feuille de personnage", "_t")
t("Switch graphical modes", "Changer de mode graphique", "_t")
t("Accept action", "Accepter l'action", "_t")
t("Exit menu", "Quitter", "_t")
------------------------------------------------
section "engine/data/keybinds/chat.lua"
t("Talk to people", "Parler aux gens", "_t")
t("Display chat log", "Afficher l'historique de conversation", "_t")
t("Cycle chat channels", "Faire défiler les canaux de conversations", "_t")
------------------------------------------------
section "engine/data/keybinds/debug.lua"
t("Show Lua console", "Afficher la console Lua", "_t")
t("Debug Mode", "Mode Débogage", "_t")
------------------------------------------------
section "engine/data/keybinds/hotkeys.lua"
t("Hotkey 1", "Raccourci 1", "_t")
t("Hotkey 2", "Raccourci 2", "_t")
t("Hotkey 3", "Raccourci 3", "_t")
t("Hotkey 4", "Raccourci 4", "_t")
t("Hotkey 5", "Raccourci 5", "_t")
t("Hotkey 6", "Raccourci 6", "_t")
t("Hotkey 7", "Raccourci 7", "_t")
t("Hotkey 8", "Raccourci 8", "_t")
t("Hotkey 9", "Raccourci 9", "_t")
t("Hotkey 10", "Raccourci 10", "_t")
t("Hotkey 11", "Raccourci 11", "_t")
t("Hotkey 12", "Raccourci 12", "_t")
t("Secondary Hotkey 1", "Second Raccourci 1", "_t")
t("Secondary Hotkey 2", "Second Raccourci 2", "_t")
t("Secondary Hotkey 3", "Second Raccourci 3", "_t")
t("Secondary Hotkey 4", "Second Raccourci 4", "_t")
t("Secondary Hotkey 5", "Second Raccourci 5", "_t")
t("Secondary Hotkey 6", "Second Raccourci 6", "_t")
t("Secondary Hotkey 7", "Second Raccourci 7", "_t")
t("Secondary Hotkey 8", "Second Raccourci 8", "_t")
t("Secondary Hotkey 9", "Second Raccourci 9", "_t")
t("Secondary Hotkey 10", "Second Raccourci 10", "_t")
t("Secondary Hotkey 11", "Second Raccourci 11", "_t")
t("Secondary Hotkey 12", "Second Raccourci 12", "_t")
t("Third Hotkey 1", "Troisième Raccourci 1", "_t")
t("Third Hotkey 2", "Troisième Raccourci 2", "_t")
t("Third Hotkey 3", "Troisième Raccourci 3", "_t")
t("Third Hotkey 4", "Troisième Raccourci 4", "_t")
t("Third Hotkey 5", "Troisième Raccourci 5", "_t")
t("Third Hotkey 6", "Troisième Raccourci 6", "_t")
t("Third Hotkey 7", "Troisième Raccourci 7", "_t")
t("Third Hotkey 8", "Troisième Raccourci 8", "_t")
t("Third Hotkey 9", "Troisième Raccourci 9", "_t")
t("Third Hotkey 10", "Troisième Raccourci 10", "_t")
t("Third Hotkey 11", "Troisième Raccourci 11", "_t")
t("Third Hotkey 12", "Troisième Raccourci 12", "_t")
t("Fourth Hotkey 1", "Quatrième Raccourci 1", "_t")
t("Fourth Hotkey 2", "Quatrième Raccourci 2", "_t")
t("Fourth Hotkey 3", "Quatrième Raccourci 3", "_t")
t("Fourth Hotkey 4", "Quatrième Raccourci 4", "_t")
t("Fourth Hotkey 5", "Quatrième Raccourci 5", "_t")
t("Fourth Hotkey 6", "Quatrième Raccourci 6", "_t")
t("Fourth Hotkey 7", "Quatrième Raccourci 7", "_t")
t("Fourth Hotkey 8", "Quatrième Raccourci 8", "_t")
t("Fourth Hotkey 9", "Quatrième Raccourci 9", "_t")
t("Fourth Hotkey 10", "Quatrième Raccourci 10", "_t")
t("Fourth Hotkey 11", "Quatrième Raccourci 11", "_t")
t("Fourth Hotkey 12", "Quatrième Raccourci 12", "_t")
t("Fifth Hotkey 1", "Cinquième Raccourci 1", "_t")
t("Fifth Hotkey 2", "Cinquième Raccourci 2", "_t")
t("Fifth Hotkey 3", "Cinquième Raccourci 3", "_t")
t("Fifth Hotkey 4", "Cinquième Raccourci 4", "_t")
t("Fifth Hotkey 5", "Cinquième Raccourci 5", "_t")
t("Fifth Hotkey 6", "Cinquième Raccourci 6", "_t")
t("Fifth Hotkey 7", "Cinquième Raccourci 7", "_t")
t("Fifth Hotkey 8", "Cinquième Raccourci 8", "_t")
t("Fifth Hotkey 9", "Cinquième Raccourci 9", "_t")
t("Fifth Hotkey 10", "Cinquième Raccourci 10", "_t")
t("Fifth Hotkey 11", "Cinquième Raccourci 11", "_t")
t("Fifth Hotkey 12", "Cinquième Raccourci 12", "_t")
t("Six Hotkey 1", "Sixième Raccourci 1", "_t")
t("Six Hotkey 2", "Sixième Raccourci 2", "_t")
t("Six Hotkey 3", "Sixième Raccourci 3", "_t")
t("Six Hotkey 4", "Sixième Raccourci 4", "_t")
t("Six Hotkey 5", "Sixième Raccourci 5", "_t")
t("Six Hotkey 6", "Sixième Raccourci 6", "_t")
t("Six Hotkey 7", "Sixième Raccourci 7", "_t")
t("Six Hotkey 8", "Sixième Raccourci 8", "_t")
t("Six Hotkey 9", "Sixième Raccourci 9", "_t")
t("Six Hotkey 10", "Sixième Raccourci 10", "_t")
t("Six Hotkey 11", "Sixième Raccourci 11", "_t")
t("Six Hotkey 12", "Sixième Raccourci 12", "_t")
t("Seven Hotkey 1", "Septième Raccourci 1", "_t")
t("Seven Hotkey 2", "Septième Raccourci 2", "_t")
t("Seven Hotkey 3", "Septième Raccourci 3", "_t")
t("Seven Hotkey 4", "Septième Raccourci 4", "_t")
t("Seven Hotkey 5", "Septième Raccourci 5", "_t")
t("Seven Hotkey 6", "Septième Raccourci 6", "_t")
t("Seven Hotkey 7", "Septième Raccourci 7", "_t")
t("Seven Hotkey 8", "Septième Raccourci 8", "_t")
t("Seven Hotkey 9", "Septième Raccourci 9", "_t")
t("Seven Hotkey 10", "Septième Raccourci 10", "_t")
t("Seven Hotkey 11", "Septième Raccourci 11", "_t")
t("Seven Hotkey 12", "Septième Raccourci 12", "_t")
t("Previous Hotkey Page", "Page de Raccourcis précédente", "_t")
t("Next Hotkey Page", "Page de Raccourcis suivante", "_t")
t("Quick switch to Hotkey Page 2", "Passer rapidement à la page de raccourcis 2", "_t")
t("Quick switch to Hotkey Page 3", "Passer rapidement à la page de raccourcis 3", "_t")
------------------------------------------------
section "engine/data/keybinds/interface.lua"
t("Toggle list of seen creatures", "Afficher la liste des créatures en vue", "_t")
t("Show message log", "Afficher l'historique des messages", "_t")
t("Take a screenshot", "Faire une capture d'écran", "_t")
t("Show map", "Afficher la carte", "_t")
t("Scroll map mode", "Passer la carte en mode exploration", "_t")
------------------------------------------------
section "engine/data/keybinds/inventory.lua"
t("Show inventory", "Afficher l'inventaire", "_t")
t("Show equipment", "Afficher l'équipement", "_t")
t("Pickup items", "Ramasser des objets", "_t")
t("Drop items", "Abandonner des objets", "_t")
t("Wield/wear items", "Manier/Porter de l'équipement", "_t")
t("Takeoff items", "Enlever de l'équipement", "_t")
t("Use items", "Utiliser des objets", "_t")
t("Quick switch weapons set", "Changer de set d'armes", "_t")
------------------------------------------------
section "engine/data/keybinds/move.lua"
t("Move left", "Se déplacer à gauche", "_t")
t("Move right", "Se déplacer à droite", "_t")
t("Move up", "Se déplacer en haut", "_t")
t("Move down", "Se déplacer en bas", "_t")
t("Move diagonally left and up", "Se déplacer en haut à gauche", "_t")
t("Move diagonally right and up", "Se déplacer en haut à droite", "_t")
t("Move diagonally left and down", "Se déplacer en bas à gauche", "_t")
t("Move diagonally right and down", "Se déplacer en bas à droite", "_t")
t("Stay for a turn", "Se reposer un tour", "_t")
t("Run", "Courir", "_t")
t("Run left", "Courir à gauche", "_t")
t("Run right", "Courir à droite", "_t")
t("Run up", "Courir en haut", "_t")
t("Run down", "Courir en bas", "_t")
t("Run diagonally left and up", "Courir en haut à gauche", "_t")
t("Run diagonally right and up", "Courir en haut à droite", "_t")
t("Run diagonally left and down", "Courir en bas à gauche", "_t")
t("Run diagonally right and down", "Courir en bas à droite", "_t")
t("Auto-explore", "Explorer automatiquement", "_t")
t("movement", "mouvement", "_t")
t("Move left (WASD directions)", "Se déplacer à gauche (ZQSD Directions)", "_t")
t("Move right (WASD directions)", "Se déplacer à droite (ZQSD Directions)", "_t")
t("Move up (WASD directions)", "Se déplacer en haut (ZQSD Directions)", "_t")
t("Move down (WASD directions)", "Se déplacer en bas (ZQSD Directions)", "_t")
------------------------------------------------
section "engine/data/keybinds/mtxn.lua"
t("List purchasable", "Liste d'achats", "_t")
t("Use purchased", "Achats réalisés", "_t")
------------------------------------------------
section "engine/engine/ActorsSeenDisplay.lua"
-- texte non traduit
--[==[
t("%s (%d)#WHITE#; distance [%s]", "%s (%d)#WHITE#; distance [%s]", "tformat")
--]==]
------------------------------------------------
section "engine/engine/Birther.lua"
t("Enter your character's name", "Entrer le nom de votre personnage", "_t")
t("Name", "Nom", "_t")
t("Character Creation: %s", "Création du personnage: %s", "tformat")
t([[Keyboard: #00FF00#up key/down key#FFFFFF# to select an option; #00FF00#Enter#FFFFFF# to accept; #00FF00#Backspace#FFFFFF# to go back.
Mouse: #00FF00#Left click#FFFFFF# to accept; #00FF00#right click#FFFFFF# to go back.
]], [[Clavier: #00FF00#touche haut/touche bas#FFFFFF# pour séléctionner une option; #00FF00#Entrée#FFFFFF# pour accepter; #00FF00#Backspace#FFFFFF# pour revenir en arrière.
Souris: #00FF00#Clic gauche#FFFFFF# pour accepter; #00FF00#clic droit#FFFFFF# pour revenir en arrière.
]], "_t")
t("Random", "Au hasard", "_t")
t("Quick Birth", "Création rapide", "_t")
t("Do you want to recreate the same character?", "Voulez-vous recréer le même personnage?", "_t")
t("Recreate", "Recréer?", "_t")
t("New character", "Nouveau personnage", "_t")
t("Randomly selected %s.", "Choisir au hasard %s.", "log")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/Chat.lua"
-- texte non traduit
--[==[
t("???", "???", "_t")
--]==]
------------------------------------------------
section "engine/engine/DebugConsole.lua"
t("Lua Console", "Console Lua", "_t")
------------------------------------------------
section "engine/engine/Dialog.lua"
t("Yes", "Oui", "_t")
t("No", "Non", "_t")
------------------------------------------------
section "engine/engine/Game.lua"
t("Screenshot taken!", "Capture d'écran réalisé!", "_t")
t([[Screenshot should appear in your Steam client's #LIGHT_GREEN#Screenshots Library#LAST#.
Also available on disk: %s]], [[La capture d'écran devrait être disponible dans votre #LIGHT_GREEN#bibliothèque de capture d'écran Steam#LAST#.
Disponible aussi sur votre disque: %s]], "tformat")
t("File: %s", "Fichier: %s", "tformat")
------------------------------------------------
section "engine/engine/HotkeysDisplay.lua"
t("Missing!", "Manquant!", "_t")
------------------------------------------------
section "engine/engine/HotkeysIconsDisplay.lua"
t("Unknown!", "Inconnu!", "_t")
t("Missing!", "Manquant!", "_t")
------------------------------------------------
section "engine/engine/I18N.lua"
t("Testing arg one %d and two %d", "Test de l'argument un %d et deux %d", "tformat")
------------------------------------------------
section "engine/engine/Key.lua"
t("#LIGHT_RED#Keyboard input temporarily disabled.", "#LIGHT_RED#Entrées clavier temporairement désactivées.", "log")
------------------------------------------------
section "engine/engine/LogDisplay.lua"
t("Message Log", "Historique des messages", "_t")
------------------------------------------------
section "engine/engine/MicroTxn.lua"
-- texte non traduit
--[==[
t("Test", "Test", "_t")
--]==]
------------------------------------------------
section "engine/engine/Module.lua"
t("Beta Addons Disabled", "Addons Beta Désactivés", "_t")
t([[This beta version is meant to be tested without addons, as such the following ones are currently disabled:
#GREY#]], [[Cette version beta a vocation à être testée sans addons, c'est pourquoi les addons sont pour l'instant désactivés
#GREY#]], "_t")
t("#{italic}##PINK#Addons developers can still test their addons by enabling developer mode.#{normal}#", "#{italic}##PINK#Les développeurs d'addons peuvent continuer à tester leurs addons en activant le mode développeur.#{normal}#", "_t")
t([[Total playtime of all registered players:%s
]], [[Temps de jeu total des joueurs enregistré:%s
]], "tformat")
t("#LIGHT_BLUE#%s#WHITE# is one of the top five played races", "#LIGHT_BLUE#%s#WHITE# est l'une des cinq races les plus jouées", "tformat")
t("#LIGHT_BLUE#%s#WHITE# is one of the top five played classes", "#LIGHT_BLUE#%s#WHITE# est l'une des cinq classes les plus jouées", "tformat")
t("#CRIMSON#%s#WHITE# is one of the top ten killers", "#CRIMSON#%s#WHITE# est l'un des dix plus grand tueurs", "tformat")
t("#LIGHT_BLUE#%s#WHITE# is one of the top ten race/class combo", "#LIGHT_BLUE#%s#WHITE# est l'un des dix combo race/classe les plus joué", "tformat")
t("There are currently %d people playing online", "Il y a acctuellement %d joueurs en ligne", "tformat")
t("The character's vault has registered a total of #RED#%d#WHITE# character's deaths", "Le coffre de personnages enregistre un totale de #RED#%d#WHITE# personnages morts", "tformat")
t("The character's vault has registered a total of #LIGHT_BLUE#%d#WHITE# winners for the current version", "Le coffre de personnages enregistre un totale de #LIGHT_BLUE#%d#WHITE# gagnant pour la version actuelle", "tformat")
t("The latest donator is #LIGHT_GREEN#%s#WHITE#. Many thanks to all donators, you are keeping this game alive!", "Le dernier donateur est #LIGHT_GREEN#%s#WHITE#. Un grand merci à tous les donateurs, vous gardez le jeu en vie!", "tformat")
t("#LIGHT_RED#Online profile disabled(switching to offline profile) due to %s.", "#LIGHT_RED#Profil en ligne désactivé (passage au profil hors ligne) car %s.", "log")
------------------------------------------------
section "engine/engine/Mouse.lua"
t("#LIGHT_RED#Mouse input temporarily disabled.", "#LIGHT_RED#Entrées souris temporairement désactivées", "log")
------------------------------------------------
section "engine/engine/Object.lua"
t("Requires:", "Requis:", "_t")
t("%s (level %d)", "%s (niveau %d)", "tformat")
t("Level %d", "Niveau %d", "tformat")
t("Talent %s (level %d)", "Talent %s (Niveau %d)", "tformat")
-- texte non traduit
--[==[
t("Talent %s", "Talent %s", "tformat")
--]==]
------------------------------------------------
section "engine/engine/PlayerProfile.lua"
t("#YELLOW#Connection to online server established.", "#YELLOW#Connexion au server en ligne établie.", "log")
t("#YELLOW#Connection to online server lost, trying to reconnect.", "#YELLOW#Connexion au serveur en ligne perdue, tentative de reconnexion.", "log")
t("no online profile active", "le profil en ligne n'est pas actif", "_t")
t("cheat mode active", "le mode triche est actif", "_t")
t("savefile tainted", "le fichier de sauvegarde est abimé", "_t")
t("bad game version", "la version du jeu n'est pas la bonne", "_t")
t("bad game addon version", "la version de l'addon du jeu n'est pas la bonne", "_t")
t("nothing to update", "il n'y a rien a mettre à jour", "_t")
t("unknown error", "il y a une erreur inconnue", "_t")
t("Registering character", "Personnage en cours d'enregistrement", "_t")
t("Character is being registered on https://te4.org/", "Le personnage est en train d'être enregistré sur https://te4.org/", "_t")
t("Retrieving data from the server", "Donnée en cours de récupération sur le serveur", "_t")
t("Retrieving...", "Récupération...", "_t")
------------------------------------------------
section "engine/engine/Quest.lua"
t("active", "actif", "_t")
t("completed", "terminée", "_t")
t("done", "réalisée", "_t")
t("failed", "échouée", "_t")
------------------------------------------------
section "engine/engine/Savefile.lua"
t("Saving world", "Sauvegarde du monde", "_t")
t("Please wait while saving the world...", "Patientez pendant la sauvegarde du monde s'il vous plait...", "_t")
t("Saving game", "Sauvegarde du jeu", "_t")
t("Please wait while saving the game...", "Patientez pendant la sauvegarde du jeu s'il vous plait...", "_t")
t("Saving zone", "Sauvegarde de la zone", "_t")
t("Please wait while saving the zone...", "Patientez pendant la sauvegarde de la zone s'il vous plait...", "_t")
t("Saving level", "Sauvegarde du niveau", "_t")
t("Please wait while saving the level...", "Patientez pendant la sauvegarde du niveau s'il vous plait...", "_t")
t("Saving entity", "Sauvegarde de l'entité", "_t")
t("Please wait while saving the entity...", "Patientez pendant la sauvegarde de l'entité s'il vous plait...", "_t")
t("Loading world", "Chargement du monde", "_t")
t("Please wait while loading the world...", "Patientez pendant le chargement du monde s'il vous plait...", "_t")
t("Loading game", "Chargement du jeu", "_t")
t("Please wait while loading the game...", "Patientez pendant le chargement du jeu s'il vous plait...", "_t")
t("Loading zone", "Chargement de la zone", "_t")
t("Please wait while loading the zone...", "Patientez pendant le chargement de la zone s'il vous plait...", "_t")
t("Loading level", "Chargement du niveau", "_t")
t("Please wait while loading the level...", "Patientez pendant le chargement du niveau s'il vous plait...", "_t")
t("Loading entity", "Chargement de l'entité", "_t")
t("Please wait while loading the entity...", "Patientez pendant le chargement de l'entité s'il vous plait...", "_t")
------------------------------------------------
section "engine/engine/SavefilePipe.lua"
t("Saving done.", "Sauvegarde réalisée.", "log")
t("Saving...", "Sauvegarde en cours...", "_t")
t("Please wait while saving...", "Patientez pendant la sauvegarde s'il vous plait...", "_t")
------------------------------------------------
section "engine/engine/Store.lua"
t("Store: %s", "Boutique: %s", "tformat")
t("Buy", "Acheter", "_t")
t("Buy %d %s", "Acheter %d %s", "tformat")
t("Cancel", "Annuler", "_t")
t("Sell", "Vendre", "_t")
t("Sell %d %s", "Vendre %d %s", "tformat")
------------------------------------------------
section "engine/engine/Trap.lua"
t("%s fails to disarm a trap (%s).", "%s échoue à désarmer le piège (%s).", "logSeen")
t("%s disarms a trap (%s).", "%s désarme le piège (%s).", "logSeen")
t("%s triggers a trap (%s)!", "%s déclenche le piège (%s)!", "logSeen")
-- texte non traduit
--[==[
t("%s", "%s", "logSeen")
--]==]
------------------------------------------------
section "engine/engine/UserChat.lua"
t("Ignoring all new messages from %s.", "Ignorer tous les nouveaux messages de %s.", "log")
t([[#{bold}#Thank you#{normal}# for you donation, your support means a lot for the continued survival of this game.
Your current donation total is #LIGHT_GREEN#%0.2f euro#WHITE# which equals to #ROYAL_BLUE#%d voratun coins#WHITE# to use on te4.org.
Your Item Vault has #TEAL#%d slots#WHITE#.
Again, thank you, and enjoy Eyal!
#{italic}#Your malevolent local god of darkness, #GOLD#DarkGod#{normal}#]], [[#{bold}#Merci#{normal}# pour votre donation, votre soutien signifie beaucoup pour la survie de ce jeu.
Le montant total de vos dons s'élève actuellement à #LIGHT_GREEN#%0.2f euros#WHITE# ce qui est équivaut à #ROYAL_BLUE#%d pieces de voratun#WHITE# à utiliser sur te4.org.
Votre coffre d'objets a #TEAL#%d emplacements#WHITE#.
Encore une fois, merci, et profitez bien de Eyal!
#{italic}#Votre dieu des ténèbres malveillant, #GOLD#DarkGod#{normal}#]], "tformat")
t("Thank you!", "Merci!", "_t")
t("#{italic}#Joined channel#{normal}#", "#{italic}#Canal rejoint#{normal}#", "_t")
t("#{italic}#Left channel#{normal}#", "#{italic}#Canal quitté#{normal}#", "_t")
t("#{italic}##FIREBRICK#has joined the channel#{normal}#", "#{italic}##FIREBRICK#a rejoint le canal#{normal}#", "_t")
t("#{italic}##FIREBRICK#has left the channel#{normal}#", "#{italic}##FIREBRICK#a quitté le canal#{normal}#", "_t")
t("#CRIMSON#You are not subscribed to any channel, you can change that in the game options.#LAST#", "#CRIMSON#Vous n'avez souscrit à aucun canaux, vous pouvez changer cela dans les options du jeu.#LAST#", "log")
t("Requesting...", "Demande en cours...", "_t")
t("Requesting user info...", "Demande d'information sur l'utilisateur...", "_t")
t("Error", "Erreur", "_t")
t("The server does not know about this player.", "Le serveur ne sait rien sur ce joueur.", "_t")
------------------------------------------------
section "engine/engine/Zone.lua"
t("Loading level", "Chargement du niveau", "_t")
t("Please wait while loading the level... ", "Patientez pendant le chargement du niveau s'il vous plait... ", "_t")
t("Generating level", "Génération du niveau", "_t")
t("Please wait while generating the level... ", "Patientez pendant la génération du niveau s'il vous plait... ", "_t")
------------------------------------------------
section "engine/engine/ai/talented.lua"
t("#ORCHID#__[%d]%s improved talented AI picked talent[att:%d, turn %s]: %s", "#ORCHID#__[%d]%s IA de talent amélioré a choisi un talent[att:%d, tour %s]: %s", "log")
t("__[%d]%s#ORANGE# ACTION FAILED: %s, %s", "__[%d]%s#ORANGE# ACTION RATÉE: %s, %s", "log")
t("#SLATE#__%s[%d] improved talented AI No talents available [att:%d, turn %s]", "#SLATE#__%s[%d] IA de talent amélioré Pas de talents disponibles [att:%d, tour %s]", "log")
------------------------------------------------
section "engine/engine/dialogs/AudioOptions.lua"
t("Audio Options", "Options audio", "_t")
t("Enable audio", "Activer l'audio", "_t")
t("Music: ", "Son: ", "_t")
t("Effects: ", "Effets: ", "_t")
------------------------------------------------
section "engine/engine/dialogs/ChatChannels.lua"
t("Chat channels", "Canaux de discussion", "_t")
t(" [spoilers]", " [divulgachis]", "_t")
t("Select which channels to listen to. You can join new channels by typing '/join <channelname>' in the talkbox and leave channels by typing '/part <channelname>'", "Séléctionnez les canaux que vous souhaitez écouter. Vous pouvez rejoindre un canal en tapant '/join <nomducanal>' dans la fenêtre de tchat,et en quitter en tapant '/part <nomducanal>'", "_t")
-- texte non traduit
--[==[
t("Global", "Global", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ChatFilter.lua"
t("Chat filters", "Filtres de tchat", "_t")
t("Public chat", "Tchat public", "_t")
t("Private whispers", "Messages privés", "_t")
t("Join/part messages", "Joindre/quitter", "_t")
t("First time achievements (recommended to keep them on)", "Succès réalisés pour la première fois (il est recommandé de les garder)", "_t")
t("Important achievements (recommended to keep them on)", "Succès Important (il est recommandé de les garder)", "_t")
t("Other achievements", "Autres succès", "_t")
t("Select which types of chat events to see or not.", "Sélectionnez les types d'événements de tchat à voir ou non.", "_t")
------------------------------------------------
section "engine/engine/dialogs/ChatIgnores.lua"
t("Chat ignore list", "Liste des utilisateurs ignorés", "_t")
t("Stop ignoring", "Vous avez cessé de l'ignorer", "_t")
t("Really stop ignoring: %s", "Voulez vous vraiment cesser d'ignorer %s?", "tformat")
t("Click a user to stop ignoring her/his messages.", "Cliquez sur un utilisateur pour cesser d'ignorer ses messages.", "_t")
------------------------------------------------
section "engine/engine/dialogs/DisplayResolution.lua"
t("Switch Resolution", "Changer de résolution", "_t")
t("Fullscreen", "Plein écran", "_t")
t("Borderless", "Sans bordure", "_t")
t("Windowed", "Fenêtré", "_t")
t("Engine Restart Required", "Redémarrage du jeu requis", "_t")
t("Continue? %s", "Continuer? %s", "tformat")
t(" (progress will be saved)", " (La progression sera sauvegardée)", "_t")
t("Reset Window Position?", "Réinitialiser la position de la fenêtre?", "_t")
t("Simply restart or restart+reset window position?", "Seulement redémarrer, ou redémarrer et réinitialiser la position de la fenêtre?", "_t")
t("Restart", "Redémarrage", "_t")
t("Restart with reset", "Redémarrage avec réinitialisation", "_t")
t("Yes", "Oui", "_t")
t("No", "Non", "_t")
------------------------------------------------
section "engine/engine/dialogs/Downloader.lua"
t("Download: %s", "Téléchargement: %s", "tformat")
t("Cancel", "Annuler", "_t")
------------------------------------------------
section "engine/engine/dialogs/GameMenu.lua"
t("Game Menu", "Menu du jeu", "_t")
t("Resume", "Reprendre", "_t")
t("Language", "Langage", "_t")
t("Key Bindings", "Affectation des touches", "_t")
t("Video Options", "Options vidéo", "_t")
t("Display Resolution", "Résolution", "_t")
t("Show Achievements", "Montrer les succès", "_t")
t("Audio Options", "Options audio", "_t")
t("#GREY#Developer Mode", "#GREY#Mode développeur", "_t")
t("Developer Mode", "Mode développeur", "_t")
t("Disable developer mode?", "Désactiver le mode développeur?", "_t")
t([[Enable developer mode?
Developer Mode is a special game mode used to debug and create addons.
Using it will #CRIMSON#invalidate#LAST# any savefiles loaded.
When activated you will have access to special commands:
- CTRL+L: bring up a lua console that lets you explore and alter all the game objects, enter arbitrary lua commands, ...
- CTRL+A: bring up a menu to easily do many tasks (create NPCs, teleport to zones, ...)
- CTRL+left click: teleport to the clicked location
]], [[Activer le mode développeur?
Le mode développeur est un mode de jeu spécial utilisé pour déboguer et créer des addons.
Son utilisation #CRIMSON#invalidera#LAST# tout fichier de sauvegarde chargé.
Lorsqu'il est activé, vous aurez accès à des commandes spéciales:
- CTRL+L: fait apparaître une console Lua qui vous permet d'explorer et de modifier tous les objets du jeu, d'entrer des commandes Lua arbitraires,...
- CTRL+Q: affiche un menu permettant de réaliser facilement de nombreuses tâches (créer des PNJs, se téléporter dans des zones,...)
- CTRL+clic gauche : se téléporter à l'endroit cliqué.
]], "_t")
t("No", "Non", "_t")
t("Yes", "Oui", "_t")
t("Save Game", "Sauvegarder le jeu", "_t")
t("Main Menu", "Menu principal", "_t")
t("Exit Game", "Quitter le jeu", "_t")
------------------------------------------------
section "engine/engine/dialogs/GetQuantity.lua"
t("Quantity", "Quantité", "_t")
t("Accept", "Accepter", "_t")
t("Cancel", "Annuler", "_t")
t("Error", "Erreur", "_t")
t("Enter a quantity.", "Entrer une quantité.", "_t")
------------------------------------------------
section "engine/engine/dialogs/GetQuantitySlider.lua"
t("Quantity", "Quantité", "_t")
t("Accept", "Accepter", "_t")
t("Cancel", "Annuler", "_t")
t("Error", "Erreur", "_t")
t("Enter a quantity.", "Entrer une quantité.", "_t")
------------------------------------------------
section "engine/engine/dialogs/GetText.lua"
t("Accept", "Accepter", "_t")
t("Cancel", "Annuler", "_t")
t("Error", "Erreur", "_t")
t("Must be between %i and %i characters.", "Doit être entre %i et %i caractères", "tformat")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/KeyBinder.lua"
t("Key bindings", "Affectation des touches", "_t")
t(" Press a key (escape to cancel, backspace to remove) for: %s", " Appuyer sur une touche (escape pour annuler, backspace pour supprimer) pour: %s", "tformat")
t("Bind key", "Affecter une touche", "_t")
t("Bind alternate key", "Affecter une touche alternative", "_t")
t("Make gesture (using right mouse button) or type it (or escape) for: %s", "Faire un geste (en utilisant le bouton droit de la souris) ou tapez-le (ou appuyer sur escape) pour: %s", "tformat")
t("Gesture", "Geste", "_t")
------------------------------------------------
section "engine/engine/dialogs/LanguageSelect.lua"
t("Language Selection", "Sélection de la langue", "_t")
------------------------------------------------
section "engine/engine/dialogs/ShowAchievements.lua"
t("Achievements(%s/%s)", "Succès(%s/%s)", "tformat")
t("Yours only", "Seulement les vôtres", "_t")
t("All achieved", "Tous les succès remportés", "_t")
t("Everything", "Tout", "_t")
t("Achievement", "Succès", "_t")
t("Category", "Catégorie", "_t")
t("When", "Quand", "_t")
t("Who", "Qui", "_t")
t([[#GOLD#Also achieved by your current character#LAST#
]], [[#GOLD#Également réalisé par votre personnage actuel#LAST#
]], "_t")
t([[#GOLD#Achieved on:#LAST# %s
#GOLD#Achieved by:#LAST# %s
%s
#GOLD#Description:#LAST# %s]], [[#GOLD#Réalisé le:#LAST# %s
#GOLD#Réalisé par:#LAST# %s
%s
#GOLD#Description:#LAST# %s]], "tformat")
t("Progress: ", "Progression: ", "_t")
t("-- Unknown --", "-- Inconnu --", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
t("???", "???", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowEquipInven.lua"
t("Inventory", "Inventaire", "_t")
t("Category", "Catégorie", "_t")
t("Enc.", "Enc", "_t")
t("Equipment", "Équipement", "_t")
t("Hotkey %s assigned", "Raccourci %s assigné", "tformat")
t("%s assigned to hotkey %s", "%s assigné au raccourci %s", "tformat")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowEquipment.lua"
t("Equipment", "Équipement", "_t")
t("Category", "Catégorie", "_t")
t("Enc.", "Enc", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowErrorStack.lua"
t("Lua Error", "Erreur Lua", "_t")
t("If you already reported that error, you do not have to do it again (unless you feel the situation is different).", "Si vous avez déjà signalé cette erreur, vous n'avez pas à le refaire (sauf si vous estimez que la situation est différente).", "_t")
t("You #LIGHT_GREEN#already reported#WHITE# that error, you do not have to do it again (unless you feel the situation is different).", "Vous #LIGHT_GREEN#avez déjà signalé#WHITE# cette erreur, vous n'avez pas à le refaire (sauf si vous estimez que la situation est différente).", "_t")
t("You have already got this error but #LIGHT_RED#never reported#WHITE# it, please do.", "Vous avez déjà eu cette erreur mais #LIGHT_RED#ne l'avez jamais signalée#WHITE#, faites-le s'il vous plait.", "_t")
t("You have #LIGHT_RED#never seen#WHITE# that error, please report it.", "Vous n'avez #LIGHT_RED#jamais vu#WHITE# cette erreur, s'il vous plaît, veuillez la signaler.", "_t")
t([[#{bold}#Oh my! It seems there was an error!
The game might still work but this is suspect, please type in your current situation and click on "Send" to send an error report to the game creator.
If you are not currently connected to the internet, please report this bug when you can on the forums at http://forums.te4.org/
]], [[#{bold}#Oh là là! Il semble qu'il y ait eu une erreur!
Le jeu peut encore fonctionner mais cela est suspect, veuillez saisir votre situation actuelle et cliquer sur "Envoyer" pour envoyer un rapport d'erreur au créateur du jeu.
Si vous n'êtes pas actuellement connecté à Internet, veuillez signaler ce bug lorsque vous le pourrez sur les forums à l'adresse http://forums.te4.org/
]], "_t")
t("What happened?: ", "Que s'est il passé?:", "_t")
t("Send", "Envoyer", "_t")
t("Close", "Fermer", "_t")
t("Close All", "Tout fermer", "_t")
t("Log saved to file (click to copy to clipboard):#LIGHT_BLUE#%s", "Log enregistré dans un fichier (cliquer pour copier dans le presse-papiers):#LIGHT_BLUE#%s", "tformat")
t("File location copied to clipboard.", "Emplacement du fichier copié dans le presse-papiers.", "log")
t("#YELLOW#Error report sent, thank you.", "#YELLOW#Rapport d'erreur envoyé, merci.", "log")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowInventory.lua"
t("Inventory", "Inventaire", "_t")
t("Category", "Catégorie", "_t")
t("Enc.", "Enc", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowPickupFloor.lua"
t("Pickup", "Ramasser", "_t")
t("(*) Take all", "(*) Tout prendre", "_t")
t("Item", "Objet", "_t")
t("Category", "Catégorie", "_t")
t("Enc.", "Enc", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowQuests.lua"
t("Quest Log for %s", "Journal de quête de %s", "tformat")
t("Quest", "Quête", "_t")
t("Status", "Statut", "_t")
------------------------------------------------
section "engine/engine/dialogs/ShowStore.lua"
t("Store", "Magasin", "_t")
t("Inventory", "Inventaire", "_t")
t("Category", "Catégorie", "_t")
t("Price", "Prix", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ShowText.lua"
t("Text", "Texte", "_t")
------------------------------------------------
section "engine/engine/dialogs/SteamOptions.lua"
t("Steam Options", "Options Steam", "_t")
t([[Enable Steam Cloud saves.
Your saves will be put on steam cloud and always be available everywhere.
Disable if you have bandwidth limitations.#WHITE#]], [[Activer les sauvegardes sur le cloud Steam.
Vos sauvegardes seront placées sur le cloud et seront toujours disponibles partout.
Désactivez le si vous avez des limitations de bande passante.#WHITE#]], "_t")
t("#GOLD##{bold}#Cloud Saves#WHITE##{normal}#", "#GOLD##{bold}#Sauvegardes cloud#WHITE##{normal}#", "_t")
t("enabled", "activé", "_t")
t("disabled", "désactivé", "_t")
t([[Purge all Steam Cloud saves.
This will remove all saves from the cloud cloud (but not your local copy). Only use if you somehow encounter storage problems on it (which should not happen, the game automatically manages it for you).#WHITE#]], [[Purger toutes les sauvegardes du cloud Steam.
Cela supprimera toutes les sauvegardes de Steam (mais pas votre copie locale). À n'utiliser que si vous rencontrez d'une manière ou d'une autre des problèmes de stockage sur celui-ci (ce qui ne devrait pas arriver, le jeu le gère automatiquement pour vous).#WHITE#]], "_t")
t("#GOLD##{bold}#Purge Cloud Saves#WHITE##{normal}#", "#GOLD##{bold}#Purger les sauvergardes du cloud Steam#WHITE##{normal}#", "_t")
t("Steam Cloud Purge", "Purge du cloud Steam", "_t")
t("Confirm purge?", "Confirmer la purge?", "_t")
t("All data purged from the cloud.", "Toutes les données ont été supprimées du cloud.", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/Talkbox.lua"
t("Say: ", "Dire: ", "_t")
t("Accept", "Accepter", "_t")
t("Cancel", "Annuler", "_t")
t("Target: ", "Cible: ", "_t")
t("Channel: %s", "Canal: %s", "tformat")
t("Friend: %s", "Ami: %s", "tformat")
t("User: %s", "Utilisateur: %s", "tformat")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/UseTalents.lua"
t("Use Talents: ", "Utiliser des talents: ", "tformat")
t([[You can bind a talent to a hotkey be pressing the corresponding hotkey while selecting a talent.
Check out the keybinding screen in the game menu to bind hotkeys to a key (default is 1-0 plus control or shift).
]], [[Vous pouvez lier un talent à un raccourci en appuyant sur la touche correspondante tout en sélectionnant un talent.
Consultez l'écran d'affectation des touches dans le menu du jeu pour lier les raccourcis à une touche (par défaut, 1-0 plus control ou shift).
]], "_t")
t("Status", "Statut", "_t")
t("Hotkey %s assigned", "Raccourci %s assigné", "tformat")
t("%s assigned to hotkey %s", "%s assigné au raccourci %s", "tformat")
-- texte non traduit
--[==[
t("", "", "_t")
t("Talent", "Talent", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/UserInfo.lua"
t("User: %s", "Utilisateur: %s", "tformat")
t("Currently playing: ", "Joue actuellement: ", "_t")
t("unknown", "inconnu", "_t")
t("Game: ", "Partie: ", "_t")
t("Game has been validated by the server", "La partie a été validée par le serveur", "_t")
t("Game is not validated by the server", "La partie n'est pas validée par le serveur", "_t")
t("Go to online profile", "Aller sur le profil en ligne", "_t")
t("Go to online charsheet", "Aller sur la feuille de personnage en ligne", "_t")
-- texte non traduit
--[==[
t("Validation: ", "Validation: ", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/VideoOptions.lua"
t("Video Options", "Options vidéo", "_t")
t("Display resolution.", "Résolution d'affichage.", "_t")
t("#GOLD##{bold}#Resolution#WHITE##{normal}#", "#GOLD##{bold}#Résolution#WHITE##{normal}#", "_t")
t("If you have a very high DPI screen you may want to raise this value. Requires a restart to take effect.#WHITE#", [[Si vous êtes sur un écran avec un DPI très élevé, vous pouvez vouloir augmenter cette valeur.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#Screen Zoom#WHITE##{normal}#", "#GOLD##{bold}#Zoom d'écran#WHITE##{normal}#", "_t")
t("Enter Zoom %", "Valeur de zoom %", "_t")
t("From 50 to 400", "De 50 à 400", "_t")
t([[Request this display refresh rate.
Set it lower to reduce CPU load, higher to increase interface responsiveness.#WHITE#]], [[Règle le taux de rafraîchissement (en images par seconde) de l'affichage.
Réglez-le à un niveau inférieur pour réduire la charge du processeur, à un niveau supérieur pour augmenter la réactivité de l'interface.#WHITE#]], "_t")
t("#GOLD##{bold}#Requested FPS#WHITE##{normal}#", "#GOLD##{bold}#Taux de rafraîchissement#WHITE##{normal}#", "_t")
t("Enter density", "Entrer la densité", "_t")
t("From 5 to 60", "De 5 à 60", "_t")
t([[Controls the particle effects density.
This option allows to change the density of the many particle effects in the game.
If the game is slow when displaying spell effects try to lower this setting.#WHITE#]], [[Contrôle la densité des effets des particules.
Cette option permet de modifier la densité des nombreux effets de particules dans le jeu.
Si le jeu est lent lors de l'affichage des effets de sorts, essayez de diminuer ce paramètre.#WHITE#]], "_t")
t("#GOLD##{bold}#Particle effects density#WHITE##{normal}#", "#GOLD##{bold}#Densité des effets des particules#WHITE##{normal}#", "_t")
t("From 0 to 100", "De 0 à 100", "_t")
t([[Activates antialiased texts.
Texts will look nicer but it can be slower on some computers.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les textes antialiasés.
Les textes seront plus beaux, mais cela peut faire ralentir sur certains ordinateurs.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#Antialiased texts#WHITE##{normal}#", "#GOLD##{bold}#Textes antialiasés#WHITE##{normal}#", "_t")
t("enabled", "activé", "_t")
t("disabled", "désactivé", "_t")
t([[Apply a global scaling to all fonts.
Applies after restarting the game]], [[Applique une mise à l'échelle globale à toutes les polices.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#Font Scale#WHITE##{normal}#", "#GOLD##{bold}#Mise à l'échelle des polices#WHITE##{normal}#", "_t")
t("Font Scale %", "Échelle des polices en %", "_t")
t("From 50 to 300", "De 50 à 300", "_t")
t([[Activates framebuffers.
This option allows for some special graphical effects.
If you encounter weird graphical glitches try to disable it.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les framebuffers.
Cette option permet d'obtenir certains effets graphiques spéciaux.
Si vous rencontrez des problèmes graphiques, essayez de les désactiver.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#Framebuffers#WHITE##{normal}#", "#GOLD##{bold}#tampon de trame#WHITE##{normal}#", "_t")
t([[Activates OpenGL Shaders.
This option allows for some special graphical effects.
If you encounter weird graphical glitches try to disable it.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les shaders OpenGL.
Cette option permet d'obtenir certains effets graphiques spéciaux.
Si vous rencontrez des problèmes graphiques, essayez de les désactiver.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#OpenGL Shaders#WHITE##{normal}#", "#GOLD##{bold}#Shaders OpenGL#WHITE##{normal}#", "_t")
t([[Activates advanced shaders.
This option allows for advanced effects (like water surfaces, ...). Disabling it can improve performance.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les shaders avancés.
Cette option permet d'obtenir des effets avancés (comme les surfaces d'eau, ...). Sa désactivation peut améliorer les performances.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#OpenGL Shaders: Advanced#WHITE##{normal}#", "#GOLD##{bold}#Shaders OpenGL avancés#WHITE##{normal}#", "_t")
t([[Activates distorting shaders.
This option allows for distortion effects (like spell effects doing a visual distortion, ...). Disabling it can improve performance.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les shaders de distorsion.
Cette option permet d'obtenir des effets de distorsion (comme les effets de sort qui provoquent une distorsion visuelle, ...). Sa désactivation peut améliorer les performances.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#OpenGL Shaders: Distortions#WHITE##{normal}#", "#GOLD##{bold}#Shaders OpenGL de distorsion#WHITE##{normal}#", "_t")
t([[Activates volumetric shaders.
This option allows for volumetricion effects (like deep starfields). Enabling it will severely reduce performance when shaders are displayed.
#LIGHT_RED#You must restart the game for it to take effect.#WHITE#]], [[Active les shaders volumétriques.
Cette option permet d'obtenir des effets volumétriques (comme les champs d'étoiles en profondeur). L'activer réduira considérablement les performances lorsque les shaders sont affichés.
#LIGHT_RED#Nécessite un redémarrage pour prendre effet.#WHITE#]], "_t")
t("#GOLD##{bold}#OpenGL Shaders: Volumetric#WHITE##{normal}#", "#GOLD##{bold}#Shaders OpenGL volumétriques#WHITE##{normal}#", "_t")
t([[Use the custom cursor.
Disabling it will use your normal operating system cursor.#WHITE#]], [[Utilise le curseur personnalisé.
En le désactivant, vous utiliserez le curseur de votre système d'exploitation.#WHITE#]], "_t")
t("#GOLD##{bold}#Mouse cursor#WHITE##{normal}#", "#GOLD##{bold}#Curseur de souris#WHITE##{normal}#", "_t")
t([[Gamma correction setting.
Increase this to get a brighter display.#WHITE#]], [[Réglage de la correction gamma.
Augmentez ce réglage pour obtenir un affichage plus lumineux.#WHITE#]], "_t")
t("#GOLD##{bold}#Gamma correction#WHITE##{normal}#", "#GOLD##{bold}#Correction gamma#WHITE##{normal}#", "_t")
t("Gamma correction", "Correction gamma", "_t")
t([[Enable/disable usage of tilesets.
In some rare cases on very slow machines with bad GPUs/drivers it can be detrimental.]], [[Activer/désactiver l'utilisation des tilesets.
Dans de rares cas, sur des machines très lentes avec de mauvais GPU/pilotes, cela peut être préjudiciable.]], "_t")
t("#GOLD##{bold}#Use tilesets#WHITE##{normal}#", "#GOLD##{bold}#Utilisation des tilesets#WHITE##{normal}#", "_t")
t([[Request a specific origin point for the game window.
This point corresponds to where the upper left corner of the window will be located.
Useful when dealing with multiple monitors and borderless windows.
The default origin is (0,0).
Note: This value will automatically revert after ten seconds if not confirmed by the user.#WHITE#]], [[Demandez un point d'origine spécifique pour la fenêtre de jeu.
Ce point correspond à l'endroit où le coin supérieur gauche de la fenêtre sera situé.
Utile lorsque vous avez plusieurs moniteurs et des fenêtres sans bordure.
L'origine par défaut est (0,0).
Note : Cette valeur sera automatiquement réinitialisée au bout de dix secondes si elle n'est pas confirmée par l'utilisateur.#WHITE#]], "_t")
t("#GOLD##{bold}#Requested Window Position#WHITE##{normal}#", "#GOLD##{bold}#Position de la fenêtre#WHITE##{normal}#", "_t")
t("Window Origin: X-Coordinate", "Origine X de la fenêtre", "_t")
t("Enter the x-coordinate", "Entrer la coordonnée X", "_t")
t("Window Origin: Y-Coordinate", "Origine Y de la fenêtre", "_t")
t("Enter the y-coordinate", "Entrer la coordonnée Y", "_t")
t("Position changed.", "Position modifiée", "_t")
t("Save position?", "Sauvegarde de la position?", "_t")
t("Accept", "Accepter", "_t")
t("Revert", "Revenir en arrière", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/ViewHighScores.lua"
t("High Scores", "Meilleurs scores", "_t")
------------------------------------------------
section "engine/engine/dialogs/microtxn/MTXMain.lua"
t("%s #GOLD#Purchasables#LAST#", "%s #GOLD#Produits achetables#LAST#", "tformat")
t("Online Store", "Boutique en ligne", "_t")
t([[Welcome!
I am #{italic}##ANTIQUE_WHITE#DarkGod#LAST##{normal}#, the creator of the game and before you go on your merry way I wish to take a few seconds of your time to explain why there are microtransactions in the game.
Before you run off in terror let me put it plainly: I am very #{bold}#firmly #CRIMSON#against#LAST# pay2win#{normal}# things so rest assured I will not add this kind of stuff.
So why put microtransactions? Tales of Maj'Eyal is a cheap/free game and has no subscription required to play. It is my baby and I love it; I plan to work on it for many years to come (as I do since 2009!) but for it to be viable I must ensure a steady stream of income as this is sadly the state of the world we live in.
As for what kind of purchases are/will be available:
- #GOLD#Cosmetics#LAST#: in addition to the existing racial cosmetics & item shimmers available in the game you can get new packs of purely cosmetic items & skins to look even more dapper!
- #GOLD#Pay2DIE#LAST#: Tired of your character? End it with style!
- #GOLD#Vault space#LAST#: For those that donated they can turn all those "useless" donations into even more online vault slots.
- #GOLD#Community events#LAST#: A few online events are automatically and randomly triggered by the server. With those options you can force one of them to trigger; bonus point they trigger for the whole server so everybody online benefits from them each time!
I hope I've convinced you of my non-evil intentions (ironic for a DarkGod I know ;)). I must say feel dirty doing microtransactions even as benign as those but I want to find all the ways I can to ensure the game's future.
Thanks, and have fun!]], [[Bienvenue!
Je suis #{italic}##ANTIQUE_WHITE#DarkGod#LAST##{normal}#, le créateur du jeu et avant que vous ne continuiez votre joyeux chemin, je souhaite prendre quelques secondes de votre temps pour vous expliquer pourquoi il y a des microtransactions dans le jeu.
Avant que vous ne vous enfuyez de terreur, laissez-moi vous expliquer clairement: Je suis très #{bold}#fermement #CRIMSON#contre#LAST# le pay2win#{normal}# alors soyez assuré que je n'ajouterai pas ce genre de choses.
Alors pourquoi intégrer des microtransactions? Tales of Maj'Eyal est un jeu bon marché/gratuit et ne nécessite pas d'abonnement pour y jouer. C'est mon bébé et je l'adore; je compte y travailler pendant encore de nombreuses années (comme je le fais depuis 2009!) mais pour qu'il soit viable, je dois m'assurer un flux de revenus régulier car c'est malheureusement l'état du monde dans lequel nous vivons.
Quant à savoir quels types d'achats sont/seront disponibles:
- #GOLD#Cosmetiques#LAST#: en plus des produits cosmétiques et chatoyants existants dans le jeu, vous pouvez obtenir de nouveaux packs d'articles et de peaux purement cosmétiques pour avoir l'air encore plus élégant!
- #GOLD#Pay2DIE#LAST#: Vous en avez assez de votre personnage? Finissez-en avec style!
- #GOLD#Espace de stockage du coffre-fort#LAST#: Pour ceux qui ont fait des dons, ils peuvent transformer tous ces dons "inutiles" en encore plus de places de stockage dans leur coffre-fort en ligne.
- #GOLD#Evènements communautaires#LAST#: Quelques évènements en ligne sont automatiquement et aléatoirement déclenchés par le serveur. Avec ces options, vous pouvez forcer l'un d'entre eux à se déclencher; points bonus, ils se déclenchent pour l'ensemble du serveur afin que tous les joueurs en ligne en profitent à chaque fois!
J'espère vous avoir convaincu de mes intentions non diaboliques (ironie pour un dieu des ténèbres que je suis ;)). Je dois dire que je me sens sale de faire des microtransactions même aussi bénignes que celles-ci mais je veux trouver tous les moyens possibles pour assurer l'avenir du jeu.
Merci, et amusez-vous bien!]], "_t")
------------------------------------------------
section "engine/engine/dialogs/microtxn/ShowPurchasable.lua"
t("#{italic}##UMBER#Bonus vault slots from this order: #ROYAL_BLUE#%d#{normal}#", "#{italic}##UMBER#Emplacements de stockage du coffre-fort en bonus pour cette commande: #ROYAL_BLUE#%d#{normal}#", "_t")
t([[For every purchase of #{italic}##GREY#%s#LAST##{normal}# you gain a permanent additional vault slot.
#GOLD##{italic}#Because why not!#{normal}#]], [[Pour chaque achat de #{italic}##GREY#%s#LAST##{normal}# vous gagnez une place de stockage additionelle dans votre coffre-fort.
#GOLD##{italic}#Parce que pourquoi pas!#{normal}#]], "_t")
t("#{italic}##UMBER#Voratun Coins available from your donations: #ROYAL_BLUE#%d#{normal}#", "#{italic}##UMBER#Pièces de voratun disponible grâce a vos donations: #ROYAL_BLUE#%d#{normal}#", "_t")
t([[For every donations you've ever made you have earned voratun coins. These can be spent purchasing expansions or options on the online store. This is the amount you have left, if your purchase total is below this number you'll instantly get your purchase validated, if not you'll need to donate some more first.
#GOLD##{italic}#Thanks for your support, every little bit helps the game survive for years on!#{normal}#]], [[Pour chaque don que vous avez fait, vous avez gagné des pièces de voratun. Vous pouvez les dépenser en achetant des extensions ou des options sur la boutique en ligne. C'est le montant qu'il vous reste. Si le total de vos achats est inférieur à ce chiffre, votre achat sera instantanément validé, sinon vous devrez d'abord faire un don supplémentaire.
#GOLD##{italic}#Merci pour votre soutien, chaque don aide le jeu à survivre pour les années à venir!#{normal}#]], "_t")
t("%s #GOLD#Online Store#LAST#", "%s #GOLD#Boutique en ligne#LAST#", "tformat")
t("#YELLOW#-- connecting to server... --", "#YELLOW#-- connexion au serveur... --", "_t")
t("Purchase", "Acheter", "_t")
t("Name", "Nom", "_t")
t("Price", "Prix", "_t")
t("Qty", "Qté", "_t")
t("Online Store", "Boutique en ligne", "_t")
t("You need to be logged in before using the store. Please go back to the main menu and login.", "Vous devez être connecté avant d'utiliser le magasin. S'il vous plaît, revenez au menu principal et connectez vous.", "_t")
t("Steam users need to link their profiles to their steam account. This is very easy in just a few clicks. Once this is done, simply restart the game.", "Les utilisateurs de Steam doivent relier leur profil à leur compte Steam. C'est très simple, juste quelques clics. Une fois que cela est fait, il suffit de relancer le jeu.", "_t")
t("Let's do it! (Opens in your browser)", "Allons y! (S'ouvre dans votre navigateur internet)", "_t")
t("Not now", "Pas maintenant", "_t")
t("The Online Store (and expansions) are only purchasable by players that bought the game. Plaese go have a look at the donation page for more explanations.", "La boutique en ligne (et les extensions) sont seulement achetables par les joueurs qui ont acheté le jeu. Allez voir la page des donations pour plus d'explications s'il vous plait.", "_t")
t("Let's go! (Opens in your browser)", "Allons y! (S'ouvre dans votre navigateur internet)", "_t")
t("%d coins", "%d pièces", "tformat")
t(" (%d items in cart, %s)", " (%d objets dans le panier, %s)", "tformat")
t("Cart", "Panier", "_t")
t("Cart is empty!", "Votre panier est vide", "_t")
t([[In-game browser is inoperant or disabled, impossible to auto-install shimmer pack.
Please go to https://te4.org/ to download it manually.]], [[Le navigateur en jeu est inopérant ou désactivé, impossible d'auto-installer le pack chatoyant.
Allez sur https://te4.org pour le télécharger manuellement s'il vous plait.]], "_t")
t("Shimmer pack installed!", "Pack chatoyant installé!", "_t")
t([[Could not dynamically link addon to current character, maybe the installation weng wrong.
You can fix that by manually downloading the addon from https://te4.org/ and placing it in game/addons/ folder.]], [[Impossible de lier dynamiquement l'addon au personnage actuel, peut-être que l'installation s'est mal déroulée.
Vous pouvez remédier à cela en téléchargeant manuellement l'addon à partir de https://te4.org/ et en le plaçant dans le dossier game/addons/.]], "_t")
t("Downloading cosmetic pack: #LIGHT_GREEN#%s", "Téléchargement du pack cosmetique: #LIGHT_GREEN#%s", "tformat")
t("- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: The pack should be downloading or even finished by now.", "- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: Le pack devrait être en téléchargement ou même déjà fini maintenant.", "tformat")
t("- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: You can now trigger it whenever you are ready.", "- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: Vous pouvez maintenant l'activer dès que vous êtes prêt.", "tformat")
t("- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: Your available vault space has increased.", "- #{bold}##ROYAL_BLUE#%s #SLATE#x%d#WHITE##{normal}#: L'espace de stockage de votre coffre-fort a augmenté.", "tformat")
t("Payment", "Paiement", "_t")
t([[Payment accepted.
%s]], [[Paiement accepté.
%s]], "tformat")
t("Connecting to Steam", "Connexion à Steam", "_t")
t("Steam Overlay should appear, if it does not please make sure it you have not disabled it.", "Le Steam Overlay devrait apparaître, si ce n'est pas le cas, soyez sûr de ne pas l'avoir désactivé.", "_t")
t("Finalizing transaction with Steam servers...", "Finalisation de la transaction avec les serveurs Steam...", "_t")
t("Payment refused, you have not been billed.", "Paiement refusé, vous n'avez pas été facturé.", "_t")
t("Connecting to server", "Connexion au serveur", "_t")
t("Please wait...", "Patientez s'il vous plait...", "_t")
t("You have enough coins to instantly purchase those options. Confirm?", "Vous avez suffisamment de pièces pour acheter instantanément ces options. Confirmer?", "_t")
t("Cancel", "Annuler", "_t")
t("You need %s more coins to purchase those options. Do you want to go to the donation page now?", "Vous avez besoin de %s pièces supplémentaires pour acheter ces options. Voulez vous aller sur la page de donations maintenant?", "tformat")
t([[#{bold}##GOLD#Community Online Event#WHITE##{normal}#: Once you have purchased a community event you will be able to trigger it at any later date, on whichever character you choose.
Community events once triggered will activate for #{bold}#every player currently logged on#{normal}# including yourself. Every player receiving it will know you sent it and thus that you are to thank for it.
To activate it you will need to have your online events option set to "all" (which is the default value).]], [[#{bold}##GOLD#Événement communautaire en ligne#WHITE##{normal}#: Une fois que vous avez acheté un événement communautaire, vous pouvez l'appliquer quand vous le souhaitez, sur le personnage que vous voulez.
Une fois un événement communautaire activé il le sera #{bold}#pour chaque joueur actuellement connecté#{normal}# vous inclus. Chaque joueur saura que vous l'avez activé et pourra vous remercier pour cela.
Pour l'activer vous devrez avoir l'option des événements en ligne paramétré sur "tous" (ce qui est la valeur par défaut).]], "_t")
t([[#{bold}##GOLD#Event#WHITE##{normal}#: Once you have purchased an event you will be able to trigger it at any later date, on whichever character you choose.
To activate it you will need to have your online events option set to "all" (which is the default value).]], [[#{bold}##GOLD#Événement#WHITE##{normal}#: Une fois que vous avez acheté un événement, vous pouvez l'appliquer quand vous le souhaitez, sur le personnage que vous voulez.
Pour l'activer vous devrez avoir l'option des événements en ligne paramétré sur "tous" (ce qui est la valeur par défaut).]], "_t")
t("#{bold}##GOLD#Non Immediate#WHITE##{normal}#: This events adds new content that you have to find by exploration. If you die before finding it, there can be no refunds.", "#{bold}##GOLD#Non Immédiat#WHITE##{normal}#: Cet événement ajoute du contenu que l'on doit trouver en explorant. Si vous mourrez avant de le trouver, il n'y aura pas de remboursement.", "_t")
t("#{bold}##GOLD#Once per Character#WHITE##{normal}#: This event can only be received #{bold}#once per character#{normal}#. Usualy because it adds a new zone or effect to the game that would not make sense to duplicate.", "#{bold}##GOLD#Une fois par personnage#WHITE##{normal}#: Cet événement peut seulement être reçu #{bold}#une fois par personnage#{normal}#. Tout simplement car il ajoute une nouvelle zone au jeu et que cela n'aurait aucun sens de le dupliquer.", "_t")
t([[#{bold}##GOLD#Shimmer Pack#WHITE##{normal}#: Once purchased the game will automatically install the shimmer pack to your game and enable it for your current character too (you will still need to use the Mirror of Reflection to switch them on).
#LIGHT_GREEN#Bonus perk:#LAST# purchasing any shimmer pack will also give your characters a portable Mirror of Reflection to be able to change your appearance anywhere, anytime!]], [[#{bold}##GOLD#Pack Chatoyant#WHITE##{normal}#: Une fois acheté le jeu installera automatiquement le pack chatoyant à votre jeu et l'activera pour tous vos personnages y compris l'actuel (vous aurez cependant toujours besoin d'utiliser le Miroir Réfléchissant pour l'utiliser).
#LIGHT_GREEN#Cadeau bonus:#LAST# acheter un pack chatoyant donnera aussi a vos personnages un Miroir Réfléchissant portable et vous permettra de changer votre apparence n'importe où, n'importe quand!]], "_t")
t("#{bold}##GOLD#UI Pack#WHITE##{normal}#: Once purchased the game will automatically install the UI pack to your game.", "#{bold}##GOLD#Pack IU#WHITE##{normal}#: Une fois acheté le jeu installera automatiquement le pack IU (Interface Utilisateur) à votre jeu.", "_t")
t("#{bold}##GOLD#Vault Space#WHITE##{normal}#: Once purchased your vault space is permanently increased.", "#{bold}##GOLD#Espace de stockage du coffre-fort#WHITE##{normal}#: Une fois acheté, l'espace de stockage de votre coffre-fort augmente de façon permanente.", "_t")
-- texte non traduit
--[==[
t("%0.2f %s", "%0.2f %s", "tformat")
t("#{bold}#TOTAL#{normal}#", "#{bold}#TOTAL#{normal}#", "_t")
--]==]
------------------------------------------------
section "engine/engine/dialogs/microtxn/UsePurchased.lua"
t("%s #GOLD#Purchased Options#LAST#", "%s #GOLD#Options Achetées#LAST#", "tformat")
t("#YELLOW#-- connecting to server... --", "#YELLOW#-- connexion au serveur... --", "_t")
t("Name", "Nom", "_t")
t("Available", "Disponible", "_t")
t("Please use purchased options when not on the worldmap.", "S'il vous plaît, utilisez une option achetée quand vous n'êtes pas sur la carte du monde.", "_t")
t("This option may only be used once per character to prevent wasting it.", "Cette option ne peut être utilisée qu'une fois par personnage pour éviter de la gâcher.", "_t")
t([[This option requires you to accept to receive events from the server.
Either you have the option currently disabled or you are playing a campaign that can not support these kind of events (mainly the Arena).
Make sure you have #GOLD##{bold}#Allow online events#WHITE##{normal}# in the #GOLD##{bold}#Online#WHITE##{normal}# section of the game options set to "all". You can set it back to your own setting once you have received the event.
]], [[Cette option exige que vous acceptiez de recevoir des événements du serveur.
Soit vous avez l'option actuellement désactivée, soit vous jouez une campagne qui ne peut pas soutenir ce genre d'événements (principalement l'Arène).
Assurez-vous d'avoir #GOLD##{bold}#Permettre les événements en ligne#WHITE##{normal}# dans la section #GOLD##{bold}#En ligne#WHITE##{normal}# des options du jeu réglée sur "tous". Vous pouvez revenir à votre propre réglage une fois que vous avez reçu l'événement.
]], "_t")
t("This pack is already installed and in use for your character.", "Ce pack est déjà installé et actif pour votre personnage.", "_t")
t("You are about to use a charge of this option. You currently have %d charges remaining.", "Vous êtes sur le point d'utiliser une charge de cette option. Vous avez actuellement %d charges restantes.", "tformat")
t("Please wait while contacting the server...", "S'il vous plaît, patientez pendant que nous contactons le serveur...", "_t")
t("The option has been activated.", "Cette option a été activée", "_t")
t("There was an error from the server: %s", "Il y a eu une erreur du serveur: %s", "tformat")
t("Online Store", "Boutique en ligne", "_t")
t("#LIGHT_GREEN#Installed", "#LIGHT_GREEN#Installé", "_t")
t("You have not purchased any usable options yet. Would you like to see the store?", "Vous n'avez actuellement acheté aucune option utilisable. Voulez-vous voir la boutique?", "_t")
-- texte non traduit
--[==[
t("#YELLOW#Installable", "#YELLOW#Installable", "_t")
--]==]
------------------------------------------------
section "engine/engine/interface/ActorInventory.lua"
t("%s picks up (%s.): %s%s.", "%s ramasse (%s.): %s%s.", "logSeen")
t("%s has no room for: %s.", "%s n'a pas de place pour: %s.", "logSeen")
t("There is nothing to pick up here.", "Il n'y a rien à ramasser ici.", "logSeen")
t("There is nothing to drop.", "Il n'y a rien à jeter.", "logSeen")
t("%s drops on the floor: %s.", "%s jette: %s au sol.", "logSeen")
t("wrong equipment slot", "mauvais emplacement pour cet équipement", "_t")
t("not enough stat", "stat insuffisantes", "_t")
t("missing %s (level %s )", "manque %s (niveau %s )", "tformat")
t("missing %s", "manque %s", "tformat")
t("not enough levels", "niveaux insuffisants", "_t")
t("missing dependency", "dépendance manquante", "_t")
t("cannot use currently due to an other worn object", "ne peut pas être utilisé maintenant à cause d'un autre objet", "_t")
t("%s is not wearable.", "%s ne peut être porté.", "logSeen")
t("%s can not wear %s.", "%s ne peut pas porter %s.", "logSeen")
t("%s can not wear (%s): %s (%s).", "%s ne peut pas porter (%s): %s (%s).", "logSeen")
t("%s wears: %s.", "%s porte: %s.", "logSeen")
t("%s wears (offslot): %s.", "%s porte (offslot): %s.", "logSeen")
t("%s wears (replacing %s): %s.", "%s porte (remplace %s): %s.", "logSeen")
t("%s can not wear: %s.", "%s ne peut pas porter: %s.", "logSeen")
------------------------------------------------
section "engine/engine/interface/ActorLife.lua"
t("#{bold}#%s killed %s!#{normal}#", "#{bold}#%s a tué %s!#{normal}#", "logSeen")
t("something", "quelque chose", "_t")
t("%s attacks %s.", "%s attaque %s.", "logSeen")
------------------------------------------------
section "engine/engine/interface/ActorTalents.lua"
t("%s is still on cooldown for %d turns.", "%s est encore en rechargement pour %d tours.", "logPlayer")
t("Talent Use Confirmation", "Confirmation d'utilisation d'un Talent", "_t")
t("Use %s?", "Utiliser %s?", "tformat")
t("Cancel", "Annuler", "_t")
t("Continue", "Continuer", "_t")
t("unknown", "inconnu", "entity name")
t("deactivates", "désactive", "_t")
t("activates", "activé", "_t")
t("%s uses %s.", "%s utilise %s.", "logSeen")
t("not enough stat: %s", "pas assez de stat: %s", "tformat")
t("not enough levels", "niveaux insuffisants", "_t")
t("missing dependency", "dépendance manquante", "_t")
t("is not %s", "n'est pas %s", "tformat")
t("unknown talent type", "type de talent inconnu", "_t")
t("not enough talents of this type known", "pas assez de talents de ce type connus", "_t")
t("- Talent category known", "- Catégorie de talent connue", "_t")
t("- Lower talents of the same category: %d", "- Talents inférieur de la même catégorie: %d", "tformat")
t("- Level %d", "- Niveau %d", "tformat")
t("- Talent %s (not known)", "- Talent %s (non connu)", "tformat")
t("- Is %s", "- est %s", "tformat")
-- texte non traduit
--[==[
t("%s", "%s", "logSeen")
t("%s %s %s.", "%s %s %s.", "logSeen")
t("- Talent %s (%d)", "- Talent %s (%d)", "tformat")
t("- Talent %s", "- Talent %s", "tformat")
--]==]
-- ancien texte traduit
t("unknown", "inconnu", "_t")
------------------------------------------------
section "engine/engine/interface/GameTargeting.lua"
t("Tactical display disabled. Press shift+'t' to enable.", "Affichage tactique désactivé. Pressez Shift+'t' pour l'activer.", "_t")
t("Target yourself?", "Se cibler?", "_t")
t("Are you sure you want to target yourself?", "Êtes vous sûr de vouloir vous cibler?", "_t")
t("No", "Non", "_t")
t("Yes", "Oui", "_t")
t("Tactical display enabled. Press shift+'t' to disable.", "Affichage tactique activé. Pressez Shift+'t' pour le désactiver.", "_t")
------------------------------------------------
section "engine/engine/interface/ObjectActivable.lua"
t("It can be used to %s, with %d charges out of %d.", "Peut être utilisé en %s, avec %d charges sur %d.", "tformat")
t("It can be used to %s, costing %d power out of %d/%d.", "Peut être utilisé en %s, coutant %d de pouvoir sur %d/%d.", "tformat")
t("It can be used to activate talent: %s (level %d).", "Peut être utilisé pour activer le talent: %s (niveau %d).", "tformat")
t("It can be used to activate talent: %s (level %d), costing %d power out of %d/%d.", "Peut être utilisé pour activer le talent: %s (niveau %d), coutant %d de pouvoir sur %d/%d.", "tformat")
t("%s is still recharging.", "%s est encore en rechagement.", "logPlayer")
t("%s can not be used anymore.", "%s ne peut plus être utilisé", "logPlayer")
------------------------------------------------
section "engine/engine/interface/PlayerExplore.lua"
t("Running...", "Cours...", "_t")
t("You are exploring, press any key to stop.", "Vous êtes en exploration, appuyez sur une touche pour vous arrêter.", "_t")
t("the path is blocked", "Le chemin est bloqué", "_t")
------------------------------------------------
section "engine/engine/interface/PlayerHotkeys.lua"
t("Hotkey not defined", "Raccourci non défini", "_t")
t("You may define a hotkey by pressing 'm' and following the instructions there.", "Vous pouvez définir un raccourci en pressant 'm' et en suivant les instructions.", "_t")
t("Item not found", "Objet non trouvé", "_t")
t("You do not have any %s .", "Vous n'avez pas de %s .", "tformat")
------------------------------------------------
section "engine/engine/interface/PlayerMouse.lua"
t("[CHEAT] teleport to %dx%d", "[TRICHE] téléportation à %dx%d", "log")
------------------------------------------------
section "engine/engine/interface/PlayerRest.lua"
t("resting", "Le repos", "_t")
t("rested", "s'est reposé", "_t")
t("You are %s, press Enter to stop.", "Vous êtes %s, appuyez sur Entrée pour arrêter.", "tformat")
t("%s starts...", "%s commence...", "log")
t("%s for %d turns (stop reason: %s).", "%s durant %d tours (raison de l'arrêt: %s)", "log")
t("%s for %d turns.", "%s durant %d tours.", "log")
-- texte non traduit
--[==[
t("%s...", "%s...", "tformat")
--]==]
------------------------------------------------
section "engine/engine/interface/PlayerRun.lua"
t("Running...", "Cours...", "_t")
t("You are running, press Enter to stop.", "Vous êtes en train de courir, appuyez sur Entrée pour arrêter.", "_t")
t("You don't see how to get there...", "Vous ne voyez pas comment aller là bas...", "logPlayer")
t("You are running, press any key to stop.", "Vous êtes en train de courir, appuyez sur une touche pour vous arrêter.", "_t")
t("didn't move", "n'a pas bougé", "_t")
t("trap spotted", "piège détecté", "_t")
t("terrain change on the left", "le terrain a changé à gauche", "_t")
t("terrain change on the right", "le terrain a changé à droite", "_t")
t("at %s", "à %s", "tformat")
t("Ran for %d turns (stop reason: %s).", "A couru durant %d tours (raison de l'arrêt: %s).", "log")
------------------------------------------------
section "engine/engine/interface/WorldAchievements.lua"
t("#%s#Personal New Achievement: %s!", "#%s#Nouveau Succès Personnel: %s!", "log")
t("Personal New Achievement: #%s#%s", "Nouveau Succès Personnel: #%s#%s", "tformat")
t("#%s#New Achievement: %s!", "#%s#Nouveau Succès: %s!", "log")
t("New Achievement: #%s#%s", "Nouveau Succès: #%s#%s", "tformat")
t("New Achievement", "Nouveau Succès", "_t")
------------------------------------------------
section "engine/engine/ui/Dialog.lua"
t("Close", "Fermer", "_t")
t("Yes", "Oui", "_t")
t("No", "Non", "_t")
t("Cancel", "Annuler", "_t")
t("Copy URL", "Copier l'URL", "_t")
t("URL copied to your clipboard.", "URL copiée dans votre presse-papiers.", "_t")
------------------------------------------------
section "engine/engine/ui/Gestures.lua"
t("Mouse Gestures", "Mouvement de Souris", "_t")
t([[You have started to draw a mouse gesture for the first time!
Gestures allow you to use talents or keyboard action by a simple movement of the mouse. To draw one you simply #{bold}#hold right click + move#{normal}#.
By default no bindings are done for gesture so if you want to use them go to the Keybinds and add some, it's easy and fun!
Gestures movements are color coded to better display which movement to do:
#15ed2f##{italic}#green#{normal}##LAST#: moving up
#1576ed##{italic}#blue#{normal}##LAST#: moving down
#ed1515##{italic}#red#{normal}##LAST#: moving left
#d6ed15##{italic}#yellow#{normal}##LAST#: moving right
If you do not wish to see gestures anymore, you can hide them in the UI section of the Game Options.
]], [[Vous avez commencé à dessiner un geste avec la souris pour la première fois!
Les gestes vous permettent d'utiliser des talents ou des actions au clavier par un simple mouvement de souris. Pour en dessiner un, il vous suffit de #{bold}#maintenir le clic droit + déplacer#{normal}#.
Par défaut, aucun raccourci n'est fait pour les gestes, donc si vous voulez les utiliser, allez dans les Raccourcis et ajoutez-en, c'est facile et amusant!
Les mouvements des gestes sont codés par couleur pour mieux afficher le mouvement à faire:
#15ed2f##{italic}#vert#{normal}##LAST#: déplacement en haut
#1576ed##{italic}#bleu#{normal}##LAST#: déplacement en bas
#ed1515##{italic}#rouge#{normal}##LAST#: déplacement à gauche
#d6ed15##{italic}#jaune#{normal}##LAST#: déplacement à droite
Si vous ne souhaitez plus voir les gestes, vous pouvez les cacher dans la section IU des options du jeu.
]], "_t")
------------------------------------------------
section "engine/engine/ui/Inventory.lua"
t("Inventory", "Inventaire", "_t")
t("Category", "Catégorie", "_t")
t("Enc.", "Enc", "_t")
-- texte non traduit
--[==[
t("", "", "_t")
--]==]
------------------------------------------------
section "engine/engine/ui/WebView.lua"
t("Download: ", "Télécharger: ", "tformat")
t("Cancel", "Annuler", "_t")
t("Confirm addon install/update", "Confirmer l'installation ou la mise à jour de l'addon", "_t")
t("Are you sure you want to install this addon: #LIGHT_GREEN##{bold}#%s#{normal}##LAST# ?", "Êtes vous sûr de vouloir installer cet addon: #LIGHT_GREEN##{bold}#%s#{normal}##LAST#?", "_t")
t("Confirm module install/update", "Confirmer l'installation ou la mise à jour du module", "_t")
t("Are you sure you want to install this module: #LIGHT_GREEN##{bold}#%s#{normal}##LAST#?", "Êtes vous sûr de vouloir installer ce module: #LIGHT_GREEN##{bold}#%s#{normal}##LAST#?", "tformat")
t("Addon installed!", "Addon installé!", "_t")
t("Addon installation successful. New addons are only active for new characters.", "Addon installé avec succès. Les nouveaux addons ne sont actifs que pour les nouveaux personnages.", "_t")
t("Game installed!", "Jeu installé!", "_t")
t("Game installation successful. Have fun!", "Jeu installé avec succès. Amusez vous bien!", "_t")
------------------------------------------------
section "engine/engine/utils.lua"
t("%dth", "%dième", "_t")
t("%dst", "%dier", "_t")
t("%dnd", "%dième", "_t")
t("%drd", "%dième", "_t")
t("an ", "un ", "_t")
t("a ", "un ", "_t")
t("she", "elle", "_t")
t("it", "il", "_t")
t("he", "il", "_t")
t("her", "sa", "_t")
t("its", "son", "_t")
t("his", "son", "_t")
t("him", "lui", "_t")
t("herself", "elle-même", "_t")
t("itself", "lui-même", "_t")
t("himself", "lui-même", "_t")
<file_sep>/tome-items-vault.lua
------------------------------------------------
section "tome-items-vault/data/entities/fortress-grids.lua"
-- nouveau texte
--[==[
t("Item's Vault Control Orb", "Item's Vault Control Orb", "entity name")
--]==]
------------------------------------------------
section "tome-items-vault/init.lua"
-- nouveau texte
--[==[
t("Items Vault", "Items Vault", "init.lua long_name")
t("Adds access to the items vault (donator feature). The items vault will let you upload a few unwanted items to your online profile and retrieve them on other characters.", "Adds access to the items vault (donator feature). The items vault will let you upload a few unwanted items to your online profile and retrieve them on other characters.", "init.lua description")
--]==]
------------------------------------------------
section "tome-items-vault/overload/data/chats/items-vault-command-orb-offline.lua"
t("[Leave the orb alone]", "[Laisser l'orbe tranquille]", "_t")
-- nouveau texte
--[==[
t("Transfering this item will place a level %d requirement on it, since it has no requirements. ", "Transfering this item will place a level %d requirement on it, since it has no requirements. ", "tformat")
t("Some properties of the item will be lost upon transfer, since they are class- or talent-specific. ", "Some properties of the item will be lost upon transfer, since they are class- or talent-specific. ", "_t")
t([[*#LIGHT_GREEN#This orb seems to be some kind of interface to an extra-dimentional vault of items.
All your characters in alternate universes will be able to access it from here.
Only items from a validated game versions are uploadable.#WHITE#*
#CRIMSON#Offline mode#WHITE#: The item's vault works even without a network connection but items will thus only be saved on your computer and can not be shared to an other one.
The offline vault is only available when offline and contains 3 slots.]], [[*#LIGHT_GREEN#This orb seems to be some kind of interface to an extra-dimentional vault of items.
All your characters in alternate universes will be able to access it from here.
Only items from a validated game versions are uploadable.#WHITE#*
#CRIMSON#Offline mode#WHITE#: The item's vault works even without a network connection but items will thus only be saved on your computer and can not be shared to an other one.
The offline vault is only available when offline and contains 3 slots.]], "_t")
t("[Place an item in the vault]", "[Place an item in the vault]", "_t")
t("Item's Vault", "Item's Vault", "_t")
t("You can not place an item in the vault from debug mode game.", "You can not place an item in the vault from debug mode game.", "_t")
t("Place an item in the Item's Vault", "Place an item in the Item's Vault", "_t")
t("Caution", "Caution", "_t")
t("Continue?", "Continue?", "_t")
t("[Retrieve an item from the vault]", "[Retrieve an item from the vault]", "_t")
--]==]
------------------------------------------------
section "tome-items-vault/overload/data/chats/items-vault-command-orb.lua"
t("[Leave the orb alone]", "[Laisser l'orbe tranquille]", "_t")
-- nouveau texte
--[==[
t("Transfering this item will place a level %d requirement on it, since it has no requirements. ", "Transfering this item will place a level %d requirement on it, since it has no requirements. ", "tformat")
t("Some properties of the item will be lost upon transfer, since they are class- or talent-specific. ", "Some properties of the item will be lost upon transfer, since they are class- or talent-specific. ", "_t")
t([[*#LIGHT_GREEN#This orb seems to be some kind of interface to an extra-dimentional vault of items.
All your characters in alternate universes will be able to access it from here.
Only items from a validated game versions are uploadable.#WHITE#*
#GOLD#Donator's Feature#ANCIENT_WHITE#: Items are saved on the server, only donators have access to this feature and the number of items storable at once depends on your generosity.
I, DarkGod, the maker of this game want to personaly thank all donators because you people are keeping this game going. Thanks and enjoy!]], [[*#LIGHT_GREEN#This orb seems to be some kind of interface to an extra-dimentional vault of items.
All your characters in alternate universes will be able to access it from here.
Only items from a validated game versions are uploadable.#WHITE#*
#GOLD#Donator's Feature#ANCIENT_WHITE#: Items are saved on the server, only donators have access to this feature and the number of items storable at once depends on your generosity.
I, DarkGod, the maker of this game want to personaly thank all donators because you people are keeping this game going. Thanks and enjoy!]], "_t")
t("\
#CRIMSON#Note for Steam Players#ANCIENT_WHITE#: This feature requires you to have registered a profile & bound it to steam (automatic if you register ingame) because it needs to store things on the server.\
Until you do so you will get an error.", "\
#CRIMSON#Note for Steam Players#ANCIENT_WHITE#: This feature requires you to have registered a profile & bound it to steam (automatic if you register ingame) because it needs to store things on the server.\
Until you do so you will get an error.", "_t")
t("[Place an item in the vault]", "[Place an item in the vault]", "_t")
t("Item's Vault", "Item's Vault", "_t")
t("You can not place an item in the vault from an un-validated game.", "You can not place an item in the vault from an un-validated game.", "_t")
t("Place an item in the Item's Vault", "Place an item in the Item's Vault", "_t")
t("Caution", "Caution", "_t")
t("Continue?", "Continue?", "_t")
t("[Retrieve an item from the vault]", "[Retrieve an item from the vault]", "_t")
t("#GOLD#I wish to help the funding of this game and donate#WHITE#", "#GOLD#I wish to help the funding of this game and donate#WHITE#", "_t")
--]==]
------------------------------------------------
section "tome-items-vault/overload/data/maps/items-vault/fortress.lua"
-- nouveau texte
--[==[
t("Psionic Metarial Retention", "Psionic Metarial Retention", "_t")
t("Temporal Locked Vault", "Temporal Locked Vault", "_t")
--]==]
------------------------------------------------
section "tome-items-vault/overload/mod/class/ItemsVaultDLC.lua"
t("unknown reason", "Raison inconnue", "_t")
-- nouveau texte
--[==[
t("the #GOLD#Item's Vault#WHITE#", "the #GOLD#Item's Vault#WHITE#", "_t")
t("\
#CRIMSON#This item has been sent to the Item's Vault.", "\
#CRIMSON#This item has been sent to the Item's Vault.", "_t")
t("Transfering...", "Transfering...", "_t")
t("Teleporting object to the vault, please wait...", "Teleporting object to the vault, please wait...", "_t")
t("#LIGHT_BLUE#You transfer %s to the online item's vault.", "#LIGHT_BLUE#You transfer %s to the online item's vault.", "logPlayer")
t("#LIGHT_RED#Error while transfering %s to the online item's vault, please retry later.", "#LIGHT_RED#Error while transfering %s to the online item's vault, please retry later.", "logPlayer")
t("#CRIMSON#Server said: %s", "#CRIMSON#Server said: %s", "logPlayer")
t("#LIGHT_BLUE#You transfer %s to the offline item's vault.", "#LIGHT_BLUE#You transfer %s to the offline item's vault.", "logPlayer")
t("Teleporting object from the vault, please wait...", "Teleporting object from the vault, please wait...", "_t")
t("Transfer failed", "Transfer failed", "_t")
t([[This item comes from a previous version and would not work in your current game.
To prevent the universe from imploding the item was not transfered from the vault.]], [[This item comes from a previous version and would not work in your current game.
To prevent the universe from imploding the item was not transfered from the vault.]], "_t")
t("Item's Vault", "Item's Vault", "_t")
t("Checking item's vault list, please wait...", "Checking item's vault list, please wait...", "_t")
--]==]
------------------------------------------------
section "tome-items-vault/overload/mod/dialogs/ItemsVault.lua"
t("Name", "Nom", "_t")
t("Cooldown", "Rechargement", "_t")
-- nouveau texte
--[==[
t("Item's Vault", "Item's Vault", "_t")
t("Impossible to contact the server, please wait a few minutes and try again.", "Impossible to contact the server, please wait a few minutes and try again.", "_t")
t("Item's Vault (%d/%d)", "Item's Vault (%d/%d)", "tformat")
t([[Retrieve an item from the vault. When you place an item in the vault the paradox energies around it are so powerful you must wait one hour before retrieving it.
#CRIMSON#Warning: while you *can* retrieve items made with previous versions of the game, no guarantee is given that the universe (or your character) will not explode.]], [[Retrieve an item from the vault. When you place an item in the vault the paradox energies around it are so powerful you must wait one hour before retrieving it.
#CRIMSON#Warning: while you *can* retrieve items made with previous versions of the game, no guarantee is given that the universe (or your character) will not explode.]], "_t")
t("Usable", "Usable", "_t")
t("#LIGHT_GREEN#Yes", "#LIGHT_GREEN#Yes", "_t")
t("#LIGHT_RED#In less than one minute", "#LIGHT_RED#In less than one minute", "_t")
t("#LIGHT_RED#In %d minutes", "#LIGHT_RED#In %d minutes", "tformat")
t("This item has been placed recently in the vault, you must wait a bit before removing it.", "This item has been placed recently in the vault, you must wait a bit before removing it.", "_t")
t("#LIGHT_BLUE#You transfer %s from the online item's vault.", "#LIGHT_BLUE#You transfer %s from the online item's vault.", "log")
t("#LIGHT_RED#Error while transfering from the online item's vault, please retry later.", "#LIGHT_RED#Error while transfering from the online item's vault, please retry later.", "log")
--]==]
------------------------------------------------
section "tome-items-vault/overload/mod/dialogs/ItemsVaultOffline.lua"
t("Name", "Nom", "_t")
t("Cooldown", "Rechargement", "_t")
-- nouveau texte
--[==[
t("Item's Vault", "Item's Vault", "_t")
t("Impossible to contact the server, please wait a few minutes and try again.", "Impossible to contact the server, please wait a few minutes and try again.", "_t")
t("Item's Vault (%d/%d)", "Item's Vault (%d/%d)", "tformat")
t([[Retrieve an item from the vault. When you place an item in the vault the paradox energies around it are so powerful you must wait one hour before retrieving it.
#CRIMSON#Warning: while you *can* retrieve items made with previous versions of the game, no guarantee is given that the universe (or your character) will not explode.]], [[Retrieve an item from the vault. When you place an item in the vault the paradox energies around it are so powerful you must wait one hour before retrieving it.
#CRIMSON#Warning: while you *can* retrieve items made with previous versions of the game, no guarantee is given that the universe (or your character) will not explode.]], "_t")
t("Usable", "Usable", "_t")
t("#LIGHT_GREEN#Yes", "#LIGHT_GREEN#Yes", "_t")
t("#LIGHT_RED#In less than one minute", "#LIGHT_RED#In less than one minute", "_t")
t("#LIGHT_RED#In %d minutes", "#LIGHT_RED#In %d minutes", "tformat")
t("This item has been placed recently in the vault, you must wait a bit before removing it.", "This item has been placed recently in the vault, you must wait a bit before removing it.", "_t")
t("#LIGHT_BLUE#You transfer %s from the offline item's vault.", "#LIGHT_BLUE#You transfer %s from the offline item's vault.", "log")
t("#LIGHT_RED#Error while transfering from the offline item's vault, please retry later.", "#LIGHT_RED#Error while transfering from the offline item's vault, please retry later.", "log")
--]==]
| 3ba19d9bd021ee42091bc033a0b27b8c89a49dea | [
"Lua"
] | 5 | Lua | Krabator/ToME-Fr | 0a00d55546128b76603b2fc5aebf95768d1d6316 | e5bfb7cfc284c45762885ccdc93c61f32aee3e22 |
refs/heads/master | <file_sep>document.addEventListener('DOMContentLoaded', function() {
var skylink = new Skylink();
skylink.init({
apiKey: 'your-key-here',
defaultRoom: 'SampleRoom'
}, function() {
skylink.joinRoom({audio: true, video: true})
});
skylink.on('incomingStream', function(peerId, stream, isSelf) {
if(isSelf) return;
attachMediaStream(document.getElementById('remote'), stream);
});
skylink.on('mediaAccessSuccess', function(stream) {
attachMediaStream(document.getElementById('local'), stream);
});
});
<file_sep>
var skylink = new Skylink();
// initialize the skylink object
skylink.init({
apiKey: 'your-key-here',
defaultRoom: 'myRoom'
}, function() {
//join the room on auth success
skylink.joinRoom({audio: false, video: false})
});
// announce people joining the session
skylink.on('peerJoined', function(peerId, peerInfo, isSelf) {
if (!isSelf) renderMessage( peerId, 'has joined the room');
});
// handle new messages
skylink.on('incomingMessage', function(message, peerId, peerInfo, isSelf) {
// identify sender
var sender = peerInfo.userData.name || peerId;
renderMessage(sender,message.content);
});
function send() {
var messageBody = document.getElementById('out');
skylink.sendMessage(messageBody.value);
messageBody.value = '';
}
////////////
function renderMessage(sender,content) {
// create message elements
var msgContainer = document.createElement('div');
var msgContent = document.createTextNode(sender + ": " + content);
var messages = document.getElementById('messages');
// attach new message
msgContainer.appendChild(msgContent);
messages.insertBefore(msgContainer, messages.firstChild);
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('send').addEventListener('click', function() {
send();
});
});
<file_sep>var skylink = new Skylink();
skylink.init({
apiKey: 'your-key-here',
defaultRoom: 'MyLocalRoom'
}, function() {
skylink.joinRoom({
audio: true,
video: true
})
});
skylink.on('mediaAccessSuccess', function(stream) {
var video = document.getElementById('local');
attachMediaStream(video, stream);
});
<file_sep>/*
$(document).ready(function() {
$('#presentation').fullpage({
afterLoad: function() {
$('.page-number').each(function(key) {$(this).text(key+1)});
},
css3: true,
scrollingSpeed: 700,
fitToSection: true,
fitToSectionDelay: 1000,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease'
});
}); */
var sections;
var currentSection = 0;
function nextSection() {
currentSection = currentSection + 1;
if (currentSection > sections.length) {
currentSection = sections.length;
}
window.scrollTo(0,sections[currentSection].offsetTop);
}
function prevSection() {
currentSection = currentSection - 1;
if (currentSection < 0) {
currentSection = 0;
}
window.scrollTo(0,sections[currentSection].offsetTop);
}
//// SKYLINK FUN
function insertPageNumber(pageNum, target) {
var pageNumberBlock = document.createElement('div');
var pageNumberText = document.createTextNode(pageNum+1);
pageNumberBlock.classList.add('page-number');
pageNumberBlock.appendChild(pageNumberText);
target.insertBefore(pageNumberBlock, target.childNodes[0]);
}
document.addEventListener('DOMContentLoaded', function() {
console.log('adding page numbers');
sections = document.querySelectorAll('.section');
for(var i = 0; i < sections.length; i++) {
insertPageNumber(i, sections[i]);
}
});
document.addEventListener('keyup', function(evt) {
if(evt.key == 'ArrowUp' || evt.key == 'a') prevSection();
if(evt.key == 'ArrowDown' | evt.key == 'z') nextSection();
});
var skylink = new Skylink();
skylink.init({
apiKey: 'your-key-here',
defaultRoom: 'millimatters'
}, function() {
skylink.joinRoom({
audio: false,
video: false
})
});
skylink.on('peerJoined', function(peerId, peerInfo, isSelf) {
if(isSelf) return;
});
skylink.on('incomingMessage', function(message, peerId, peerInfo, isSelf) {
switch(message.content) {
case 'prev':
prevSection();
break;
case 'next':
nextSection();
break;
default:
break;
}
});
///
skylink.on('incomingStream', function(peerId, stream, isSelf) {
if(isSelf) return;
attachMediaStream(document.getElementById('remote'), stream);
});
skylink.on('mediaAccessSuccess', function(stream) {
attachMediaStream(document.getElementById('local'), stream);
});
function start() {
skylink.joinRoom({
audio: true,
video: true
})
$('#video-container').show();
}
function stop() {
skylink.leaveRoom();
$('#video-container').hide();
}
<file_sep>Milliseconds Matter: Creating Real-time Interactions With Temasys SDKs
### How to run this demo
1. You will need a Temasys App Key for this demo. You can signup for free and get one [HERE](https://console.temasys.io/register).
2. To create an app key, you can follow [THIS GUIDE](https://temasys.io/temasys-rtc-getting-started-web-sdk/) (specifically steps 1 to 4).
IMPORTANT: Make sure to include `localhost` (or your server's IP address) in your CORS Url key settings. Otherwise, the demos wouldn't work.
3. In each demo folder, replace the `apiKey` with your new app key.
4. Run a webserver in the root directory of this repository. My personal favorites:
Ruby 2.x and above
```ruby
ruby -run -ehttpd . -p8000
```
Python 2.x
```python
python -m SimpleHTTPServer
```
Python 3.x
```python
python -m http.server 8000
```
5. Visit `localhost:8000` in your browser and just click on each link to check out each demo!
6. You can find [more examples here!](https://github.com/Temasys/SkylinkJS/tree/0.6.x/master/demo)
NOTE: MCU functionality will not be available in the free plan, so the screensharing demo will not work if you have a free app key.
### Resources
- [Getting Started Guide](https://temasys.com.sg/webrtc-getting-started-temasys-peer-connectivity/)
- [SDK Documentation](http://cdn.temasys.io/skylink/skylinkjs/latest/doc/classes/Skylink.html)
- [Support](http://support.temasys.com.sg/support/home)<file_sep>document.addEventListener('DOMContentLoaded', function() {
var remoteContainer = document.getElementById('remote');
var skylink = new Skylink();
skylink.init({
apiKey: 'your-key-here',
defaultRoom: 'SampleRoom'
}, function() {
skylink.joinRoom({audio: true, video: true})
});
// handle incoming remote streams
skylink.on('incomingStream', function(peerId, stream, isSelf) {
if(isSelf) return;
attachMediaStream(document.getElementById(peerId), stream);
});
// handle camera access dialog action
skylink.on('mediaAccessSuccess', function(stream) {
attachMediaStream(document.getElementById('local'), stream);
});
// handle peer enter
skylink.on('peerJoined', function(peerId, peerInfo, isSelf) {
if(isSelf) return;
var video = document.createElement('video');
video.setAttribute('id', peerId);
video.setAttribute('muted', true); // demo only
video.setAttribute('autoplay', true);
remoteContainer.appendChild(video);
});
// handle peer departure
skylink.on('peerLeft', function(peerId, peerInfo, isSelf) {
document.getElementById(peerId).remove();
});
});
////////////////////////
| e9071f1e8f9eda89b0848710a765e4017a483534 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | Temasys/cebu-webrtc-meetup-demos | 3873f97f8d5da262b5cb68b8c1d7c37f5610d4b4 | be89f7e83deaae244ab66c4c5c22b72db4ba006c |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import axios from 'axios';
import SmurfCard from './SmurfCard';
import { Link } from 'react-router-dom';
export default class Smurfs extends Component {
constructor(props) {
super(props);
this.state = {
smurfs: [],
}
};
// add any needed code to ensure that the smurfs collection exists on state and it has data coming from the server
// Notice what your map function is looping over and returning inside of Smurfs.
// You'll need to make sure you have the right properties on state and pass them down to props.
componentDidMount() {
axios.get(`http://localhost:3333/smurfs`)
.then(response => this.setState({ smurfs: response.data }))
.catch(err => { console.log(err) })
}
render() {
console.log('Smurfs.fs', this.state.smurfs);
return (
<div className="Smurfs">
{this.state.smurfs.map(smurf => (
<SmurfDetails key={smurf.id} smurf={smurf} />
))}
</div>
)
}
}
function SmurfDetails({ smurf }) {
console.log('Smurf Id', smurf.id);
return (
<Link to={`/${smurf.id}`}>
<SmurfCard smurf={smurf} />
</Link>
)
}
<file_sep>import React from 'react';
import axios from 'axios';
import SmurfCard from './SmurfCard';
export default class Smurf extends React.Component {
constructor(props) {
super(props);
this.state = {
smurf: null
};
}
componentDidMount() {
this.fetchSmurf(this.props.match.params.id);
}
componentWillReceiveProps(newProps) {
if (this.props.match.params.id !== newProps.match.params.id) {
this.fetchSmurf(newProps.match.params.id);
}
}
fetchSmurf = id => {
axios.get(`http://localhost:3333/smurfs`)
.then(response => this.setState({ smurf: response.data[id] }))
.catch(err => { console.log(err) })
};
render() {
console.log('Smurf.js', this.state.smurf);
if (!this.state.smurf) {
return <div>Loading smurf information...</div>;
}
return (
<div>
<SmurfCard smurf={this.state.smurf} />
</div>
);
}
}
<file_sep>import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import './App.css';
import SmurfForm from './components/SmurfForm';
import Smurfs from './components/Smurfs';
import Smurf from './components/Smurf';
import Header from './components/Header';
class App extends Component {
render() {
return (
<div className="App">
<SmurfForm />
<Header />
<Route exact path="/" component={Smurfs} />
<Route path="/:id" render={(props) => {
return <Smurf {...props} />
}} />
</div>
);
}
}
export default App;
| 5b10bf949b185c78a2c662f4fac6ed77b8074f80 | [
"JavaScript"
] | 3 | JavaScript | eddygonzalez9708/Sprint-Challenge-Routing-Axios | a9149925aa340f3d8694db8b9a68f4747c65c280 | e7148fe4c2e9db3106962b84a5b1954f154f27a0 |
refs/heads/master | <file_sep>#!/usr/bin/env node
require('./bin/flashback')
<file_sep>npm-flashback
=============
Flashback will do npm install as if it were taking place on a given date. All semantically versioned dependencies will be installed as if it were taking place on that date. Ie newer packages will be ignored.
I have found that semantic versioning in npm can cause issues when patches and minors break functionality. Use this tool to help diagnose issues.
#Quick start
##Node.js
npm install -g flashback
##Usage
Navigate to root of module you want flashbacked
flashback <date>
##Errors Will Corrupt Node_Modules
Reinstall dependencies through npm install to fix corruption
## How It works
1. Read the package.json dependencies
2. Run npm view on each dependency
3. Filter by date and available versions
4. Install specific version
5. Recurse on the newly installed modules dependencies
| 06b5fdc1dd210995f6465e2fe430b9055fe33ed9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | stierma1/npm-flashback | 07469b83a22a5decf098f73292b8188cbbb6450d | bf47b822beab0cf49e8720a28ccb05fb4dcdb530 |
refs/heads/main | <repo_name>pzsnark/ds-filippov-konstantin-2<file_sep>/js/toys_.js
var toys_item = document.querySelectorAll('.toys-item');
var toys_item_link = document.querySelectorAll('.toys-item-link');
console.log(toys_item)
console.log(toys_item_link)
for (let i = 0; i < toys_item.length; i++) {
toys_item[i].addEventListener("mouseover", function() {
toys_item_link[i].style.display = "block";
console.log('Курсор над блоком')
});
}
for (let i = 0; i < toys_item.length; i++) {
toys_item[i].addEventListener("mouseout", function() {
toys_item_link[i].style.display = "none";
console.log('Курсор вне блока')
});
}
<file_sep>/js/modal_.js
var modal = document.getElementById("modal");
var btn = document.getElementById("exploreBtn");
var span = document.getElementsByClassName("close_window")[0];
btn.onclick = function() {
modal.style.display = "flex";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
} | 749965f16c03f39a2701462f467248acbd0cab06 | [
"JavaScript"
] | 2 | JavaScript | pzsnark/ds-filippov-konstantin-2 | f2654b09426a6dbfe77455b78ed49f816bf97dd3 | ace6f883dadd25708dc2728fc3b917b3a99fa827 |
refs/heads/master | <repo_name>LGaedo/test3IT<file_sep>/src/main/java/com/test/tresIT/SpringBootApp3IT.java
package com.test.tresIT;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootApp3IT {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp3IT.class, args);
}
}
<file_sep>/src/main/java/com/test/tresIT/service/impl/UserServiceImpl.java
package com.test.tresIT.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.jboss.logging.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.tresIT.dto.UserDTO;
import com.test.tresIT.entity.User;
import com.test.tresIT.repository.UserRepository;
import com.test.tresIT.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserRepository userRepository;
private static final Logger LOG = Logger.getLogger(UserServiceImpl.class.getName());
@Override
public UserDTO createUser(UserDTO user) {
UserDTO returnValue;
try {
User userModel = new User();
returnValue = new UserDTO();
LOG.info("se inicia creación de usuario");
BeanUtils.copyProperties(user, userModel);
User infoUser = userRepository.save(userModel);
if (infoUser != null) {
BeanUtils.copyProperties(infoUser, returnValue);
returnValue.setComentario("creado");
LOG.info("usuario creado");
}
} catch (Exception e) {
return null;
}
return returnValue;
}
@Override
public List<UserDTO> findAll() {
List<UserDTO> users = new ArrayList<UserDTO>();
List<User> usersM = new ArrayList<User>();
userRepository.findAll().forEach(usersM::add);
BeanUtils.copyProperties(usersM, users);
return users;
}
@Override
public Boolean existsByMail(String mail) {
Boolean ret = userRepository.existsByMail(mail);
return ret;
}
}
<file_sep>/README.md
# Spring Boot H2 Database Rest API with Spring Data JPA
> [Angular 11 Client](https://bezkoder.com/angular-11-crud-app/)
Run both Back-end & Front-end in one place:
> [Integrate Angular with Spring Boot Rest API](https://bezkoder.com/integrate-angular-spring-boot/)
## Run Spring Boot application
```
mvn spring-boot:run
```
<file_sep>/src/main/java/com/test/tresIT/controller/UserController.java
package com.test.tresIT.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.tresIT.dto.UserDTO;
import com.test.tresIT.service.UserService;
@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/users")
public ResponseEntity<List<UserDTO>> getAllUsers() {
try {
List<UserDTO> users = new ArrayList<UserDTO>();
userService.findAll().forEach(users::add);
if (users.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(users, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDTO> createUser(@RequestBody UserDTO user) {
try {
Boolean exist = userService.existsByMail(user.getMail());
UserDTO userDTO = new UserDTO();
if (exist) {
userDTO.setComentario("existe");
} else if(!user.getMail().equals("")){
userDTO = userService.createUser(user);
}else {
userDTO.setComentario("existe");
}
return new ResponseEntity<>(userDTO, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
<file_sep>/src/main/java/com/test/tresIT/entity/User.java
package com.test.tresIT.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
@Id
@Column(name = "mail")
private String mail;
@Column
private String tipoMusica;
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTipoMusica() {
return tipoMusica;
}
public void setTipoMusica(String tipoMusica) {
this.tipoMusica = tipoMusica;
}
}
| faa9e6f5fe0d2a0eae5750ebb2b56261a1f18f7f | [
"Markdown",
"Java"
] | 5 | Java | LGaedo/test3IT | 2b52b34b57f4ad682bf7e05661c0bb6d25ba1fda | 6bd8ae6ef154f39a837ee1b0a50ea1479f35e8f4 |
refs/heads/master | <repo_name>danibaxx/PyTuts<file_sep>/add.py
''' Problem 13 '''
''' Write a program add.py, takes in 2 numbers as command line arguments and prints the sum'''
import sys
x = int(sys.argv[1])
y = int(sys.argv[2])
add = x + y
print('addition:', add)<file_sep>/hello.py
''' Problem 2 '''
''' How many multiplications are performed when each of the following lines of code is executed? '''
numcalls = 0
def square(x):
global numcalls
numcalls = numcalls + 1
return x * x
# print(square(5))
# print(square(2*5))
# 3
''' Problem 3 '''
''' What will be the output? '''
x = 1
def f():
return x
# print(x) # 1
# print(f()) # 1
''' Problem 4 '''
''' What will be the output? '''
x = 1
def fx():
x = 2
return x
# print(x) # 1
# print(fx()) # 2
# print(x) # 1
''' Problem 5 '''
''' What will be the output? '''
x = 1
def fxy():
x = 2
y = x
return x + y
# print(x) # 1
# print(fxy()) # 4
# print(x) # 1
''' Problem 6'''
''' What will be the output? '''
x = 2
def fxyz(a):
x = a * a
return x
y = fxyz(3)
# print(x,y) # 2, 9
''' Problem 7 '''
''' Write a function count_digits to find number of digits in the given number '''
def count_digits(x):
x = x
return x
x = count_digits(str(12345))
# print(len(x)) # 5
'''Problem 8'''
''' Write a function istrcmp to compare two strings, ignoring the case. '''
''' >>> istrcmp('python', 'Python')
True
>>> istrcmp('LaTeX', 'Latex')
True
>>> istrcmp('a', 'b')
False '''
def istrcmp1(a, b):
if a.lower() == b.lower():
return True
else:
return False
lang = istrcmp1('python', 'Python')
# print(lang) # True
def istrcmp2(c, d):
if c.lower() == d.lower():
return True
else:
return False
glove = istrcmp2('LaTeX', 'Latex')
# print(glove) # True
def istrcmp3(e,f):
if e.lower() == f.lower():
return True
else:
return False
alpha = istrcmp3('a', 'b')
# print(alpha) # False
''' Problem 9 '''
''' What will be the output? '''
# print(2 < 3 and 3 > 1) # True
# print(2 < 3 or 3 > 1) # True
# print(2 < 3 or not 3 > 1) # True
# print(2 < 3 and not 3 > 1) # False
''' Problem 10 '''
''' What will be the output? '''
x = 4
y = 5
z = []
p = x < y or x < z
# print(p) # True
''' Problem 11 '''
''' What will happen when the code is executed? Will it give any error? Explain. '''
# x = 2
# if x == 2:
# print(x)
# else:
# print(y)
# I think the following code will run since x = 2 it will only run the if block and print x, no error will be given as the else block will not run.
''' Problem 12 '''
''' What will happen when the code is executed? Will it give any error? Explain. '''
# x = 2
# if x == 2:
# print(x)
# else:
# x +
# Before running this block of code, I figured it would of still ran even with the invalid syntax but after running it, I have realized this wont work at all due to the syntax errors. | a734dd043f1fd22c06369430f929619f5e98b4b5 | [
"Python"
] | 2 | Python | danibaxx/PyTuts | 90d6829e82e8517ddfac1af44fd518ce8e2f2f98 | 323a857a674e09b03d499cab421f15e4510c46e7 |
refs/heads/master | <repo_name>Samuel-Taya/Lab1-ProjectEuler-1-to-7-and-9<file_sep>/Problem7.cpp
// What is the 10 001st prime number?
#include <math.h>
#include <iostream>
using namespace std;
int primeNumber(int ordinal)
{
int contfac=0, contP=0, n = 2;
while (contP < ordinal)
{
for(int i=1;i<=sqrt(n);i++)
{
if(n%i==0)
{
contfac++;
}
if(contfac>1)
{
break;
}
}
if(contfac==1) // si solo tiene un factor primo
{
contP++;
}
contfac = 0;
n++;
}
return n-1;
}
int main()
{
cout << primeNumber(10001);
return 0;
}
<file_sep>/Problem6.cpp
// Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int sum1=0, sum2=0;
int dif;
for(int i=1; i<=100 ;i++)
{
sum1 = sum1 + pow(i,2);
sum2 = sum2 + i;
}
sum2 = pow(sum2,2);
dif = sum2-sum1;
cout << "La diferencia es: " << dif;
return 0;
}
<file_sep>/Problem2.cpp
//The terms in the Fibonacci sequence whose values do not exceed four million, FIND the sum of the even-valued terms
#include <iostream>
using namespace std;
int sumFibonacci()
{
int n, numpar, suma=0;
long long int num_ant=1, num_sig=1, nue_num=1;
for(n=0;n<33;n++)
{
num_ant=num_sig;
num_sig=nue_num;
nue_num=num_ant+num_sig;
if(num_sig<4000000)
{
numpar=num_sig%2;
if(numpar==0)
{
suma+=num_sig;
}
}
else
break;
}
return suma;
}
int main()
{
cout << "Respuesta: " << sumFibonacci() << endl;
return 0;
}
<file_sep>/Problem9.cpp
// There exists exactly one Pythagorean triplet for which a + b + c = 1000.
// Find the product abc.
#include <iostream>
#include <math.h>
using namespace std;
int encontrar(int a,int b,int c)
{
for(int i=5; i<1000; i++)
{
c=i;
for(int j=4; j<c; j++)
{
b=j;
for(int k=3; k<b; k++)
{
a=k;
if(a*a + b*b ==c*c && a+b+c == 1000)
{
return a*b*c;
}
}
}
}
}
int main()
{
int a,b,c;
cout << encontrar(a,b,c) << endl;
return 0;
}
<file_sep>/Problem3.cpp
// the largest prime factor of the number 600851475143
#include <iostream>
#include <math.h>
using namespace std;
void primeFactors(long long int n)
{
while (n%2 == 0) // si se puede dividir en 2
{
cout << 2 << " ";
n = n/2;
}
for (int i=3; i <= sqrt(n); i=i+2)
{
while (n%i == 0)
{
cout << i << " ";
n = n/i;
}
}
if (n>2) // cuando es un numero primo mas grande que 2
cout << n << " ";
}
int main()
{
long long int n = 9;//600851475143;
primeFactors(n);
return 0;
}
<file_sep>/Problem4.cpp
// largest palindrome made from the product of two 3-digit numbers.
#include <iostream>
#include <math.h>
using namespace std;
bool palindromo(int n)
{
int num = n;
int inv = 0;
// operacion para invertir el numero
while (num>0)
{
inv = inv * 10 + num % 10; // obtiene el ultimo digito
num = num / 10; // elimina el ultimo digito
}
if (inv == n)
return true;
return false;
}
int main()
{
int num, aux;
num = 0;
for (int i=100; i<1000; i++) // numeros de 3 digitos
{
for (int j=100; j<1000; j++)
{
aux = i*j;
if (palindromo(aux) && aux>num) // aux>num para hallar el palindromo mas grande
num=aux;
}
}
cout<<num;
return 0;
}
<file_sep>/Problem1.cpp
// sum of all the multiples of 3 or 5 below 1000
#include<iostream>
using namespace std;
int multiples()
{
int i,m3,m5,suma=0;
for(i=0;i<1000;i++)
{
m3=i%3; // se guarda el residuo en m3
m5=i%5;
if(m3==0 || m5==0)
{
suma+=i;
}
}
return suma;
}
int main()
{
cout << "Respuesta: " << multiples() << endl;
return 0;
}
<file_sep>/README.md
# Lab1-ProjectEuler-1-to-7-and-9
Solution at some problems of project euler
I tried to solve the first problems of project euler, and here I put all solutions for every problem of these project, I would solve the first hundred
<file_sep>/Problem5.cpp
// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20
#include <iostream>
#include <math.h>
using namespace std;
int divisible(int num[])
{
// sacamos los factores minimos en cada elemento del arreglo a partir del numero 4 en base a los anteriores
for (int i=2; i<20; i++)
{
for (int j=1; j<i; j++)
{
if (num[i] % num[j] == 0)
{
num[i] = num[i] / num[j];
}
}
}
// multiplicamos el arreglo anterior
int times= 1;
for (int i=0; i<20; i++)
{
times = times * num[i];
}
return times;
}
int main()
{
// creamos un arreglo con los numeros de 1 al 20
int numeros[20];
for (int i=0;i<20; i++)
{
numeros[i] = i+1;
}
cout<< divisible(numeros) << endl;
return 0;
}
| f861977e3ddcf577fd2aed123d624ef436709211 | [
"Markdown",
"C++"
] | 9 | C++ | Samuel-Taya/Lab1-ProjectEuler-1-to-7-and-9 | 53cca98c765f8eb08e9b936969b09c8fceb0e6ca | a0ceb263a6e6e80034a27bfce04e155ab5eae9c1 |
refs/heads/master | <file_sep>package com.example.ep.ui.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import com.example.ep.R;
import com.example.ep.R.layout;
import com.example.ep.util.UserInfo;
/**
* 主页面父类
*
* @author liusy 2015-04-18
*
*/
@SuppressLint({ "NewApi", "JavascriptInterface" })
public abstract class AbsMainActivity extends Activity {
protected FragmentManager fgm;
protected Display display;
protected UserInfo userInfo = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//如果没登陆,将跳转到登陆页面,登陆了,将进入方法
if(checkUserLogin())
{
//获得Fragment管理所需要的类的对象
fgm = getFragmentManager();
display = getWindowManager().getDefaultDisplay();
initMainFragment();
}
}
protected abstract void initMainFragment();
/**
* 检查用户是否登陆
*
* @return true 已经登陆,false 未登陆
*/
private boolean checkUserLogin()
{
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
if(null != bundle )
{
userInfo = (UserInfo) bundle.get("UserInfo");
}
if(null==userInfo)
{
Intent intentLoginActivity = new Intent(AbsMainActivity.this, LoginActivity.class);
startActivity(intentLoginActivity);
finish(); //不加这一句,按回退键就会回到欢迎界面不合理。
return false;
}
return true;
}
public UserInfo getUserInfo()
{
return this.userInfo;
}
}
<file_sep>package com.example.ep.ui.fragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.example.ep.ui.fragment.adapter.CheckboxAdapter;
/**
* Tab内容基类
*
* @author liusy 2015-04-18
*
*/
@SuppressLint("NewApi")
public abstract class AbsTabContext extends AbsBaseFragment {
protected int layout;
public AbsTabContext(int layout) {
super();
this.layout = layout;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(layout, container,false);
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(!hidden)
{
//在前端显示
}
else
{
//不在前端显示
}
}
public int getLayout() {
return layout;
}
public void listViewItemCheckedChanged(int currtPosition,boolean isChecked,CheckboxAdapter checkboxAdapter){};
}
<file_sep>package com.example.ep.util;
import java.io.Serializable;
/**
* 用户登陆信息
*
* @author liusy 2015-04-18
*
*/
public class UserInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String userId;
private String userPwd;
private String userName;
private String email;
private String job;
private String dept;
private String org;
public UserInfo(String id, String userId, String userPwd, String userName,
String email,String job, String dept, String org) {
super();
this.id = id;
this.userId = userId;
this.userPwd = userPwd;
this.userName = userName;
this.email = email;
this.org = org;
this.dept = dept;
}
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>package com.example.ep.ui.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.ep.R;
import com.example.ep.ui.fragment.listviewitems.BarChartItem;
import com.example.ep.ui.fragment.listviewitems.ChartItem;
import com.example.ep.ui.fragment.listviewitems.LineChartItem;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
/**
* Tab内容页1(注册服务信息)
*
* @author liusy 2015-04-18
*
*/
@SuppressLint({ "NewApi", "ValidFragment" })
public class TabContext1 extends AbsTabContext {
protected String[] mMonths = new String[] {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
protected String[] mParties = new String[] {
"Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H",
"Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P",
"Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
"Party Y", "Party Z"
};
public TabContext1(int layout) {
super(layout);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initTabContext1();
}
public void initTabContext1()
{
ListView lvSSFH = (ListView) acMain.findViewById(R.id.chartListViewSSFH);
ArrayList<ChartItem> list = new ArrayList<ChartItem>();
list.add(new LineChartItem(generateDataLine(1), acMain.getApplicationContext(),"实时负荷情况","单位(千瓦)/小时"));
ChartDataAdapter cda = new ChartDataAdapter(acMain.getApplicationContext(), list);
lvSSFH.setAdapter(cda);
//list.add(new PieChartItem(generateDataPie(i + 1), acMain.getApplicationContext()));
ListView lvFHZL = (ListView) acMain.findViewById(R.id.chartListViewFHZL);
ArrayList<ChartItem> listFHZL = new ArrayList<ChartItem>();
listFHZL.add(new BarChartItem(generateDataBar(1), acMain.getApplicationContext(),"负荷总量","单位(千瓦)/天"));
ChartDataAdapter cdaFHZL = new ChartDataAdapter(acMain.getApplicationContext(), listFHZL);
lvFHZL.setAdapter(cdaFHZL);
ListView listViewSBXJMX = (ListView)acMain.findViewById(R.id.listViewSBXJMX);
ArrayList<Map<String,Object>> listData= new ArrayList<Map<String,Object>>();
Map<String,Object> item = new HashMap<String,Object>();
item.put("textView1", "大型设备1");
item.put("textView2", "4千瓦");
listData.add(item);
Map<String,Object> item2 = new HashMap<String,Object>();
item2.put("textView1", "大型设备2");
item2.put("textView2", "4千瓦");
listData.add(item2);
Map<String,Object> item3 = new HashMap<String,Object>();
item3.put("textView1", "大型设备3");
item3.put("textView2", "2千瓦");
listData.add(item3);
Map<String,Object> item4 = new HashMap<String,Object>();
item4.put("textView1", "大型设备4");
item4.put("textView2", "6千瓦");
listData.add(item4);
SimpleAdapter adapter = new SimpleAdapter(acMain,listData,R.layout.context1_sub1_list_view,new String[]{"textView1","textView2"},new int[]{R.id.textView1,R.id.textView2,R.id.checkBox1});
listViewSBXJMX.setAdapter(adapter);
//
}
/** adapter that supports 3 different item types */
private class ChartDataAdapter extends ArrayAdapter<ChartItem> {
public ChartDataAdapter(Context context, List<ChartItem> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getItem(position).getView(position, convertView, getContext());
}
@Override
public int getItemViewType(int position) {
// return the views type
return getItem(position).getItemType();
}
@Override
public int getViewTypeCount() {
return 3; // we have 3 different item-types
}
}
/**
* generates a random ChartData object with just one DataSet
*
* @return
*/
private LineData generateDataLine(int cnt) {
ArrayList<Entry> e1 = new ArrayList<Entry>();
for (int i = 0; i < 24; i++) {
e1.add(new Entry((int) (Math.random() * 65) + 40, i));
}
LineDataSet d1 = new LineDataSet(e1, "New DataSet " + cnt + ", (1)");
d1.setLineWidth(2.5f);
d1.setCircleSize(4.5f);
d1.setHighLightColor(Color.rgb(244, 117, 117));
d1.setDrawValues(false);
d1.setLabel("昨日负荷");
ArrayList<Entry> e2 = new ArrayList<Entry>();
for (int i = 0; i < 24; i++) {
e2.add(new Entry((int)(Math.random() * 65) + 50, i));
}
LineDataSet d2 = new LineDataSet(e2, "New DataSet " + cnt + ", (2)");
d2.setLineWidth(2.5f);
d2.setCircleSize(4.5f);
d2.setHighLightColor(Color.rgb(244, 117, 117));
d2.setColor(ColorTemplate.VORDIPLOM_COLORS[0]);
d2.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[0]);
d2.setDrawValues(false);
d2.setLabel("今日负荷");
ArrayList<LineDataSet> sets = new ArrayList<LineDataSet>();
sets.add(d1);
sets.add(d2);
LineData cd = new LineData(getHours(), sets);
return cd;
}
/**
* generates a random ChartData object with just one DataSet
*
* @return
*/
private BarData generateDataBar(int cnt) {
ArrayList<BarEntry> entries = new ArrayList<BarEntry>();
for (int i = 0; i < 31; i++) {
entries.add(new BarEntry((int) (Math.random() * 70) + 30, i));
}
BarDataSet d = new BarDataSet(entries, "1个月");
d.setBarSpacePercent(20f);
d.setColors(ColorTemplate.VORDIPLOM_COLORS);
d.setHighLightAlpha(255);
BarData cd = new BarData(getDays(), d);
return cd;
}
/**
* generates a random ChartData object with just one DataSet
*
* @return
*/
private PieData generateDataPie(int cnt) {
ArrayList<Entry> entries = new ArrayList<Entry>();
for (int i = 0; i < 4; i++) {
entries.add(new Entry((int) (Math.random() * 70) + 30, i));
}
PieDataSet d = new PieDataSet(entries, "");
// space between slices
d.setSliceSpace(2f);
d.setColors(ColorTemplate.VORDIPLOM_COLORS);
PieData cd = new PieData(getQuarters(), d);
return cd;
}
private ArrayList<String> getQuarters() {
ArrayList<String> q = new ArrayList<String>();
q.add("1st Quarter");
q.add("2nd Quarter");
q.add("3rd Quarter");
q.add("4th Quarter");
return q;
}
private ArrayList<String> getMonths() {
ArrayList<String> m = new ArrayList<String>();
m.add("一");
m.add("二");
m.add("三");
m.add("四");
m.add("五");
m.add("六");
m.add("七");
m.add("八");
m.add("九");
m.add("十");
m.add("十一");
m.add("十二");
return m;
}
private ArrayList<String> getDays() {
ArrayList<String> m = new ArrayList<String>();
for(int i=0;i<31;i++)
{
m.add(""+i);
}
return m;
}
private ArrayList<String> getHours() {
ArrayList<String> m = new ArrayList<String>();
for(int i=0;i<24;i++)
{
m.add(""+i);
}
return m;
}
}
<file_sep>package com.example.ep.ui.fragment;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.example.ep.ui.activity.AbsMainActivity;
/**
* Fragme基本类
*
* @author liusy 2015-04-18
*
*/
@SuppressLint("NewApi")
public abstract class AbsBaseFragment extends Fragment {
protected AbsMainActivity acMain;
protected FragmentManager fgm;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
acMain = (AbsMainActivity)this.getActivity();
fgm = acMain.getFragmentManager();
return super.onCreateView(inflater, container, savedInstanceState);
}
}
<file_sep>package com.example.ep.ui.fragment;
import java.util.Map.Entry;
import android.annotation.SuppressLint;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ep.R;
import com.example.ep.util.FragmentMangeUtil;
/**
* Fragme主页面,启动页面
*
* @author liusy 2015-04-18
*
*/
@SuppressLint({ "NewApi", "ResourceAsColor", "UseSparseArrays" })
public class MainTabFragment extends AbsMainFragment {
private FragmentMangeUtil fgmUtil;
//判断是否是回退键事件
private boolean isButtonsClickEvent = true;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.main_tab, container,false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
initBackStackChangedListener();
initFragment();
initBottomButtonsClickEvent();
}
/**
* 初始化Fragment页面集合
*/
private void initFragment() {
fgmUtil = new FragmentMangeUtil(this.fgm,R.id.fragmentRoot);
fgmUtil.putSubFragme(R.id.rbMain, new TabContext1(R.layout.tab_context1));
fgmUtil.putSubFragme(R.id.rbCategory,new TabContext(R.layout.tab_context2));
//fgmUtil.putSubFragme(R.id.rbFind, new TabContext(R.layout.tab_context3));
fgmUtil.putSubFragme(R.id.rbFind, new TabContext3(R.layout.tab_context3));
fgmUtil.putSubFragme(R.id.rbData,new TabContext(R.layout.tab_context4));
fgmUtil.putSubFragme(R.id.rbMe,new TabContext(R.layout.tab_context5));
initFirstFragment(R.id.rbMain);
}
/**
*
* @param rbId tab下的标签按钮R.id.rbMain.,mapTab中的Key
*/
private void initFirstFragment(Integer rbId)
{
acMain.findViewById(rbId).setBackgroundResource(R.color.black_overlay);
fgmUtil.addFragmentManager(rbId);
}
/**
* 处理底部点击事件
*/
private RadioButton rb;
private void initBottomButtonsClickEvent() {
OnClickListener bottomButtonsClick =new OnClickListener() {
@Override
public void onClick(View v) {
String name =(String) ((RadioButton)v).getText();
acMain.findViewById(fgmUtil.getCurrentrRbId()).setBackgroundResource(R.color.footBar);
for(Integer rbId :fgmUtil.getMapTab().keySet())
{
rb = ((RadioButton)acMain.findViewById(rbId));
if(name.equals(rb.getText()))
{
((TextView)acMain.findViewById(R.id.tvOrg)).setText(rb.getText());
//Toast.makeText(acMain, ((TextView)acMain.findViewById(R.id.tvOrg)).getText()+" : ", Toast.LENGTH_SHORT).show();
acMain.findViewById(rbId).setBackgroundResource(R.color.black_overlay);
fgmUtil.addFragmentManager(rbId);
}
}
}
};
for(Integer rbId :fgmUtil.getMapTab().keySet())
{
rb = ((RadioButton)acMain.findViewById(rbId));
rb.setOnClickListener(bottomButtonsClick);
}
}
/**
* 从back stack弹出所有的fragment,保留首页的那个
*/
public void popAllFragmentsExceptTheBottomOne() {
for (int i = 0, count = fgm.getBackStackEntryCount() - 1; i < count; i++) {
fgm.popBackStack();
}
}
/**
* 回退
* 提示:在activity中写onKeyDown后,onBackPressed将无效果
* 供给主Activity调用,既acMain
*/
private long exitTime = 0;
@Override
public void onBackPressed() {
if (fgmUtil.isHomePage()) {
//显示的是第一个页面,按两下退出
if((System.currentTimeMillis()-exitTime) > 2000){
Toast.makeText(acMain, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
acMain.finish();
}
} else {
isButtonsClickEvent = false;
fgm.popBackStack();
}
}
public void initBackStackChangedListener()
{
fgm.addOnBackStackChangedListener(new OnBackStackChangedListener(){
@Override
public void onBackStackChanged() {
//只有当用户按回退键的时候才执行
if(!isButtonsClickEvent)
{
for(Entry<Integer,AbsTabContext> entry:fgmUtil.getMapTab().entrySet())
{
if(entry.getValue().isVisible()&&entry.getKey()!=fgmUtil.getCurrentrRbId())
{
acMain.findViewById(entry.getKey()).setBackgroundResource(R.color.black_overlay);
acMain.findViewById(fgmUtil.getCurrentrRbId()).setBackgroundResource(R.color.footBar);
((TextView)acMain.findViewById(R.id.tvOrg)).setText(((RadioButton) acMain.findViewById(fgmUtil.getCurrentrRbId())).getText());
//Toast.makeText(acMain, ((RadioButton) acMain.findViewById(fgmUtil.getCurrentrRbId())).getText()+" : "+((RadioButton) acMain.findViewById(entry.getKey())).getText(), Toast.LENGTH_SHORT).show();
fgmUtil.setCurrentLayout(entry.getValue().getLayout());
fgmUtil.setCurrentrRbId(entry.getKey());
break;
}
}
isButtonsClickEvent = true;
}
}});
}
}
| cb4d865370efec9d9a3ce34318f7c3b16161e53d | [
"Java"
] | 6 | Java | lsylive/BaseAndroid | 2d4ebd3bc497ae1a1a45e336a0d4c3f84cc3060e | b4ede62d1c39c56190aed700249b4d2bf95a2d1f |
refs/heads/main | <file_sep>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FibonacciApp {
public static void main(String[] args) {
int n = 15;
FibonacciBase fib = new Fibonacci(n);
fib.getFibs(n);
System.out.println(fib);
File fibfile = new File("Fibonnaci.ser");
try {
// -- wrap the target disc file in a raw byte FileOutputStream (object inside file)
// and an ObjectOutputStream for serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fibfile));
// -- write the array of objects to the file
out.writeObject(fib);
// -- close the stream
out.close();
System.out.println("Serialized data is saved in " + fibfile.getAbsolutePath());
} catch (IOException i) {
// -- in case the file cannot be opened
System.out.println("can't open file");
}
System.out.println("Serialized data being read from " + fibfile.getAbsolutePath());
// -- create a reference to an array of Rectangle
try {
FibonacciBase f = null;
// -- wrap the target disc file in a FileInputStream (object inside file)
// and an ObjectInputStream
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fibfile));
// -- read the object from the file
// note that this returns an Object and therefore must be cast
// to the appropriate type to ensure usability
Object ob = in.readObject();
// -- close the stream
in.close();
// -- verify the object class and cast
if (ob instanceof Fibonacci) {
f = (FibonacciBase)ob;
}
System.out.println(f);
} catch (IOException i) {
// -- in case the file cannot be opened
System.out.println("can't open file");
return;
} catch (ClassNotFoundException c) {
// -- in case the Rectangle.class file cannot be found after
// reading the file
System.out.println("Rectangle class not found");
return;
}
}
}
<file_sep>import java.io.Serializable;
public abstract class FibonacciBase implements Serializable {
private static final long serialVersionUID = 1L;
// -- holds computed Fibonacci numbers. This will be constructed
// as a [n][2] array. Locations [i][0] hold values computed
// with the iterative method. Locations [i][1] hold values
// computed with the recursive method.
protected int fibs[][];
// -- Include a constructor that looks like this
// public Fibonacci (int n) {
// fibs = new int[n][2];
// }
// -- return the Nth Fibonacci number using an iterative algorithm
public abstract int fibI(int N) throws IllegalArgumentException;
// -- return the Nth Fibonacci number using a recursive algorithm
public abstract int fibR(int N) throws IllegalArgumentException;
// -- fills the fibs[][] array (see above) with the first N
public void getFibs(int N) throws IllegalArgumentException {
if (N < 0) {
throw new IllegalArgumentException("invalid argument");
}
try {
for (int i = 1; i <= N; ++i) {
fibs[i-1][0] = fibI(i);
fibs[i-1][1] = fibR(i);
}
}
catch (IllegalArgumentException e) {
throw e;
}
}
@Override
public String toString() {
String s = "";
for (int i = 0; i < fibs.length; ++i) {
s += fibs[i][0] + "\t" + fibs[i][1] + "\n";
}
return s;
}
}
<file_sep># serialized_fibonacci
The Serialized Fibonacci assignment for CS 220.
Author: <NAME>
Date: 11/20/2020
| d9f1a623800b9870b8d2e1ec62431c12155b6345 | [
"Markdown",
"Java"
] | 3 | Java | amontg/serialized_fibonacci | dca83759e2645c6fa7095eff4ffe74d9c7e330d1 | 3b6d19a79ba0201efcd94fa62086d8c3739d335d |
refs/heads/master | <file_sep>require 'envyable'
module Envyable
class Railtie < Rails::Railtie
initializer "envyable.load", :before => :load_environment_config do
load
end
def load
Envyable.load root.join('config', 'env.yml'), Rails.env
end
# Fallback of ENV variable or current directory because
# Rails 4.1+ returns nil for Rails.root prior to app initialization
def root
Rails.root || Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd)
end
# Avoid Rails calling `Kernel#load` via #method_mising
def self.load
instance.load
end
end
end
<file_sep>#!/usr/bin/env ruby
require "thor"
require "./lib/envyable/cli"
Envyable::CLI.start
<file_sep>require 'fileutils'
require 'rubygems'
begin
require "simplecov"
require "codeclimate-test-reporter"
SimpleCov.start do
formatter SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
CodeClimate::TestReporter::Formatter
])
add_filter "/spec/"
end
rescue LoadError
end
gem 'minitest'
require 'minitest/autorun'
require File.join(File.dirname(__FILE__), '..', 'lib', 'envyable')
def destination_root(opts={})
dir = File.join(File.dirname(__FILE__), "sandbox")
FileUtils.mkdir_p(dir)
FileUtils.touch("#{dir}/.gitignore") if opts[:with_gitignore]
dir
end
| 18117e8a7c9d7d284ac77c48fee4e6c05bc948c0 | [
"Ruby"
] | 3 | Ruby | backspace/envyable | 818b54027915df28231a11508cc93f8b94ed834c | ca28552d260c30210b73a5f2dea2b2db7a8c1619 |
refs/heads/master | <file_sep># Määrittelydokumentti
## Sovelluksen tarkoitus
Sovelluksen tarkoitus on verrata reittihakualgortimien tehokkuutta.
Aluksi toteutan Jump Point Search ja A* algoritmit ja vertailen näiden tehokkuutta.
Jos aika riitää, lisään joko Bellmanin ja Fordin algoritmin tai Floyd ja Warshallin algoritmin,
## Algoritmit ja tietorakenteet
Käytän Jump Point Search ja A* algoritmejä.
Ensimmäinen käyttää tietorankenteena minimikekoa.
Jälkimmäisessä käytetään myös minimikekoa sekä sen lisäksi heuristiikkafunktiota.
## Syötteet
Ohjelma saa syötteenä 2-ulotteisen taulukon.
Kartta ajatellaan verkkona, missä ruudut ovat verkon solmuja
## Aikavaativuudet
Dikkstran algoritmin aikavaatimus on O(n + m log n) ja A* algoritmin aikavaatimus on O(n).
n on solmujen lkm ja m on kaarien lukumäärä.
## Lähteet
Tietorakenteet ja Algoritmit kirja (Antti Laaksonen 2020)
[Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) Wikipedia
[Introduction to A*](http://theory.stanford.edu/~amitp/GameProgramming/AStarComparison.html)
[Kartat](https://www.movingai.com/benchmarks/grids.html)
[Jump Point Search](https://en.wikipedia.org/wiki/Jump_point_search)
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algoritmit;
/**
*
* @author kukkojoo
*/
public class astar {
public int testaus() {
return 1;
}
}
<file_sep># Viikkoraportti 1
## Käytetty aika?
3-4h
## Mitä olen tehnyt tällä viikolla?
Päätin ohjelmointityöni aiheen ja käytin aikaa tutustumalla aiheeseen.
Tutustuin aiheeseen sekä tarkemmin A* algoritmiin ja tämän lisäksi lueskelin aikaisempia Tiran harjoitustöitä.
Tämän lisäksi palauttelin mieleeni Dijstranin toteutuksen Tiran-kurssin materiaaleista.
Näiden pohjalta loin määrittelydokumentin.
Loin projektin NetBeasillä.
Tämän lisäksi loin repon GitHubiin, sallin issuet ja rekisteröidyin Labtooliin.
Tämän lisäksi olen tutustunut kurssimateriaaliin.
## Miten ohjelma on edistynyt?
Loin NetBeansillä uuden Maven-projektin.
Päivitin pom filen ohjeiden mukaisesti, sekä lisäsin nbaction xml filen.
## Mitä opin tällä viikolla / tänään?
Tutustuin A* algoritmiin ja sen perusteisiin.
## Mitä jäi epäselväksi tai tuottanut vaikeuksia?
Ensimmäisen ja toisen viikon ajankohta on hankala.
Olen vielä lomalla tämän ajankohdan ja tiedän, että eteneminen ei tule olemaan parasta.
Tämä ongelma ratkeaa kun työt alkavat taas ja pääsen normaaliin rytmiin.
## Mitä teen seuraavaksi?
Seuraavaksi palautan mieleeni Dijstran algoritmin ja tutustun tarkemmin A* totetukseen.
Tämän lisäksi alan rakentamaan projektille runkoa.
<file_sep># Viikkoraportti 2
## Käytetty aika?
2h
## Mitä olen tehnyt tällä viikolla?
Tarkensin aiheuttani labtoolin kommenttien mukaan.
Tutustuin JPS algoritmii, sekä tutustuin enemmän A*.
Katsoin aiheesta useita videoita ja luin artikkeleita.
## Miten ohjelma on edistynyt?
Lisäsin ohjelmaan rungon.
## Mitä opin tällä viikolla /tänään?
Opin A* ja JPS algoritmistä.
## Mitä käi epäselväksi tai tuottanut vaikeuksia?
Edelleen sama tilanne kuin viime viikolla, loma.
Tarkoitukseni on päästä paneutumaan kunnolla ensi viikolla kun arki alkaa.
## Mitä teen seuraavaksi?
Ensi viikolla rakennan näiden algoritmien ensimmäiset toteutukset.
| 9372d88561a73f3d012988438ba17efcd7f35c21 | [
"Markdown",
"Java"
] | 4 | Markdown | jkukko/tiralabra | 29aafa147b980128c49166734fcf1c0a007923a5 | 5fe7327f9d431746336d093aa53de1cc71104f5c |
refs/heads/master | <file_sep># 0.1.3
- Add package packageinfo,lanchicon,scoped_model
- Add scoped_model suport
# 0.1.2
- Add package github_trend,font-awesome-icon
- Add drawer and endDrawer widget
- Load languages for endDrawer
# 0.1.1
- Read trending data from github search api
- Change app name to `GTA`
- Add License
# 0.1.0
- Complete the core layout<file_sep>set -e
# install dependencies
./flutter/bin/flutter packages get
#Serializing JSON using code generation libraries
./flutter/bin/flutter packages pub run build_runner build --delete-conflicting-outputs
# Run the analyzer to find any static analysis issues.
./flutter/bin/flutter analyze --no-pub
# Run the formatter on all the dart files to make sure everything's linted.
find . -not -path "./flutter/*" | grep "\.dart$" | xargs ./flutter/bin/flutter format -n
# Run the actual tests.
./flutter/bin/flutter test
echo "-- Success --"<file_sep>storePassword=<PASSWORD>
keyPassword=<PASSWORD>
keyAlias=key
storeFile=/home/workspace/huangyanxiong/key.jks<file_sep># Github Trending App [](https://travis-ci.org/huangyanxiong01/Github-Trending-App)
Github Trending app built with [Flutter](https://github.com/flutter)+[Redux](https://github.com/brianegan/flutter_redux)+[Built](https://github.com/google/built_value.dart)(Immutable Data)
> If you want to learn Flutter, it is perfect for you. Small but complete
## Features
- [x] View README of the Repository
- [x] Filter repositories by language
- [ ] Filter repositories by date(daily, weekly, monthly)
- [ ] Star your favorite repository
- [X] Github login
- [ ] CI
- [ ] Unit test
## Build
Clone code to local
```
git clone <EMAIL>:huangyanxiong01/Github-Trending-App.git
```
Get packages from dart pub site
```
flutter packages get
```
Build Built Value Generator File
```
flutter packages pub run build_runner build
```
Run app
```
flutter run
```
| 78bf9ff006fd1840b60b8cbb24db177c9cfd473b | [
"Markdown",
"INI",
"Shell"
] | 4 | Markdown | LinuxUbuntuLearn/Github-Trending-App | c6c33390dd30f90f828c8990cebd76dafeb9b822 | 82501c256bb885c248956e201ab8f4b214c63ef2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.