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/main
|
<repo_name>orkuntemiz/MetuISFever<file_sep>/predict.py
import tensorflow as tf
import tensorflow_hub as hub
import torch
from transformers import BartTokenizer, BartForConditionalGeneration
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
torch_device = 'cuda'
QA_TOKENIZER = AutoTokenizer.from_pretrained("dmis-lab/biobert-base-cased-v1.1-squad")
QA_MODEL = AutoModelForQuestionAnswering.from_pretrained("dmis-lab/biobert-base-cased-v1.1-squad")
QA_MODEL.to(torch_device)
QA_MODEL.eval()
import sentencepiece
from transformers import BartTokenizer, BartForConditionalGeneration
SUMMARY_TOKENIZER = BartTokenizer.from_pretrained('sshleifer/distilbart-cnn-12-6')
SUMMARY_MODEL = BartForConditionalGeneration.from_pretrained('sshleifer/distilbart-cnn-12-6')
#from transformers import PegasusTokenizer, PegasusForConditionalGeneration
#SUMMARY_TOKENIZER = PegasusTokenizer.from_pretrained('mayu0007/pegasus_large_covid')
#SUMMARY_MODEL = PegasusForConditionalGeneration.from_pretrained('mayu0007/pegasus_large_covid')
SUMMARY_MODEL.to(torch_device)
SUMMARY_MODEL.eval()
def Summarizer(string_all):
if 1==1:
## try generating an exacutive summary with bart abstractive summarizer
allAnswersTxt = string_all.replace('\n','')
answers_input_ids = SUMMARY_TOKENIZER.batch_encode_plus([allAnswersTxt], return_tensors='pt', max_length=1024)['input_ids'].to(torch_device)
#answers_input_ids = SUMMARY_TOKENIZER.prepare_seq2seq_batch([allAnswersTxt], return_tensors='pt', truncation=True, padding='longest')['input_ids'].to(torch_device)
summary_ids = SUMMARY_MODEL.generate(answers_input_ids,
num_beams=4,
length_penalty=0.8,
repetition_penalty=2.0,
min_length=5,
no_repeat_ngram_size=0,
do_sample=False )
exec_sum = SUMMARY_TOKENIZER.decode(summary_ids.squeeze(), skip_special_tokens=True)
return exec_sum
# Program to find most frequent
# element in a list
from collections import Counter
def most_frequent(List):
occurence_count = Counter(List)
return occurence_count.most_common(1)[0][0]
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM,AutoModelForSequenceClassification
#hg_model_hub_name = "ynie/roberta-large-snli_mnli_fever_anli_R1_R2_R3-nli"
# hg_model_hub_name = "ynie/albert-xxlarge-v2-snli_mnli_fever_anli_R1_R2_R3-nli"
# hg_model_hub_name = "ynie/bart-large-snli_mnli_fever_anli_R1_R2_R3-nli"
# hg_model_hub_name = "ynie/electra-large-discriminator-snli_mnli_fever_anli_R1_R2_R3-nli"
hg_model_hub_name = "ynie/xlnet-large-cased-snli_mnli_fever_anli_R1_R2_R3-nli"
tokenizer_nli = AutoTokenizer.from_pretrained(hg_model_hub_name, use_fast=False)
model_nli = AutoModelForSequenceClassification.from_pretrained(hg_model_hub_name)
model_nli.to(torch_device)
model_nli.eval()
from pyserini.search import pysearch
import re
import sys
from anglicize import anglicize
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
from spacy.tokenizer import Tokenizer
from nltk.tokenize import word_tokenize
from spacy.lang.en import English
import spacy
import en_core_web_sm
nlp = en_core_web_sm.load()
nlp.add_pipe("merge_noun_chunks")
tokenizer = Tokenizer(nlp.vocab)
from timeit import default_timer as timer
import time
import json
import numpy as np
import statistics
import pandas as pd
dataset_path = "dev.jsonl"
output_path = dataset_path.replace(".jsonl", "_predictions.jsonl")
evaluation_path = dataset_path.replace(".jsonl", "_evaluation.jsonl")
with open(dataset_path, "r", encoding="utf-8") as f:
dataset = [json.loads(line) for line in f]
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
pd.set_option("display.width", 1000)
import sqlalchemy as sqla
db_fullpath = "feverous_wikiv1.db"
db = sqla.create_engine("sqlite:///{}".format(db_fullpath))
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=db)
sql_session = Session()
lucene_dir = 'anserini/indexes/fever/lucene-index-fever-paragraph'
searcher = pysearch.SimpleSearcher(lucene_dir)
def get_relevant_pages(claim, FULL_CLAIM=True, SPACY_ENTITIES=True, CASE_ENTITIES=True, LINKED_PAGES=False, LINKING_PAGES=False, N_RESULTS=70):
if not SPACY_ENTITIES and not CASE_ENTITIES and not LINKED_PAGES:
FULL_CLAIM = True
start_timer = timer()
claim = nlp(claim.replace(" ", " ").replace("", " ")) # Replaces the obnoxious space character with normal space
keywords = set()
entities = set()
if SPACY_ENTITIES:
spacy_entities = [entity.text for entity in claim.ents]
entities.update(spacy_entities)
if CASE_ENTITIES:
case_entities = set()
chunks = claim.noun_chunks
for chunk in chunks:
for token in tokenizer(chunk.text):
if token.text[0].isupper():
case_entities.add(chunk.text)
break
entities.update(case_entities)
#print(case_entities)
#print(entities)
#sys.exit(0)
keywords.update(entities)
if not FULL_CLAIM:
search_query = (", ".join(keywords) + '"' + '", "'.join(entities) + '"')
# search_query = (", ".join(keywords) + ", ".join(entities))
else:
search_query = (claim.text + ' "' + '", "'.join(keywords) + '" "' + '", "'.join(entities) + '"')
# search_query = (claim.text + " " + ", ".join(keywords) + ", ".join(entities))
if FULL_CLAIM or keywords:
try:
lucene_hits = searcher.search(search_query.encode("utf-8"), k=N_RESULTS)
except:
lucene_hits = None
else:
lucene_hits = None
hit_dictionary = {}
if lucene_hits:
for hit in lucene_hits:
hit_dict = {"abstract": None, "real_abstract": None, "title": None}
hit_dict['abstract']=hit.lucene_document.get("raw")
hit_dict['real_abstract']=hit.lucene_document.get("raw")
hit_dict['title'] = str(hit.docid)
hit_dictionary[str(hit.docid)] = hit_dict
linked_pages = set()
if LINKED_PAGES:
for hit in lucene_hits:
links = re.findall(r"(?:\[\[)(.*?)(?:\|)", hit.raw)
for link in links:
linked_pages.update([link.replace("_", " ").encode("latin-1", "ignore").decode("utf-8", "ignore")])
linking_pages = set()
if LINKING_PAGES and sql_session:
linking_results = sql_session.execute('select target, sources from inlinks where target IN ("{}")'.format('", "'.join([hit.docid.replace('"', '""') for hit in lucene_hits])))
for row in linking_results:
linking_pages.update(row["sources"].split(";"))
found_pages = [hit.docid for hit in lucene_hits]
for i in range(0, len(found_pages)):
try:
found_pages[i] = found_pages[i].encode("latin-1", "ignore").decode("utf-8", "ignore")
#print("Done:",found_pages[i])
except:
import regex
print(found_pages[i], anglicize(found_pages[i]), regex.sub(r'[^\p{Latin}]', '', found_pages[i]).encode("latin-1").decode("utf-8"))
found_pages = set(found_pages)
hit_scores = [hit.score for hit in lucene_hits]
hit_score_min = min(hit_scores)
hit_score_25 = np.percentile(hit_scores, 25)
hit_score_mean = np.mean(hit_scores)
hit_score_median = statistics.median(hit_scores)
hit_score_75 = np.percentile(hit_scores, 75)
hit_score_max = max(hit_scores)
else:
is_found = False
found_pages = set()
entities = set()
keywords = set()
linked_pages = set()
linking_pages = set()
lucene_hits = []
hit_scores = []
hit_score_min = None
hit_score_25 = None
hit_score_mean = None
hit_score_median = None
hit_score_75 = None
hit_score_max = None
end_timer = timer()
elapsed = int(end_timer - start_timer)
elapsed_formatted = time.strftime("%H:%M:%S", time.gmtime(elapsed))
result = [claim.text, elapsed_formatted,
found_pages,
keywords,
linked_pages,
linking_pages,
len(lucene_hits),
hit_score_min, hit_score_25, hit_score_mean, hit_score_median,
hit_score_75, hit_score_max, hit_scores]
#print(result)
result = pd.DataFrame([result], columns=["CLAIM", "ELAPSED",
"PAGES_FOUND",
"KEYWORDS",
"LINKED_PAGES",
"LINKING_PAGES",
"N_LUCENE_HITS",
"HIT_SCORE_MIN", "HIT_SCORE_25", "HIT_SCORE_MEAN", "HIT_SCORE_MEDIAN",
"HIT_SCORE_75", "HIT_SCORE_MAX", "HIT_SCORES"])
return result, hit_dictionary
def CheckEntailmentNeturalorContradict(ranked_aswers, string_all, pandasData):
if 1 == 1:
premise_list = []
hypothesis_list = []
entailment_prob = []
neutral_prob = []
contradict_prob = []
final_result_list = []
if len(ranked_aswers) > 8:
v_range = 8
else:
v_range = len(ranked_aswers)
for i in range(v_range):
if pandasData[i][2] >= 0.4:
max_length = 512
candidate_answer = Summarizer(ranked_aswers[i])
# premise = "symptoms of covid-19 range from none (asymptomatic) to severe pneumonia and it can be fatal. fever and cough are the most common symptoms in patients with 2019-ncov infection. Several people have muscle soreness or fatigue as well as ards. diarrhea, hemoptysis, headache, sore throat, shock, and other symptoms only occur in a small number of patients"
if len(candidate_answer) > len(ranked_aswers[i]):
premise = ranked_aswers[i]
else:
premise = candidate_answer
# premise = "covid-19 symptom is highly various in each patient, with fever, fatigue, shortness of breath, and cough as the main presenting symptoms. patient with covid-19 may shows severe symptom with severe pneumonia and ards, mild symptom resembling simple upper respiration tract infection, or even completely asymptomatic. approximately 80 % of cases is mild "
hypothesis = string_all
tokenized_input_seq_pair = tokenizer_nli.encode_plus(
premise,
hypothesis,
max_length=max_length,
return_token_type_ids=True,
truncation=True,
)
input_ids = (
torch.Tensor(tokenized_input_seq_pair["input_ids"])
.long()
.unsqueeze(0)
.to(torch_device)
)
# remember bart doesn't have 'token_type_ids', remove the line below if you are using bart.
token_type_ids = (
torch.Tensor(tokenized_input_seq_pair["token_type_ids"])
.long()
.unsqueeze(0)
.to(torch_device)
)
attention_mask = (
torch.Tensor(tokenized_input_seq_pair["attention_mask"])
.long()
.unsqueeze(0)
.to(torch_device)
)
outputs = model_nli(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
labels=None,
)
# Note:
# "id2label": {
# "0": "entailment",
# "1": "neutral",
# "2": "contradiction"
# },
predicted_probability = torch.softmax(outputs[0], dim=1)[
0
].tolist() # batch_size only one
# print("Premise:", premise)
premise_list.append(premise)
# print("Hypothesis:", hypothesis)
hypothesis_list.append(hypothesis)
# print("input Ans:",ranked_aswers[i])
# print("Entailment:", predicted_probability[0])
entailment_prob.append(predicted_probability[0])
# print("Neutral:", predicted_probability[1])
neutral_prob.append(predicted_probability[1])
# print("Contradiction:", predicted_probability[2])
contradict_prob.append(predicted_probability[2])
if len(premise_list) > 0:
avg_entailment = np.average(entailment_prob)
avg_neutral = np.average(neutral_prob)
avg_contradiction = np.average(contradict_prob)
zipped_list = zip(entailment_prob, neutral_prob, contradict_prob)
for key, val in enumerate(hypothesis_list):
if neutral_prob[key] > 0.8:
final_result = "Neutral"
elif entailment_prob[key] > contradict_prob[key]:
final_result = "True"
final_result_list.append(final_result)
else:
final_result = "False"
final_result_list.append(final_result)
if len(final_result_list) > 0:
verdict = most_frequent(final_result_list)
else:
verdict = "Neutral"
else:
# zipped_list = zip(0,1,0)
zipped_list = zip([0], [1], [0])
verdict = "Neutral"
return zipped_list, verdict
def embed_useT(module):
with tf.Graph().as_default():
sentences = tf.compat.v1.placeholder(tf.string)
embed = hub.Module(module)
embeddings = embed(sentences)
session = tf.compat.v1.train.MonitoredSession()
return lambda x: session.run(embeddings, {sentences: x})
embed_fn = embed_useT('/home/titanx/kaggle/working/sentence_wise_email/module/module_useT')
def get_answers(query, hit_dictionary, display_table=False):
for idx,v in hit_dictionary.items():
abs_dirty = v['abstract']
real_abs_dirty = v['real_abstract']
#abs_dirty = v['paragraph']
# looks like the abstract value can be an empty list
v['abstract_paragraphs'] = []
v['abstract_full'] = ''
v['real_abstract_full'] = ''
v['real_abstract_paragraphs']=[]
if abs_dirty:
# looks like if it is a list, then the only entry is a dictionary wher text is in 'text' key
# looks like it is broken up by paragraph if it is in that form. lets make lists for every paragraph
# and a new entry that is full abstract text as both could be valuable for BERT derrived QA
if isinstance(abs_dirty, list):
for p in abs_dirty:
v['abstract_paragraphs'].append(p['text'])
v['abstract_full'] += p['text'] + ' \n\n'
# looks like in some cases the abstract can be straight up text so we can actually leave that alone
if isinstance(abs_dirty, str):
v['abstract_paragraphs'].append(abs_dirty)
v['abstract_full'] += abs_dirty + ' \n\n'
if real_abs_dirty:
# looks like if it is a list, then the only entry is a dictionary wher text is in 'text' key
# looks like it is broken up by paragraph if it is in that form. lets make lists for every paragraph
# and a new entry that is full abstract text as both could be valuable for BERT derrived QA
if isinstance(real_abs_dirty, list):
for p in real_abs_dirty:
v['real_abstract_paragraphs'].append(p['text'])
v['real_abstract_full'] += p['text'] + ' \n\n'
# looks like in some cases the abstract can be straight up text so we can actually leave that alone
if isinstance(abs_dirty, str):
v['real_abstract_paragraphs'].append(real_abs_dirty)
v['real_abstract_full'] += real_abs_dirty + ' \n\n'
v["indexed_para"]=v["abstract_full"][len(v["real_abstract_full"]):]
# def embed_useT(module):
# with tf.Graph().as_default():
# sentences = tf.compat.v1.placeholder(tf.string)
# embed = hub.Module(module)
# embeddings = embed(sentences)
# session = tf.compat.v1.train.MonitoredSession()
# return lambda x: session.run(embeddings, {sentences: x})
# embed_fn = embed_useT('/home/titanx/kaggle/working/sentence_wise_email/module/module_useT')
import numpy as np
#Reconstruct text for generating the answer text from the BERT result, do the necessary text preprocessing and construct the answer.
def reconstructText(tokens, start=0, stop=-1):
tokens = tokens[start: stop]
if '[SEP]' in tokens:
sepind = tokens.index('[SEP]')
tokens = tokens[sepind+1:]
txt = ' '.join(tokens)
txt = txt.replace(' ##', '')
txt = txt.replace('##', '')
txt = txt.strip()
txt = " ".join(txt.split())
txt = txt.replace(' .', '.')
txt = txt.replace('( ', '(')
txt = txt.replace(' )', ')')
txt = txt.replace(' - ', '-')
txt_list = txt.split(' , ')
txt = ''
nTxtL = len(txt_list)
if nTxtL == 1:
return txt_list[0]
newList =[]
for i,t in enumerate(txt_list):
if i < nTxtL -1:
if t[-1].isdigit() and txt_list[i+1][0].isdigit():
newList += [t,',']
else:
newList += [t, ', ']
else:
newList += [t]
return ''.join(newList)
def makeBERTSQuADPrediction(document, question):
## we need to rewrite this function so that it chuncks the document into 250-300 word segments with
## 50 word overlaps on either end so that it can understand and check longer abstracts
## Get chuck of documents in order to overcome the BERT's max 512 token problem. First count the number of tokens. For example if it is
## larger than 2048 token determine the split size and overlapping token count. Split the document into pieces to fed into BERT encoding. Overlapping
## is necessary to maintain the coherence between the splits. If the token count is larger than some number 2560 token approximately this will fail.
nWords = len(document.split())
input_ids_all = QA_TOKENIZER.encode(question, document)
tokens_all = QA_TOKENIZER.convert_ids_to_tokens(input_ids_all)
overlapFac = 1.1
if len(input_ids_all)*overlapFac > 2560:
nSearchWords = int(np.ceil(nWords/6))
fifth = int(np.ceil(nWords/5))
docSplit = document.split()
docPieces = [' '.join(docSplit[:int(nSearchWords*overlapFac)]),
' '.join(docSplit[fifth-int(nSearchWords*overlapFac/2):fifth+int(fifth*overlapFac/2)]),
' '.join(docSplit[fifth*2-int(nSearchWords*overlapFac/2):fifth*2+int(fifth*overlapFac/2)]),
' '.join(docSplit[fifth*3-int(nSearchWords*overlapFac/2):fifth*3+int(fifth*overlapFac/2)]),
' '.join(docSplit[fifth*4-int(nSearchWords*overlapFac/2):fifth*4+int(fifth*overlapFac/2)]),
' '.join(docSplit[-int(nSearchWords*overlapFac):])]
input_ids = [QA_TOKENIZER.encode(question, dp) for dp in docPieces]
elif len(input_ids_all)*overlapFac > 2048:
nSearchWords = int(np.ceil(nWords/5))
quarter = int(np.ceil(nWords/4))
docSplit = document.split()
docPieces = [' '.join(docSplit[:int(nSearchWords*overlapFac)]),
' '.join(docSplit[quarter-int(nSearchWords*overlapFac/2):quarter+int(quarter*overlapFac/2)]),
' '.join(docSplit[quarter*2-int(nSearchWords*overlapFac/2):quarter*2+int(quarter*overlapFac/2)]),
' '.join(docSplit[quarter*3-int(nSearchWords*overlapFac/2):quarter*3+int(quarter*overlapFac/2)]),
' '.join(docSplit[-int(nSearchWords*overlapFac):])]
input_ids = [QA_TOKENIZER.encode(question, dp) for dp in docPieces]
elif len(input_ids_all)*overlapFac > 1536:
nSearchWords = int(np.ceil(nWords/4))
third = int(np.ceil(nWords/3))
docSplit = document.split()
docPieces = [' '.join(docSplit[:int(nSearchWords*overlapFac)]),
' '.join(docSplit[third-int(nSearchWords*overlapFac/2):third+int(nSearchWords*overlapFac/2)]),
' '.join(docSplit[third*2-int(nSearchWords*overlapFac/2):third*2+int(nSearchWords*overlapFac/2)]),
' '.join(docSplit[-int(nSearchWords*overlapFac):])]
input_ids = [QA_TOKENIZER.encode(question, dp) for dp in docPieces]
elif len(input_ids_all)*overlapFac > 1024:
nSearchWords = int(np.ceil(nWords/3))
middle = int(np.ceil(nWords/2))
docSplit = document.split()
docPieces = [' '.join(docSplit[:int(nSearchWords*overlapFac)]),
' '.join(docSplit[middle-int(nSearchWords*overlapFac/2):middle+int(nSearchWords*overlapFac/2)]),
' '.join(docSplit[-int(nSearchWords*overlapFac):])]
input_ids = [QA_TOKENIZER.encode(question, dp) for dp in docPieces]
elif len(input_ids_all)*overlapFac > 512:
nSearchWords = int(np.ceil(nWords/2))
docSplit = document.split()
docPieces = [' '.join(docSplit[:int(nSearchWords*overlapFac)]), ' '.join(docSplit[-int(nSearchWords*overlapFac):])]
input_ids = [QA_TOKENIZER.encode(question, dp) for dp in docPieces]
else:
input_ids = [input_ids_all]
absTooLong = False
answers = []
cons = []
#print(input_ids)
for iptIds in input_ids:
tokens = QA_TOKENIZER.convert_ids_to_tokens(iptIds)
#print(tokens)
sep_index = iptIds.index(QA_TOKENIZER.sep_token_id)
num_seg_a = sep_index + 1
num_seg_b = len(iptIds) - num_seg_a
segment_ids = [0]*num_seg_a + [1]*num_seg_b
assert len(segment_ids) == len(iptIds)
n_ids = len(segment_ids)
#print(n_ids)
if n_ids < 512:
outputs = QA_MODEL(torch.tensor([iptIds]).to(torch_device),
token_type_ids=torch.tensor([segment_ids]).to(torch_device))
#print(QA_MODEL(torch.tensor([iptIds]).to(torch_device),
# token_type_ids=torch.tensor([segment_ids]).to(torch_device)))
else:
#this cuts off the text if its more than 512 words so it fits in model space
#need run multiple inferences for longer text. add to the todo. I will try to expand this to longer sequences if it is necessary.
# print('****** warning only considering first 512 tokens, document is '+str(nWords)+' words long. There are '+str(n_ids)+ ' tokens')
absTooLong = True
outputs= QA_MODEL(torch.tensor([iptIds[:512]]).to(torch_device),
token_type_ids=torch.tensor([segment_ids[:512]]).to(torch_device))
start_scores=outputs.start_logits
end_scores=outputs.end_logits
start_scores = start_scores[:,1:-1]
end_scores = end_scores[:,1:-1]
answer_start = torch.argmax(start_scores)
answer_end = torch.argmax(end_scores)
#print(answer_start, answer_end)
answer = reconstructText(tokens, answer_start, answer_end+2)
if answer.startswith('. ') or answer.startswith(', '):
answer = answer[2:]
c = start_scores[0,answer_start].item()+end_scores[0,answer_end].item()
answers.append(answer)
cons.append(c)
maxC = max(cons)
iMaxC = [i for i, j in enumerate(cons) if j == maxC][0]
confidence = cons[iMaxC]
answer = answers[iMaxC]
sep_index = tokens_all.index('[SEP]')
full_txt_tokens = tokens_all[sep_index+1:]
abs_returned = reconstructText(full_txt_tokens)
ans={}
ans['answer'] = answer
#print(answer)
if answer.startswith('[CLS]') or answer_end.item() < sep_index or answer.endswith('[SEP]'):
ans['confidence'] = -1000000
else:
#confidence = torch.max(start_scores) + torch.max(end_scores)
#confidence = np.log(confidence.item())
ans['confidence'] = confidence
#ans['start'] = answer_start.item()
#ans['end'] = answer_end.item()
ans['abstract_bert'] = abs_returned
ans['abs_too_long'] = absTooLong
return ans
from tqdm import tqdm
def searchAbstracts(hit_dictionary, question):
abstractResults = {}
# for k,v in tqdm(hit_dictionary.items()):
for k,v in hit_dictionary.items():
abstract = v['abstract_full']
indexed_para=v['indexed_para']
if abstract:
ans = makeBERTSQuADPrediction(abstract, question)
if ans['answer']:
confidence = ans['confidence']
abstractResults[confidence]={}
abstractResults[confidence]['answer'] = ans['answer']
#abstractResults[confidence]['start'] = ans['start']
#abstractResults[confidence]['end'] = ans['end']
abstractResults[confidence]['abstract_bert'] = ans['abstract_bert']
abstractResults[confidence]['idx'] = k
abstractResults[confidence]['abs_too_long'] = ans['abs_too_long']
cList = list(abstractResults.keys())
if cList:
maxScore = max(cList)
total = 0.0
exp_scores = []
for c in cList:
s = np.exp(c-maxScore)
exp_scores.append(s)
total = sum(exp_scores)
for i,c in enumerate(cList):
abstractResults[exp_scores[i]/total] = abstractResults.pop(c)
return abstractResults
answers = searchAbstracts(hit_dictionary, query)
workingPath = '/root/kaggle/working'
import pandas as pd
import re
from IPython.core.display import display, HTML
#from summarizer import Summarizer
#summarizerModel = Summarizer()
def displayResults(hit_dictionary, answers, question, display_table=False):
question_HTML = '<div style="font-family: Times New Roman; font-size: 28px; padding-bottom:28px"><b>Query</b>: '+question+'</div>'
#all_HTML_txt = question_HTML
confidence = list(answers.keys())
confidence.sort(reverse=True)
confidence = list(answers.keys())
confidence.sort(reverse=True)
page_answers = dict()
for c in confidence:
if c>0 and c <= 1 and len(answers[c]['answer']) != 0:
if 'idx' not in answers[c]:
continue
rowData = []
idx = answers[c]['idx']
title = hit_dictionary[idx]['title']
full_abs = answers[c]['abstract_bert']
bert_ans = answers[c]['answer']
#split_abs = full_abs.split(bert_ans)
#x=(split_abs[0][:split_abs[0].rfind('. ')+1])
#sentance_beginning = x[x.rfind('. ')+1:] + split_abs[0][split_abs[0].rfind('. ')+1:]
#sentance_beginning = split_abs[0][split_abs[0].rfind('.')+1:]
x=''
y=''
z=''
t=''
# print(bert_ans)
split_abs = full_abs.split(bert_ans)
sentance_beginning = split_abs[0].split(" ~ ~ ")[-1]
if len(split_abs) > 1:
sentance_end = split_abs[1].split(" ~ ~ ")[0]
else:
sentance_end = ""
sentance_full = sentance_beginning + bert_ans+ sentance_end
# print(sentance_full)
answer_ids = re.findall(r"((sentence|table|cell|section|list|item)( _ [0-9]+)+ )", sentance_full)
answer_ids_formatted = []
for ids in answer_ids:
if isinstance(ids, str):
candidate = ids.replace(" ", "")
if "_" in candidate and candidate[0] != "_" and candidate not in ["sentence", "table", "cell", "section", "list", "item"]: # very hacky
answer_ids_formatted.append(candidate)
else:
for id in ids:
candidate = id.replace(" ", "")
if "_" in candidate and candidate[0] != "_" and candidate not in ["sentence", "table", "cell", "section", "list", "item"]: # very hacky
answer_ids_formatted.append(candidate)
# print(answer_ids_formatted)
page_answers[title] = answer_ids_formatted
answers[c]['full_answer'] = sentance_beginning+bert_ans+sentance_end
answers[c]['partial_answer'] = bert_ans+sentance_end
answers[c]['sentence_beginning'] = sentance_beginning
answers[c]['sentence_end'] = sentance_end
answers[c]['title'] = title
else:
answers.pop(c)
## now rerank based on semantic similarity of the answers to the question
## Universal sentence encoder
cList = list(answers.keys())
allAnswers = [answers[c]['full_answer'] for c in cList]
messages = [question]+allAnswers
encoding_matrix = embed_fn(messages)
similarity_matrix = np.inner(encoding_matrix, encoding_matrix)
rankings = similarity_matrix[1:,0]
for i,c in enumerate(cList):
answers[rankings[i]] = answers.pop(c)
## now form pandas dv
confidence = list(answers.keys())
confidence.sort(reverse=True)
pandasData = []
ranked_aswers = []
full_abs_list=[]
for c in confidence:
rowData=[]
title = answers[c]['title']
idx = answers[c]['idx']
rowData += [idx]
sentance_html = '<div>' +answers[c]['sentence_beginning'] + " <font color='red'>"+answers[c]['answer']+"</font> "+answers[c]['sentence_end']+'</div>'
answer_key = answers[c]['answer'].split("\t")[-1].strip() if "\t" in answers[c]['answer'] else answers[c]['answer'].strip()
# rowData += [sentance_html, answer_key, c,title]
rowData += [sentance_html, c,title]
pandasData.append(rowData)
ranked_aswers.append(' '.join([answers[c]['full_answer']]))
full_abs_list.append(' '.join([answers[c]['abstract_bert']]))
else:
pdata2 = pandasData
if display_table:
display(HTML(question_HTML))
# display(HTML('<div style="font-family: Times New Roman; font-size: 18px; padding-bottom:18px"><b>Body of Evidence:</b></div>'))
# df = pd.DataFrame(pdata2, columns = ['Lucene ID', 'BERT-SQuAD Answer with Highlights', 'Answer Key', 'Confidence', 'Title/Link'])
df = pd.DataFrame(pdata2, columns = ['Lucene ID', 'BERT-SQuAD Answer with Highlights', 'Confidence', 'Title/Link'])
display(HTML(df.to_html(render_links=True, escape=False)))
return page_answers,full_abs_list,ranked_aswers,pandasData
return displayResults(hit_dictionary, answers, query, display_table)
# depth or breadth
# EVIDENCE_RETRIEVAL = "breadth"
EVIDENCE_RETRIEVAL = "depth"
with open(output_path, 'w', encoding='utf-8') as f:
f.write('{"id": "", "predicted_label": "", "predicted_evidence": ""}\n')
if EVAL and os.path.isfile(evaluation_path):
os.remove(evaluation_path)
from tqdm import tqdm
for data in tqdm(dataset[:100]):
claim = data["claim"]
if not claim:
continue
hit_stats, hit_dictionary = get_relevant_pages(claim)
page_answers, full_abs_list, ranked_aswers, pandasData = get_answers(claim, hit_dictionary, display_table=False)
# print(page_answers)
# print(pandasData)
# continue
evidence_probs, verdict = CheckEntailmentNeturalorContradict(ranked_aswers,claim,pandasData)
if verdict == "False":
predicted_label = "REFUTES"
elif verdict == "True":
predicted_label = "SUPPORTS"
else:
predicted_label = "NOT ENOUGH INFO"
pages_by_confidence = [row[0] for row in pandasData]
evidences = []
if EVIDENCE_RETRIEVAL == "depth":
for page in pages_by_confidence:
idx = page_answers[page]
for element in idx:
if len(evidences) < 5:
element_type, element_id = element.split("_", 1)
evidence = [page, element_type, element_id]
if evidence not in evidences:
evidences.append(evidence)
else:
break
else:
while len(evidences) < 5:
for page in pages_by_confidence:
idx = page_answers[page]
for element in idx:
if len(evidences) < 5:
element_type, element_id = element.split("_", 1)
evidence = [page, element_type, element_id]
if evidence not in evidences:
evidences.append(evidence)
break
else:
continue
else:
break
output = {"id": data["id"], "predicted_label": predicted_label, "predicted_evidence": evidences}
with open(output_path, 'a', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=None)
f.write("\n")
if EVAL and data["label"] and data["evidence"]:
evaluation = {"id": data["id"], "claim": data["claim"], "label": data["label"],
"predicted_label": predicted_label,
"evidence": data["evidence"], "predicted_evidence": []}
for evidence in evidences:
evidence_str = evidence[0] + "_" + evidence[1] + "_" + evidence[2]
evaluation["predicted_evidence"].append(evidence_str)
with open(evaluation_path, 'a', encoding='utf-8') as f:
json.dump(evaluation, f, ensure_ascii=False, indent=None)
f.write("\n")
# print(claim)
# print(output)
<file_sep>/README.md
# MetuISFever
Metu IS Fever Competition Group
|
ac80967681bb40f31e56b9e482efe8c833edb117
|
[
"Markdown",
"Python"
] | 2
|
Python
|
orkuntemiz/MetuISFever
|
c7f254a76ee1954472d900ce4e7205d6ebc3a46e
|
4de011bcb5827f90c34165448db13ae13ef5f47c
|
refs/heads/master
|
<repo_name>aahadpatel/search_engine<file_sep>/webpage.cpp
#include <iostream>
#include <string>
#include <cctype>
#include <set>
#include "webpage.h"
using namespace std;
Webpage::Webpage()
{
}
Webpage::~Webpage()
{
}
//making the string lowercase
string Webpage::lowerWord(string word)
{
string ret = "";
for(int i=0;i<(int)word.length();i++) {
ret += tolower(word[i]);
}
return ret;
}
//insert words in words set
void Webpage::insert_word(string output)
{
words.insert(lowerWord(output));
}
//inserting filepath into set incoming_links
void Webpage::insert_incoming_links(string filepath)
{
incoming_links.insert(filepath);
}
//inserting filepath into set outgoing_links
void Webpage::insert_outgoing_links(string filepath)
{
outgoing_links.insert(filepath);
}
//check if a word is contained in set words
bool Webpage::containsWord(string word)
{
if(words.find(word) == words.end()) {
return false;
}
return true;
}
//get incoming links set
set<string> Webpage::incomingLinks()
{
return incoming_links;
}
//get outgoing links set
set<string> Webpage::outgoingLinks()
{
return outgoing_links;
}
//check incoming
bool Webpage::inIncoming(string page){
if(!incoming_links.empty()) {
set<string>::iterator it = incoming_links.find(page);
if(it == incoming_links.end()) return false;
return true;
}
return false;
}
//check if outgoing
bool Webpage::inOutgoing(string page){
if(!outgoing_links.empty()) {
set<string>::iterator it = outgoing_links.find(page);
if(it == outgoing_links.end()) return false;
return true;
}
return false;
}
<file_sep>/README.md
Makefile:
In order to compile crawler, use "make crawler"
and run using ./crawler config.txt
In order to compile search, use "make search"
and run using ./crawler config.txt
make clean is provided<file_sep>/search.cpp
#include <iostream>
#include <map>
#include <set>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <vector>
#include <cctype>
#include "webpage.h"
#include "database.h"
#include "config.h"
using namespace std;
//lowercase
string lowerWord(string word)
{
string ret = "";
for(int i=0;i<(int)word.length();i++) {
ret += tolower(word[i]);
}
return ret;
}
//pagerank takes in candidate vector, restart probability, step, and database object
vector<string> page_rank(vector<string>& candidate_set, double r, int step, Database& database)
{
//return v
vector<string> v;
//creating outDegree array
int *degOut = new int[(int)candidate_set.size()];
for(int n=0;n<(int)candidate_set.size();n++) {
degOut[n] = 1;
}
//creating adjacency matrix
int **matrix = new int*[(int)candidate_set.size()];
for(int l = 0; l < (int)candidate_set.size(); l++) {
matrix[l] = new int[(int)candidate_set.size()];
}
//creating 2-d array storing rank values
double **rankResult = new double*[step+1];
for(int m = 0; m < step+1; m++) {
rankResult[m] = new double[(int)candidate_set.size()];
}
//initializing adjacency matrix diagonals and 0s
for(int a=0;a<(int)candidate_set.size();a++) {
for(int u=0;u<(int)candidate_set.size();u++) {
if(a == u) matrix[a][u] = 1;
else matrix[a][u] = 0;
}
}
//initializing rankResult base cases (1/number of nodes)
for(int o = 0; o < (int)candidate_set.size(); o++) {
rankResult[0][o] = (1.0/(int)candidate_set.size());
}
//get each webpage and fill matrix
for(int i=0;i<(int)candidate_set.size();i++) {
Webpage *curr = database.getWebpage(candidate_set[i]);
for(int j=i+1;j<(int)candidate_set.size();j++) {
if(curr->inOutgoing(candidate_set[j])) {
matrix[i][j] = 1;
degOut[i] += 1;
}
if(curr->inIncoming(candidate_set[j])) {
matrix[j][i] = 1;
if(i < j) {
degOut[j] += 1;
}
}
}
}
//iterations and add to resulting set
for(int c = 1; c < step+1; c++)
{
for(int d=0;d<(int)candidate_set.size();d++) {
double ans = 0.0;
double sum = 0.0;
for(int e=0;e<(int)candidate_set.size();e++) {
if(matrix[e][d] == 1) {
sum += (rankResult[c-1][e]*(1.0/degOut[e]));
//sum *= (1.0/degOut[e]);
}
}
ans = ((1-r)*sum) + (r*((1.0/candidate_set.size())));
rankResult[c][d] = ans;
}
}
//sorting
for(int f=0;f<(int)candidate_set.size();f++)
{
double max = 0.0;
int ind = 0;
for(int h=0;h<(int)candidate_set.size();h++) {
if(rankResult[step][h] > max) {
max = rankResult[step][h];
ind = h;
}
}
v.push_back(candidate_set[ind]);
//reset
rankResult[step][ind] = 0.0;
}
//delete degOut
delete [] degOut;
//delete 2-d matrix
for(int q = 0; q < (int)candidate_set.size(); q++)
{
delete [] matrix[q];
}
delete [] matrix;
//delete
for(int ab = 0; ab < step+1; ab++)
{
delete [] rankResult[ab];
}
delete [] rankResult;
return v;
}
int main(int argc, char *argv[])
{
//VALIDATION
if(argc > 2)
{
cout << "Invalid number of arguments!" << endl;
}
string configure = "";
if(argc == 1)
configure = "config.txt"; //if no file given, use default- config.txt
else
configure = argv[1]; //take in user's file
Config config;
config.configuration(configure);
string index_file_name = config.getIndex();
int t_steps = stoi(config.getStep());
double e_restart = stod(config.getRestart());
ifstream index;
index.open(index_file_name);
//VALIDATION
if(index.fail())
{
cout << "File could not be opened!" << endl;
return 0;
}
//declaring database object
Database database;
//file path is the actual path, not the name of the file
string file_path;
while(getline(index, file_path))
{
Webpage* new_Webpage = new Webpage;
database.insert_into_map(file_path, new_Webpage);
}
database.parse_Webpages(); //parse Webpages
//open query
ifstream qfile;
string query_file = config.getQuery();
qfile.open(query_file);
//VALIDATION
if(qfile.fail())
{
cout << "File could not be opened!" << endl;
return 0;
}
//output file
string output_file = config.getOutput();
ofstream ofile;
ofile.open(output_file);
//take in first line of query
string line;
//go through query.txt
while(getline(qfile, line))
{
stringstream ss;
ss << line;
string command;
ss >> command;
set<string> candidate_set;
//if the first word is AND
if(command == "AND")
{
string word_to_find;
string first;
set<string> and_words;
int count = 0;
while(ss >> word_to_find)
{
if(count > 0) break;
first = word_to_find;
count += 1;
}
//empty
if(count == 0 || word_to_find == "") {
and_words.insert(lowerWord(command));
set<string> result = database.or_function(and_words);
//ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
set<string> in = database.incoming(*it);
set<string> out = database.outgoing(*it);
set<string>::iterator it1;
for(it1 = in.begin();it1 != in.end();++it1)
{
if(database.containsPage(*it1)) candidate_set.insert(*it1);
}
set<string>::iterator it2;
for(it2 = out.begin();it2 != out.end();++it2)
{
if(database.containsPage(*it2)) candidate_set.insert(*it2);
}
candidate_set.insert(*it);
}
}
else {
//lower, push
and_words.insert(lowerWord(first));
and_words.insert(lowerWord(word_to_find));
while(ss >> word_to_find)
{
//insert into AND set
and_words.insert(lowerWord(word_to_find));
}
set<string> result = database.and_function(and_words);
//ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
set<string> in = database.incoming(*it);
set<string> out = database.outgoing(*it);
set<string>::iterator it1;
for(it1 = in.begin();it1 != in.end();++it1)
{
if(database.containsPage(*it1)) candidate_set.insert(*it1);
}
set<string>::iterator it2;
for(it2 = out.begin();it2 != out.end();++it2)
{
if(database.containsPage(*it2)) candidate_set.insert(*it2);
}
candidate_set.insert(*it);
}
}
//PAGERANK
vector<string> param;
set<string>::iterator itMain;
for(itMain = candidate_set.begin();itMain != candidate_set.end();++itMain)
{
param.push_back(*itMain);
}
vector<string> rankResult = page_rank(param, e_restart, t_steps, database);
ofile << rankResult.size() << endl;
for(int i=0;i<(int)rankResult.size();i++) {
ofile << rankResult[i] << endl;
}
}
//first word is OR
else if(command == "OR")
{
string word_to_find;
string first;
set<string> or_words;
int count = 0;
while(ss >> word_to_find)
{
if(count > 0) break;
first = word_to_find;
count += 1;
}
//insert words into or_words set for future comaprison
if(count == 0 || word_to_find == "") {
or_words.insert(lowerWord(command));
set<string> result = database.or_function(or_words);
//ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
set<string> in = database.incoming(*it);
set<string> out = database.outgoing(*it);
set<string>::iterator it1;
for(it1 = in.begin();it1 != in.end();++it1)
{
if(database.containsPage(*it1)) candidate_set.insert(*it1);
}
set<string>::iterator it2;
for(it2 = out.begin();it2 != out.end();++it2)
{
if(database.containsPage(*it2)) candidate_set.insert(*it2);
}
candidate_set.insert(*it);
}
}
else {
or_words.insert(lowerWord(first));
or_words.insert(lowerWord(word_to_find));
while(ss >> word_to_find)
{
//insert into OR words set
or_words.insert(lowerWord(word_to_find));
}
set<string> result = database.or_function(or_words);
//ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
set<string> in = database.incoming(*it);
set<string> out = database.outgoing(*it);
set<string>::iterator it1;
for(it1 = in.begin();it1 != in.end();++it1)
{
if(database.containsPage(*it1)) candidate_set.insert(*it1);
}
set<string>::iterator it2;
for(it2 = out.begin();it2 != out.end();++it2)
{
if(database.containsPage(*it2)) candidate_set.insert(*it2);
}
candidate_set.insert(*it);
}
}
vector<string> param;
set<string>::iterator itMain;
for(itMain = candidate_set.begin();itMain != candidate_set.end();++itMain)
{
param.push_back(*itMain);
}
vector<string> rankResult = page_rank(param, e_restart, t_steps, database);
ofile << rankResult.size() << endl;
for(int i=0;i<(int)rankResult.size();i++) {
ofile << rankResult[i] << endl;
}
}
//first word is incoming
else if(command == "INCOMING")
{
string link;
set<string> word;
int count = 0;
while(ss >> link)
{
if(count > 0) break;
count += 1;
}
if(count == 0 || link == "") {
word.insert(lowerWord(command));
set<string> result = database.or_function(word);
ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
ofile << *it << endl;
}
}
else {
//check if link is present
if(database.containsPage(link)) {
set<string> result = database.incoming(link);
ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
ofile << *it << endl;
}
}
else {
ofile << "Invalid query" << endl;
}
}
}
//first word is OUTGOING
else if(command == "OUTGOING")
{
string link;
set<string> word;
int count = 0;
while(ss >> link)
{
if(count > 0) break;
count += 1;
}
if(count == 0 || link == "") {
word.insert(lowerWord(command));
set<string> result = database.or_function(word);
ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
ofile << *it << endl;
}
}
else {
//check if link is present
if(database.containsPage(link)) {
set<string> result = database.outgoing(link);
ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
ofile << *it << endl;
}
}
else {
ofile << "Invalid query" << endl;
}
}
}
//first word is PRINT
else if(command == "PRINT")
{
string link;
set<string> word;
int count = 0;
//grab the link
while(ss >> link)
{
if(count > 0) break;
count += 1;
}
if(count == 0 || link == "") {
word.insert(lowerWord(command));
set<string> result = database.or_function(word);
ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
ofile << *it << endl;
}
}
else {
//check if link is contained
if(database.containsPage(link)) {
ofile << link << endl;
//open page
ifstream page;
page.open(link);
string line_to_parse;
//parse all lines to get the contents of the webpage
while(getline(page, line_to_parse)) {
if(line_to_parse == "") {
ofile << endl;
}
else {
for(int i=0;i<(int)line_to_parse.length();i++)
{
if(line_to_parse[i] != '(' && line_to_parse[i] != ')')
{
ofile << line_to_parse[i];
if(i == (int)line_to_parse.length() - 1)
{
ofile << endl;
}
continue;
}
else if(line_to_parse[i] == '(')
{
i++;
while(line_to_parse[i] != ')')
{
i++;
}
}
}
}
}
ofile << endl;
}
else {
ofile << "Invalid query" << endl;
}
}
}
//if just a blank line in file
else if(command == "") {
ofile << "Invalid query" << endl;
}
else
{
//searching for a word
string word_to_find;
set<string> word;
int count = 0;
while(ss >> word_to_find)
{
if(count > 0) break;
count += 1;
}
if(count == 0 || word_to_find == "") {
word.insert(lowerWord(command));
//use union
set<string> result = database.or_function(word);
//ofile << result.size() << endl;
set<string>::iterator it;
for(it = result.begin();it != result.end();++it) {
set<string> in = database.incoming(*it);
set<string> out = database.outgoing(*it);
set<string>::iterator it1;
for(it1 = in.begin();it1 != in.end();++it1)
{
if(database.containsPage(*it1)) candidate_set.insert(*it1);
}
set<string>::iterator it2;
for(it2 = out.begin();it2 != out.end();++it2)
{
if(database.containsPage(*it2)) candidate_set.insert(*it2);
}
candidate_set.insert(*it);
}
vector<string> param;
set<string>::iterator itMain;
for(itMain = candidate_set.begin();itMain != candidate_set.end();++itMain)
{
param.push_back(*itMain);
}
vector<string> rankResult = page_rank(param, e_restart, t_steps, database);
ofile << rankResult.size() << endl;
for(int i=0;i<(int)rankResult.size();i++) {
ofile << rankResult[i] << endl;
}
}
else {
ofile << "Invalid query" << endl;
}
}
}
}
<file_sep>/setutility.h
#include <iostream>
#include <string>
#include <set>
template<class T>
std::set<T> intersect(std::set<T>& lhs, std::set<T>& rhs)
{
std::set<T> result_set;
typename std::set<T>::iterator it1;
typename std::set<T>::iterator it2;
for(it1 = lhs.begin(); it1 != lhs.end(); ++it1)
{
if(rhs.find((*it1)) != rhs.end()) //found
{
result_set.insert(*it1);
}
}
return result_set;
}
//find union for OR command
template<class T>
std::set<T> union_set(std::set<T>& lhs, std::set<T>& rhs)
{
std::set<T> result_set;
typename std::set<T>::iterator it1;
typename std::set<T>::iterator it2;
for(it1 = lhs.begin(); it1 != lhs.end(); ++it1)
{
result_set.insert(*it1);
}
for(it2 = rhs.begin(); it2 != rhs.end(); ++it2)
{
result_set.insert(*it2);
}
return result_set;
}
<file_sep>/database.h
#include <iostream>
#include <map>
#include <set>
#include <string>
#include "webpage.h"
class Database {
public:
Database();
~Database();
//inserting link into map<string, Webpage*>
void insert_into_map(std::string filepath, Webpage* new_Webpage);
//calls intersect
std::set<std::string> and_function(std::set<std::string> and_words);
//calls union_set
std::set<std::string> or_function(std::set<std::string> or_words);
//go through all webpages and while that happens, call parse_Webpage
void parse_Webpages();
//parsing individual webpage
void parse_Webpage(std::string filepath, Webpage* new_Webpage);
//taking care incoming and outgoing links
std::set<std::string> incoming(std::string page);
std::set<std::string> outgoing(std::string page);
//take care of candidates
//std::set<std::string> candidate(std::string page);
//check if page is contained in map<string, Webpage*>
bool containsPage(std::string page);
std::set<Webpage*> setWebpage(std::string word);
Webpage* getWebpage(std::string page);
private:
//using AND command
std::set<std::string> intersect(std::set<std::string> and_set);
//using OR command
std::set<std::string> union_set(std::set<std::string> or_set);
//map containing filenames and the webpages
std::map<std::string, Webpage*> file_name_webpage;
};
<file_sep>/config.h
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
class Config
{
public:
void configuration(std::string filename)
{
std::ifstream ifile;
ifile.open(filename); //open file
std::string parameter;
std::string line_parse;
bool readVar = false;
while(getline(ifile, line_parse))
{
for(unsigned int i = 0; i < line_parse.size(); i++)
{
if(line_parse[i] == '#') break;
else if(line_parse[i] == ' ' || line_parse[i] == '\t' || line_parse[i] == '=') {
if(parameter == "") continue;
readVar = true;
}
else
{
if(!readVar) parameter += line_parse[i];
else {
if(parameter == "INDEX_FILE") index += line_parse[i];
else if(parameter == "QUERY_FILE") query += line_parse[i];
else if(parameter == "OUTPUT_FILE") output += line_parse[i];
else if(parameter == "RESTART_PROBABILITY") restart_prob += line_parse[i];
else if(parameter == "STEP_NUMBER") step_num += line_parse[i];
}
}
}
parameter = "";
readVar = false;
}
}
std::string getIndex()
{
return index;
}
std::string getQuery()
{
return query;
}
std::string getOutput()
{
return output;
}
std::string getRestart()
{
return restart_prob;
}
std::string getStep()
{
return step_num;
}
private:
std::string index;
std::string query;
std::string output;
std::string restart_prob;
std::string step_num;
};<file_sep>/webpage.h
#ifndef WEBPAGE_H
#define WEBPAGE_H
#include <iostream>
#include <string>
#include <set>
class Webpage {
public:
//constructor
Webpage();
//destructor
~Webpage();
//inserting words
void insert_word(std::string output);
//insert filepaths to incoming links
void insert_incoming_links(std::string incoming_link);
//inserting filepaths to outgoing_links
void insert_outgoing_links(std::string outgoing_link);
//void insert_candidate_set(std::string candidate);
//check is a word is in the words set
bool containsWord(std::string word);
std::set<std::string> incomingLinks();
std::set<std::string> outgoingLinks();
//std::set<std::string> get_candidate_set();
//std::string get_name();
//void set_name(std::string name);
bool inIncoming(std::string page);
bool inOutgoing(std::string page);
bool inEmpty;
bool outEmpty;
private:
//making a word lowercase
std::string lowerWord(std::string word);
//storing words
std::set<std::string> words;
//store all incoming links
std::set<std::string> incoming_links;
//store all outgoing links
std::set<std::string> outgoing_links;
//candidate set storing incoming and outgoing links
//std::set<std::string> candidate_set;
//std::string name_Webpage;
};
#endif<file_sep>/Makefile
CXX = g++
CPPFLAGS = -g -Wall -std=c++11
BIN_DIR = bin
all: search
crawler: config.h crawler.cpp
$(CXX) $(CPPFLAGS) config.h crawler.cpp -o crawler
search: $(BIN_DIR)/webpage.o $(BIN_DIR)/database.o
$(CXX) $(CPPFLAGS) $(BIN_DIR)/webpage.o $(BIN_DIR)/database.o search.cpp -o search
$(BIN_DIR)/database.o: database.h database.cpp $(BIN_DIR)/.dirstamp
$(CXX) $(CPPFLAGS) -c database.cpp -o $(BIN_DIR)/database.o
$(BIN_DIR)/webpage.o: webpage.h webpage.cpp $(BIN_DIR)/.dirstamp
$(CXX) $(CPPFLAGS) -c webpage.cpp -o $(BIN_DIR)/webpage.o
.PHONY: clean
clean:
rm -rf $(BIN_DIR)
$(BIN_DIR)/.dirstamp:
mkdir -p $(BIN_DIR)
touch $(BIN_DIR)/.dirstamp<file_sep>/database.cpp
#include <iostream>
#include <map>
#include <fstream>
#include <set>
#include <string>
#include <cctype>
#include "database.h"
#include "webpage.h"
using namespace std;
Database::Database()
{
}
//deletes allocated memory (Webpage*)
Database::~Database()
{
map<string, Webpage*>::iterator it;
for(it = file_name_webpage.begin();it != file_name_webpage.end();it++)
{
delete it->second;
}
}
//set Webpage, return word_set of webpage pointers
set<Webpage*> Database::setWebpage(string word)
{
set<Webpage*> word_set;
map<std::string, Webpage*>::iterator it;
for(it = file_name_webpage.begin(); it != file_name_webpage.end(); ++it)
{
if(it->second->containsWord(word))
word_set.insert(it->second);
}
return word_set;
}
//inserting filepath into the map
void Database::insert_into_map(string filepath, Webpage* new_Webpage)
{
file_name_webpage.insert(make_pair(filepath, new_Webpage));
}
//intersection using and_words set, move into intersect function NEW
set<string> Database::and_function(set<string> and_words)
{
return intersect(and_words);
}
//move into union_set function NEW
set<string> Database::or_function(set<string> or_words)
{
return union_set(or_words);
}
//go through the webpages and parse each one, calling parse_Webpage
void Database::parse_Webpages()
{
map<std::string, Webpage*>::iterator it;
for(it = file_name_webpage.begin(); it != file_name_webpage.end(); ++it)
{
parse_Webpage(it->first, it->second);
}
}
//parse the individual webpage
void Database::parse_Webpage(string filepath, Webpage* new_Webpage)
{
ifstream index_contents;
index_contents.open(filepath);
string line_to_parse;
string output;
string output_link;
//go through the contents of the webpage
while(getline(index_contents, line_to_parse)) {
for(int i = 0; i < (int)line_to_parse.length(); i++)
{
if(isalnum(line_to_parse[i]))
{
//add each valid character to output string
output += line_to_parse[i];
if(i == (int)line_to_parse.length() - 1) {
new_Webpage->insert_word(output);
output = "";
}
continue;
}
//if output is not a string
else if(output != "")
{
//put word
new_Webpage->insert_word(output);
output = "";
}
if(line_to_parse[i] == '(')
{
string link_webpage = "";
i++;
while(line_to_parse[i] != ')')
{
link_webpage += line_to_parse[i];
i++;
}
new_Webpage->insert_outgoing_links(link_webpage);
map<string, Webpage*>::iterator it = file_name_webpage.find(link_webpage);
if(it != file_name_webpage.end()) {
it->second->insert_incoming_links(filepath);
}
}
}
}
}
//for access to incoming links
set<string> Database::incoming(string page)
{
return file_name_webpage[page]->incomingLinks();
}
set<string> Database::outgoing(string page)
{
return file_name_webpage[page]->outgoingLinks();
}
bool Database::containsPage(string page)
{
//if page is contained in the map<string, Webpage*>
if(file_name_webpage.find(page) == file_name_webpage.end())
{
return false;
}
return true;
}
//find intersection for AND command
set<string> Database::intersect(set<string> and_set)
{
//return set is the final set that will be returned containing intersection
set<string> return_set;
//iterate through map
map<string, Webpage*>::iterator it1;
//interate through set
set<string>::iterator it2;
//interate through all webpages first (stored in a map)
for(it1 = file_name_webpage.begin();it1 != file_name_webpage.end();++it1)
{
bool hasAllWords = true;
//iterate through the and_set, which contains all words after
//AND command
for(it2 = and_set.begin();it2 != and_set.end();++it2)
{
//make comaprison
if(!(it1->second->containsWord(*it2)))
{
hasAllWords = false;
}
}
//if valid, insert into return_set
if(hasAllWords) return_set.insert(it1->first);
}
return return_set;
}
//find union for OR command
set<string> Database::union_set(set<string> or_set)
{
//return set is the final set that will be returned containing union
set<string> return_set;
//iterator through map
map<string, Webpage*>::iterator it1;
set<string>::iterator it2;
//iterate through webpages (stored in map)
for(it1 = file_name_webpage.begin();it1 != file_name_webpage.end();++it1)
{
bool hasAllWords = false;
//iterate through or_set, which contains all words after
//OR command
for(it2 = or_set.begin();it2 != or_set.end();++it2)
{
//make comparison
if(it1->second->containsWord(*it2))
{
hasAllWords = true;
break;
}
}
//insert into return_set if valid
if(hasAllWords) return_set.insert(it1->first);
}
return return_set;
}
Webpage* Database::getWebpage(string page) {
return file_name_webpage[page];
}<file_sep>/crawler.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <vector>
#include <algorithm>
#include <cctype>
#include <cstring>
#include "config.h"
using namespace std;
//check if a page is in the vector
bool found(string page, vector<string>& v) {
bool found = false;
for(int i=0;i<(int)v.size();i++) {
if(page == v[i]) {
found = true;
break;
}
}
return found;
}
//remove page from vector
void remove(string page, vector<string>& v) {
for(int i=0;i<(int)v.size();i++) {
if(page == v[i]) {
v.erase(v.begin()+i);
}
}
}
//parse a filepath and use dfs to explore new nodes
void parse(string filepath, vector<string>& v)
{
ifstream page;
page.open(filepath);
if(page.fail())
{
remove(filepath, v);
}
else {
string line_to_parse;
//go through the contents of the webpage
while(getline(page, line_to_parse)) {
for(int i = 0; i < (int)line_to_parse.length(); i++)
{
if(line_to_parse[i] == '(')
{
string link_webpage = "";
i++;
while(line_to_parse[i] != ')')
{
link_webpage += line_to_parse[i];
i++;
}
//accounting for outgoing and incoming links as we parse
//new_Webpage->insert_outgoing_links(link_webpage);
bool f = found(link_webpage, v);
//dfs
if(!f) {
v.push_back(link_webpage);
parse(link_webpage, v);
}
else {
continue;
}
}
}
}
}
}
int main(int argc, char *argv[])
{
string configure;
if(argc == 1)
configure = "config.txt"; //if no file given, use default- config.txt
else
configure = argv[1]; //take in user's file
Config config;
config.configuration(configure);
//get index and output
string index = config.getIndex();
string output = config.getOutput();
ifstream index_contents;
index_contents.open(index);
if(index_contents.fail())
{
cout << "File could not be opened!" << endl;
}
vector<string> v;
string line_to_parse;
while(getline(index_contents, line_to_parse)) {
if(!found(line_to_parse, v)) v.push_back(line_to_parse);
parse(line_to_parse, v);
}
//output
ofstream of;
of.open(output);
//print final contents
for(unsigned int i = 0; i < v.size(); i++)
{
of << v[i] << endl;
}
of.close();
}
|
2eb9a67edbb18dc8e82e6f040f2bfb3fc4ad351d
|
[
"Markdown",
"Makefile",
"C++"
] | 10
|
C++
|
aahadpatel/search_engine
|
65a9e585479b7c647f16d441d6f48fe04d199f16
|
93d04aadf4879b3b6c2c33b7a8957f90ded9c667
|
refs/heads/master
|
<repo_name>linuxlovr1/lunch_lady<file_sep>/lunch_lady.rb
# Basic Objectives:
# - user chooses from a list of main dishes
# - user chooses 2 side dish items
# - computer repeats users order
# - computer totals lunch items and displays total
# Bonus Objectives:
# - user can choose as many "add-on" items as they want before getting total
# - user can clear their choices and start over
# - user has a wallet total they start with and their choices cannot exceed what they can pay for
# - program is in a loop to keep asking the user to make new orders until they type 'quit' at any time
# - main dishes and side items have descriptions with them and the user has an option to view the description before they order (hint: think hashes)
# - descriptions of food can have multiple options like nutritional facts, calories, fat content ect...(hint: think nested hashes)
# - display to the user not only their total but the total fat content / calories / carbs / ect...
# - have an option to display
#class Lunch_lady
#attr_accessor main:, side1:, side2:
@arr = []
def main
puts "What main dish would you like?"
puts "1: Meatloaf (5.00)"
puts "2: Mystery meat (3.00)"
puts "3: Slop (1.00)"
selection1 = gets.strip.to_f
case selection1
when "1"
answer = 5.00
when "2"
answer = 3.00
when "3"
answer = 1.00
answer >> @arr.index(0)
end
end
def side1
puts "What side dish would you like?"
puts "1: Beans (1.75)"
puts "2: Yogurt (1.00)"
puts "3: Potatoes (.50)"
selection2 = gets.strip.to_f
case selection2
when "1"
answer = 1.75
when "2"
answer = 1.00
when "3"
answer = 0.50
answer >> @arr.index(1)
end
end
def side2
puts "What 2nd side dish would you like?"
puts "1: Beans (1.75)"
puts "2: Yogurt (1.00)"
puts "3: Potatoes (.50)"
selection3 = gets.strip.to_f
case selection3
when "1"
answer = 1.75
when "2"
answer = 1.00
when "3"
answer = 0.50
answer >> @arr.index(2)
end
end
def price_calculation
add = @arr.index
puts "your total is " "#{add}"
end
#def order_contents
# puts "Your order consits of " "#{list}"
#end
main
@arr
side1
side2
price_calculation
#order_contents
# arr = [
# { dish: "Meatloaf", price: "5.00", dish: "Mystery meat", price: "3.00", dish: "Slop", price: "1.00" },
# { dish: "Beans", price: 1.75, dish: "Yogurt", price: 1.00, dish: "Potatoes", price: 0.50 },
# { dish: "Beans", price: 1.75, dish: "Yogurt", price: 1.00, dish: "Potatoes", price: 0.50 }
# ]
#end
|
4005fa985da3395873879706f5e06c66df3aae55
|
[
"Ruby"
] | 1
|
Ruby
|
linuxlovr1/lunch_lady
|
6478c6a3983d09fb8f9d0c762e3ce032bf62c072
|
f892d0d1fa100bb783148e0bbdf1f4ca8a8f6b99
|
refs/heads/master
|
<repo_name>JanSimek/routing-homework<file_sep>/README.md
[](https://github.com/JanSimek/routing-homework/actions) [](https://codebeat.co/projects/github-com-jansimek-routing-homework-master)
# Routing Homework
### Getting started
To run automated tests execute the following command:
```mvn test```
To start the application run:
```mvn spring-boot:run```
Or use the provided wrapper script.
### Documentation
The service provides a single endpoint `/routing/AAA/BBB` where AAA and BBB
are three-letter country codes defined in ISO 3166-1 for which you can calculate a possible land route.
For example, calling `curl -X GET http://localhost:8080/routing/CZE/RUS` will return the following route:
```json
{
"route": ["CZE","POL","RUS"]
}
```
#### Api documentation
Automatically generated Swagger docs are available at:
* **Swagger UI:**
* http://localhost:8080/swagger-ui.html
* **JSON schema:**
* http://localhost:8080/v3/api-docs
<file_sep>/src/test/java/xyz/simek/routefinder/service/CountryServiceTest.java
package xyz.simek.routefinder.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.ExpectedCount;
import xyz.simek.routefinder.RoutingTest;
import xyz.simek.routefinder.dto.Country;
import xyz.simek.routefinder.exception.DataServiceException;
import java.io.IOException;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
@SpringBootTest
public class CountryServiceTest extends RoutingTest {
@Autowired
private CountryService countryService;
@Test
void testGetCountries() throws IOException {
var countries = countryService.getCountries();
server.verify();
assertEquals(5, countries.size());
var names = countries.stream().map(Country::getName).collect(Collectors.toList());
assertTrue(names.contains("CZE"));
assertTrue(names.contains("SVK"));
assertTrue(names.contains("AUT"));
assertTrue(names.contains("DEU"));
assertTrue(names.contains("ISL"));
var borders = countries.stream()
.filter(c -> c.getName().equals("CZE")).findFirst().get()
.getBorders();
assertEquals(4, borders.size());
assertTrue(borders.contains("AUT"));
assertTrue(borders.contains("DEU"));
assertTrue(borders.contains("PLN"));
assertTrue(borders.contains("SVK"));
}
@Test
void testCountriesFail() {
server.reset();
server.expect(ExpectedCount.once(), requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON));
DataServiceException ex = assertThrows(DataServiceException.class, () -> {
countryService.getCountries();
});
assertEquals("Could not get a list of countries", ex.getMessage());
}
@Test
void testCountriesEmpty() {
server.reset();
server.expect(ExpectedCount.once(), requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON).body(""));
DataServiceException ex = assertThrows(DataServiceException.class, () -> {
countryService.getCountries();
});
assertEquals("Received empty list of countries", ex.getMessage());
}
}
<file_sep>/src/test/java/xyz/simek/routefinder/controller/RoutingControllerTest.java
package xyz.simek.routefinder.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.servlet.MockMvc;
import xyz.simek.routefinder.RoutingTest;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class RoutingControllerTest extends RoutingTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetRoutingSingleOK() throws Exception {
this.mockMvc.perform(get("/routing/CZE/CZE")).andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"route\":[\"CZE\"]}"));
}
@Test
void testGetRoutingMultipleOK() throws Exception {
this.mockMvc.perform(get("/routing/SVK/DEU")).andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"route\":[\"SVK\",\"AUT\",\"DEU\"]}"));
}
@Test
void testGetRoutingInvalidCountry400() throws Exception {
this.mockMvc.perform(get("/routing/XYZ/CZE")).andDo(print())
.andExpect(status().isBadRequest())
.andExpect(status().reason(containsString("Country XYZ not found")));
}
@Test
void testGetRoutingInvalidRoute400() throws Exception {
this.mockMvc.perform(get("/routing/ISL/CZE")).andDo(print())
.andExpect(status().isBadRequest())
.andExpect(status().reason(containsString("Country ISL is isolated")));
}
@Test
void testGetRoutingServiceFail500() throws Exception {
server.reset();
server.expect(ExpectedCount.once(), requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON));
this.mockMvc.perform(get("/routing/ISL/CZE")).andDo(print())
.andExpect(status().isInternalServerError())
.andExpect(status().reason(containsString("Could not get a list of countries")));
}
}
<file_sep>/src/main/java/xyz/simek/routefinder/service/CountryService.java
package xyz.simek.routefinder.service;
import xyz.simek.routefinder.dto.Country;
import java.util.Set;
public interface CountryService {
/**
* Calls a third party service to obtain a list of countries
*
* @return all countries in the world and their borders
*/
Set<Country> getCountries();
}
<file_sep>/src/main/java/xyz/simek/routefinder/service/RouteServiceImpl.java
package xyz.simek.routefinder.service;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.shortestpath.BFSShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedPseudograph;
import org.springframework.stereotype.Service;
import xyz.simek.routefinder.dto.Country;
import xyz.simek.routefinder.dto.Route;
import xyz.simek.routefinder.exception.CountryNotFoundException;
import xyz.simek.routefinder.exception.RouteNotFoundException;
import java.util.Set;
import java.util.function.Function;
@Service
public class RouteServiceImpl implements RouteService {
private final CountryService countryService;
public RouteServiceImpl(CountryService countryService) {
this.countryService = countryService;
}
@Override
public Route findRoute(String origin, String destination) {
var countries = countryService.getCountries();
validateRoute(origin, destination, countries);
var graph = buildGraph(countries);
GraphPath<String, DefaultEdge> path = BFSShortestPath.findPathBetween(graph, origin, destination);
if (path == null) {
throw new RouteNotFoundException(String.format("Route from %s to %s not found", origin, destination));
}
return new Route(path.getVertexList());
}
private void validateRoute(String origin, String destination, Set<Country> countries) {
Function<String, Country> findCountryByName = (String countryCode) -> countries.stream()
.filter(country -> country.getName().equals(countryCode))
.findFirst()
.orElseThrow(() -> new CountryNotFoundException(countryCode));
var originCountry = findCountryByName.apply(origin);
var destinationCountry = findCountryByName.apply(destination);
if (!originCountry.equals(destinationCountry)) {
if (originCountry.isIsolated()) {
throw new RouteNotFoundException(String.format("Country %s is isolated", originCountry));
}
if (destinationCountry.isIsolated()) {
throw new RouteNotFoundException(String.format("Country %s is isolated", destinationCountry));
}
}
}
private DirectedPseudograph<String, DefaultEdge> buildGraph(Set<Country> countries) {
DirectedPseudograph<String, DefaultEdge> graph = new DirectedPseudograph<>(DefaultEdge.class);
countries.forEach(c -> {
graph.addVertex(c.getName());
c.getBorders().forEach(b -> {
graph.addVertex(b);
graph.addEdge(c.getName(), b);
});
});
return graph;
}
}
<file_sep>/src/test/java/xyz/simek/routefinder/RoutingTest.java
package xyz.simek.routefinder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import xyz.simek.routefinder.dto.Country;
import java.io.IOException;
import java.nio.file.Files;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
public abstract class RoutingTest {
protected static final Resource jsonFile = new ClassPathResource("countries.json");
protected static Country[] countries;
protected static String jsonCountries;
@Autowired
protected RestTemplate restTemplate;
protected MockRestServiceServer server;
@Value("${rest.endpoint.countries}")
protected String url;
@BeforeAll
public static void init() throws IOException {
jsonCountries = Files.readString(jsonFile.getFile().toPath());
countries = new ObjectMapper().readValue(jsonCountries, Country[].class);
}
@BeforeEach
public void initServer() {
server = MockRestServiceServer.bindTo(restTemplate).build();
server.expect(ExpectedCount.once(), requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(jsonCountries));
}
}
<file_sep>/src/main/resources/application.properties
rest.endpoint.countries=https://raw.githubusercontent.com/mledoze/countries/master/countries.json
server.error.include-message=always<file_sep>/src/main/java/xyz/simek/routefinder/service/CountryServiceImpl.java
package xyz.simek.routefinder.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import xyz.simek.routefinder.dto.Country;
import xyz.simek.routefinder.exception.DataServiceException;
import java.util.Set;
@Service
public class CountryServiceImpl implements CountryService {
private final String endpointUrl;
private final RestTemplate restTemplate;
public CountryServiceImpl(@Value("${rest.endpoint.countries}") String endpointUrl, RestTemplate restTemplate) {
this.endpointUrl = endpointUrl;
this.restTemplate = restTemplate;
}
@Override
public Set<Country> getCountries() {
try {
Country[] countries = restTemplate.getForObject(endpointUrl, Country[].class);
if (countries == null) {
throw new DataServiceException("Received empty list of countries");
}
return Set.of(countries);
} catch (HttpStatusCodeException ex) {
throw new DataServiceException("Could not get a list of countries", ex);
}
}
}
<file_sep>/src/main/java/xyz/simek/routefinder/service/RouteService.java
package xyz.simek.routefinder.service;
import xyz.simek.routefinder.dto.Route;
public interface RouteService {
/**
* Finds the shortest possible route from one country to another
*
* @param origin country
* @param destination country
* @return route with a list of border crossings to get from origin to destination
*/
Route findRoute(String origin, String destination);
}
|
f7f01853354224cf720d6da993e17345cdade5cc
|
[
"Markdown",
"Java",
"INI"
] | 9
|
Markdown
|
JanSimek/routing-homework
|
28599b75fd1cf403fd2f0b7b19b0dc344e5590a0
|
7cdf58f4ae2f8426d367222950a0abb2dc1cd3fb
|
refs/heads/main
|
<repo_name>smartprogrammer2/DictionaryOffline<file_sep>/components/Header.js
import * as React from 'react';
import {Component} from 'react';
import {Text, View, StyleSheet} from 'react-native';
class Header extends React.Component {
render() {
return (
<View>
<Text style={styles.textStyle}>
{this.props.text}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
textStyle: {
paddingLeft: 70,
backgroundColor: "blue",
fontWeight: 'bold',
fontSize: 30,
borderColor: "cyan",
borderWidth: 4,
borderRadius: 40
}
})
export default Header;<file_sep>/App.js
//importing components from respective libraries
import * as React from 'react';
import {Component} from 'react';
import {View, TextInput, Text, TouchableOpacity, StyleSheet} from 'react-native';
import Header from './components/Header';
import dictionary from './database';
export default class App extends React.Component {
constructor() {
super();
this.state = {
word: '',
definition: '',
lexicalCategory: '',
isSearchPressed: false
}
}
//creating the function to get the word by using the API link
getWord =(text)=> {
var text = text.toLowerCase();
try {
var word = dictionary[text]["word"];
var lexicalCatagory = dictionary[text]["lexicalCategory"]
var definition = dictionary[text]["definition"]
this.setState({
"word": word,
"lexicalCategory": lexicalCatagory,
"definition": definition
})
} catch(error) {
alert("sorry the word you typed is not available, please try again")
this.setState({
'text': '',
isSearchPressed: false
})
}
}
render() {
return (
<View>
<Header text = "DICTIONARY"/>
<View style = {{fontSize: 20}}>
<Text>
{this.state.isSearchPressed && this.state.word == "Loading"
?this.state.word
:""
}
</Text>
<Text>
{this.state.word !== "Loading"}
</Text>
</View>
<View>
</View>
<TextInput style={styles.inputBox} onChangeText={text => {
this.setState({
text: text,
isSearchPressed: false,
word: "Loading...",
lexicalCatagory: '',
examples: [],
defination: ""
});
}}
value={this.state.text}
/>
<TouchableOpacity style = {styles.button}onPress={()=> {
this.setState({isSearchPressed: true})
this.getWord(this.state.text)
}}>
<Text>Search</Text>
</TouchableOpacity>
<View>
<Text style={{color: "green", fontWeight: 'bold', fontSize: 20}}>
Word: {" "}
</Text>
<Text style={{fontSize: 18, fontWeight: 'bold'}}>
{this.state.word}
</Text>
</View>
<View>
<Text style={{color: "aqua", fontWeight: 'bold', fontSize: 20}}>
Type: {" "}
</Text>
<Text style={{fontSize: 18, fontWeight: 'bold'}}>
{this.state.lexicalCategory}
</Text>
</View>
<View>
<Text style={{color: "red", fontWeight: 'bold', fontSize: 20}}>
Definition: {" "}
</Text>
<Text style={{fontSize: 18, fontWeight: 'bold'}}>
{this.state.definition}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
totalStyle: {
},
button : {
borderWidth: 3,
marginTop: 30,
width: 100,
height: 40,
marginLeft: 100,
justifyContent: "center",
alignItems: "center",
backgroundColor: "red",
borderRadius: 30
},
container: {
flex: 1
},
InputBoxContainer: {
flex: 0.3,
alignItems: "center",
justifyContent: "center"
},
inputBox: {
width: "80%",
alignSelf: 'center',
alignItems: "center",
justifyContent: "center",
height: 40,
borderWidth: 4,
borderRadius: 50,
marginTop: 40
}
})
|
c54e19ad78bd5b20a36649e5c169a45e24168ae6
|
[
"JavaScript"
] | 2
|
JavaScript
|
smartprogrammer2/DictionaryOffline
|
ca007aa7ebd77a8fa8d8db03c241f5b6f3c0a02d
|
a97221d0e944acd2120333700e4af3ea52fa50ff
|
refs/heads/master
|
<file_sep>$(function () {
var dateArrays = [
"2015.2.3", "2015.2.4", "2015.2.5", "2015.2.6", "2015.2.7", "2015.2.8",
"2015.2.9", "2015.2.10", "2015.2.11", "2015.2.12", "2015.2.13", "2015.2.14"
];
// console.log(dateArrays)
datePicker(dateArrays);
function datePicker(dateArrays) {
var textWidth = 100;
var itemsNum = dateArrays.length;
var svg = d3.select("#timePicker").select("svg")
.style("width", function () {
return textWidth * itemsNum + "px";
});
d3.select("#timeLine").attr("width", function () {
return textWidth * itemsNum + "px";
});
var timeLineTextGroup = svg.append("g");
var timeLineRect = svg.append("g");
timeLineTextGroup.selectAll("text")
.data(dateArrays)
.enter()
.append("text")
.attr({
"x": function (d, i) {
return textWidth * i + "px";
},
"y": "60px",
})
.style({
"font-size": "10px",
"stroke": "white"
})
.text(function (d, i) {
return d;
});
timeLineRect.selectAll("rect")
.data(dateArrays)
.enter()
.append("rect")
.attr({
"x": function (d, i) {
return textWidth * i + "px";
},
"y": "10px",
"width": "5px",
"height": "40px",
"transform": "translate(20,0)",
"value": function (d, i) {
return d;
}
})
.style({
"fill": "#ff942b",
"cursor": "pointer"
})
.on({
"mouseover": function (d, i) {
// console.log(d3.select(this).attr("x"));
}
});
var drag = d3.behavior.drag()
.origin(function () {
return { x: d3.select(this).attr("x"), y: d3.select(this).attr("y") };
})
.on("dragstart", function () {
})
.on("drag", function () {
var x = d3.event.x;
if (x < 0 || x > 990)
return;
d3.select(this).attr("x", x);
})
.on("dragend", function () {
var start = parseFloat(d3.select("#startSlider").attr("x"));
var end = parseFloat(d3.select("#endSlider").attr("x"));
var max = start > end ? start : end;
var min = start < end ? start : end;
//选择的日期都会被保存在selectedDate里面
var selectedDate = [];
timeLineRect.selectAll("rect").each(function () {
var x = parseFloat(d3.select(this).attr("x").split("p")[0]) + 20;
if (x >= min && x <= max) {
selectedDate.push(d3.select(this).attr("value"));
}
});
console.log(selectedDate);
});
d3.select("#startSlider").call(drag);
d3.select("#endSlider").call(drag);
}
});<file_sep># date_brush
svg实现刷选日期
|
cb18be01ed576c30db57772c60943cef9d4e56ec
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
yuanzhaokang/date_brush
|
065e2c929107a09e09ce13be0bdb8a71d916aea0
|
a0e3d41c2ac6bd4355e099fa60d8c2db9b158ee3
|
refs/heads/master
|
<repo_name>webplantmedia/pinterest-rss-widget<file_sep>/pinterest-rss-widget.php
<?php
/*
Plugin Name: Pinterest RSS Widget
Plugin URI: http://www.bkmacdaddy.com/pinterest-rss-widget-a-wordpress-plugin-to-display-your-latest-pins/
Description: Display up to 25 of your latest Pinterest Pins in your sidebar. You are welcome to express your gratitude for this plugin by donating via <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SXTEL7YLUSFFC" target="_blank"><strong>PayPal</strong></a>
Author: bkmacdaddy designs
Version: 2.2.5
Author URI: http://bkmacdaddy.com/
/* License
Pinterest RSS Widget
Copyright (C) 2012 <NAME> (brian at bkmacdaddy dot com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
add_action('wp_enqueue_scripts', 'add_pinterest_rss_css');
function add_pinterest_rss_css() {
$pinterest_rss_myStyleUrl = plugins_url('style.css', __FILE__); // Respects SSL, Style.css is relative to the current file
$pinterest_rss_myStyleFile = WP_PLUGIN_DIR . '/pinterest-rss-widget/style.css';
$pinterest_rss_nailThumb = plugins_url('jquery.nailthumb.1.0.min.js', __FILE__);
if ( file_exists($pinterest_rss_myStyleFile) ) {
wp_register_style('pinterestRSScss', $pinterest_rss_myStyleUrl);
wp_enqueue_style( 'pinterestRSScss');
wp_enqueue_script(
'pinterestRSSjs',
$pinterest_rss_nailThumb,
array( 'jquery' )
);
}
}
function get_pins_feed_list($username, $boardname, $maxfeeds=25, $divname='standard', $printtext=NULL, $target='samewindow', $useenclosures='yes', $thumbwidth='150', $thumbheight='150', $showfollow='large') {
// This is the main function of the plugin. It is used by the widget and can also be called from anywhere in your theme. See the readme file for example.
// Get Pinterest Feed(s)
include_once(ABSPATH . WPINC . '/feed.php');
if( empty($boardname) ){
$pinsfeed = 'https://pinterest.com/'.$username.'/feed.rss';
}
else $pinsfeed = 'https://pinterest.com/'.$username.'/'.$boardname.'/rss';
// Get a SimplePie feed object from the Pinterest feed source
$rss = fetch_feed($pinsfeed);
if($rss instanceof WP_Error) return '';
$rss->set_timeout(60);
// Figure out how many total items there are.
$maxitems = $rss->get_item_quantity((int)$maxfeeds);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0,$maxitems);
$content = '';
$content .= '<ul class="pins-feed-list">';
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) :
$content .= '<li class="pins-feed-item" style="width:'. $thumbwidth .'px;">';
$content .= '<div class="pins-feed-'.$divname.'">';
$content .= '<a href="'.$item->get_permalink().'"';
if ($target == 'newwindow') { $content .= ' target="_BLANK" '; };
$content .= 'title="'.$item->get_title().' - Pinned on '.$item->get_date('M d, Y').'">';
if ($thumb = $item->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail') ) {
$thumb = $thumb[0]['attribs']['']['url'];
$content .= '<img src="'.$thumb.'"';
$content .= ' alt="'.$item->get_title().'"/>';
} else {
preg_match('/src="([^"]*)"/', $item->get_content(), $matches);
$src = $matches[1];
if ($matches) {
$content .= '<img src="'.$src.'"';
$content .= ' alt="'.$item->get_title().'"/>';
} else {
$content .= "thumbnail not available";
}
}
if ($printtext) {
if ($printtext != 'no') {
$content .= "<div class='imgtitle'>".$item->get_title()."</div>";
}
}
$content .= '</a>';
$content .= '</div>';
$content .= '</li>';
endforeach;
$content .= '<div class="pinsClear"></div>';
$content .= '</ul>';
$content .= '<script type="text/javascript">';
$content .= 'jQuery(document).ready(function() {';
$content .= "jQuery('.pins-feed-item img').nailthumb({width:".$thumbwidth.",height:".$thumbheight."})";
$content .= '}); </script>';
$pinterest_followButton = plugins_url('follow-on-pinterest-button.png', __FILE__);
if ($showfollow == 'large') {
$content .= '<a href="http://pinterest.com/'. $username .'/" id="pins-feed-follow" target="_blank" class="followLarge" title="Follow Me on Pinterest">';
$content .= '<img src="http://passets-cdn.pinterest.com/images/follow-on-pinterest-button.png" width="156" height="26" alt="Follow Me on Pinterest" border="0" />';
$content .= '</a>';
} elseif ($showfollow == 'medium') {
$content .= '<a href="http://pinterest.com/'. $username.'/" id="pins-feed-follow" target="_blank" class="followMed" title="Follow Me on Pinterest">';
$content .= '<img src="http://passets-cdn.pinterest.com/images/pinterest-button.png" width="78" height="26" alt="Follow Me on Pinterest" border="0" />';
$content .= '</a>';
} elseif ($showfollow == 'small') {
$content .= '<a href="http://pinterest.com/'. $username .'/" id="pins-feed-follow" target="_blank" class="followSmall" title="Follow Me on Pinterest">';
$content .= '<img src="http://passets-cdn.pinterest.com/images/big-p-button.png" width="61" height="61" alt="Follow Me on Pinterest" border="0" />';
$content .= '</a>';
} elseif ($showfollow == 'tiny') {
$content .= '<a href="http://pinterest.com/'. $username .'/" id="pins-feed-follow" target="_blank" class="followTiny" title="Follow Me on Pinterest">';
$content .= '<img src="http://passets-cdn.pinterest.com/images/small-p-button.png" width="16" height="16" alt="Follow Me on Pinterest" border="0" />';
$content .= '</a>';
} elseif ($showfollow == 'none') {}
return $content;
}
function prw_shortcode( $atts ) {
extract( shortcode_atts( array(
'username' => '',
'boardname' => '',
'maxfeeds' => 25,
'divname' => 'standard',
'printtext' => NULL,
'target' => 'samewindow',
'useenclosures' => 'yes',
'thumbwidth' => 150,
'thumbheight' => 150,
'showfollow' => 'large'
), $atts
)
);
// this will display the latest pins
$prwsc = get_pins_feed_list($username, $boardname, $maxfeeds, $divname, $printtext, $target, $useenclosures, $thumbwidth, $thumbheight, $showfollow);
return $prwsc;
}
add_shortcode('prw', 'prw_shortcode');
class Pinterest_RSS_Widget extends WP_Widget {
function Pinterest_RSS_Widget() {
$widget_ops = array('classname' => 'pinterest_rss_widget', 'description' => 'A widget to display latest Pinterest Pins via RSS feed' );
$this->WP_Widget('pinterest_rss_widget', 'Pinterest RSS Widget', $widget_ops);
}
function widget($args, $instance) {
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
$user_name = empty($instance['user_name']) ? ' ' : $instance['user_name'];
$board_name = empty($instance['board_name']) ? '' : $instance['board_name'];
$maxnumber = empty($instance['maxnumber']) ? ' ' : $instance['maxnumber'];
$thumb_height = empty($instance['thumb_height']) ? ' ' : $instance['thumb_height'];
$thumb_width = empty($instance['thumb_width']) ? ' ' : $instance['thumb_width'];
$target = empty($instance['target']) ? ' ' : $instance['target'];
$displaytitle = empty($instance['displaytitle']) ? ' ' : $instance['displaytitle'];
$useenclosures = empty($instance['useenclosures']) ? ' ' : $instance['useenclosures'];
$showfollow = empty($instance['showfollow']) ? ' ' : $instance['showfollow'];
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
if ( empty( $board_name ) ) { $board_name = ''; };
if ( empty( $target ) ) { $target = 'samewindow'; };
if ( empty( $displaytitle ) ) { $displaytitle = 'no'; };
if ( empty( $useenclosures ) ) { $useenclosures = 'yes'; };
if ( empty( $thumb_width ) ) { $thumb_width = '150'; };
if ( empty( $thumb_height ) ) { $thumb_height = '150'; };
if ( empty( $showfollow ) ) { $showfollow = 'none'; };
if ( !empty( $user_name ) ) {
echo get_pins_feed_list($user_name, $board_name, $maxnumber, 'small', $displaytitle, $target, $useenclosures, $thumb_width, $thumb_height, $showfollow); ?>
<div style="clear:both;"></div>
<?php }
echo $after_widget;
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['user_name'] = strip_tags($new_instance['user_name']);
$instance['board_name'] = strip_tags($new_instance['board_name']);
$instance['maxnumber'] = strip_tags($new_instance['maxnumber']);
$instance['thumb_height'] = strip_tags($new_instance['thumb_height']);
$instance['thumb_width'] = strip_tags($new_instance['thumb_width']);
$instance['target'] = strip_tags($new_instance['target']);
$instance['displaytitle'] = strip_tags($new_instance['displaytitle']);
$instance['useenclosures'] = strip_tags($new_instance['useenclosures']);
$instance['showfollow'] = strip_tags($new_instance['showfollow']);
return $instance;
}
function form($instance) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'user_name' => '', 'board_name' => '', 'maxnumber' => '', 'thumb_height' => '', 'thumb_width' => '', 'target' => '', 'displaytitle' => '', 'useenclosures' => '', 'showfollow' => '') );
$title = strip_tags($instance['title']);
$user_name = strip_tags($instance['user_name']);
$board_name = strip_tags($instance['board_name']);
$maxnumber = strip_tags($instance['maxnumber']);
$thumb_height = strip_tags($instance['thumb_height']);
$thumb_width = strip_tags($instance['thumb_width']);
$target = strip_tags($instance['target']);
$displaytitle = strip_tags($instance['displaytitle']);
$useenclosures = strip_tags($instance['useenclosures']);
$showfollow = strip_tags($instance['showfollow']);
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <br /><input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('user_name__title'); ?>">Pinterest Username: <br /><input class="widefat" id="<?php echo $this->get_field_id('user_name'); ?>" name="<?php echo $this->get_field_name('user_name'); ?>" type="text" value="<?php echo attribute_escape($user_name); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('user_name__board'); ?>">Username Board: (Optional) <br /><input class="widefat" id="<?php echo $this->get_field_id('board_name'); ?>" name="<?php echo $this->get_field_name('board_name'); ?>" type="text" value="<?php echo attribute_escape($board_name); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('maxnumber'); ?>">Max number of pins to display: <br /><input class="widefat" id="<?php echo $this->get_field_id('maxnumber'); ?>" name="<?php echo $this->get_field_name('maxnumber'); ?>" type="text" value="<?php echo attribute_escape($maxnumber); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('thumb_height'); ?>">Thumbnail Height in pixels<br /><em>(defaults to 150):</em><br /><input class="widefat" id="<?php echo $this->get_field_id('thumb_height'); ?>" name="<?php echo $this->get_field_name('thumb_height'); ?>" type="text" value="<?php echo attribute_escape($thumb_height); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('thumb_width'); ?>">Thumbnail Width in pixels<br /><em>(defaults to 150):</em><br /><input class="widefat" id="<?php echo $this->get_field_id('thumb_width'); ?>" name="<?php echo $this->get_field_name('thumb_width'); ?>" type="text" value="<?php echo attribute_escape($thumb_width); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('displaytitle'); ?>">Display title below pins? <select id="<?php echo $this->get_field_id('displaytitle'); ?>" name="<?php echo $this->get_field_name('displaytitle'); ?>">
<?php
echo '<option ';
if ( $instance['displaytitle'] == 'yes' ) { echo 'selected '; }
echo 'value="yes">';
echo 'Yes</option>';
echo '<option ';
if ( $instance['displaytitle'] == 'no' ) { echo 'selected '; }
echo 'value="no">';
echo 'No</option>'; ?>
</select></label></p>
<p><label for="<?php echo $this->get_field_id('target'); ?>">Where to open the links: <br /><select id="<?php echo $this->get_field_id('target'); ?>" name="<?php echo $this->get_field_name('target'); ?>">
<?php
echo '<option ';
if ( $instance['target'] == 'samewindow' ) { echo 'selected '; }
echo 'value="samewindow">';
echo 'Same Window</option>';
echo '<option ';
if ( $instance['target'] == 'newwindow' ) { echo 'selected '; }
echo 'value="newwindow">';
echo 'New Window</option>'; ?>
</select></label></p>
<p><label for="<?php echo $this->get_field_id('showfollow'); ?>">Show "Follow Me On Pinterest" button? <br /><select id="<?php echo $this->get_field_id('showfollow'); ?>" name="<?php echo $this->get_field_name('showfollow'); ?>">
<?php
echo '<option ';
if ( $instance['showfollow'] == 'large' ) { echo 'selected '; }
echo 'value="large">';
echo 'Large (156x26) </option>';
echo '<option ';
if ( $instance['showfollow'] == 'medium' ) { echo 'selected '; }
echo 'value="medium">';
echo 'Medium (78x26) </option>';
echo '<option ';
if ( $instance['showfollow'] == 'small' ) { echo 'selected '; }
echo 'value="small">';
echo 'Small (61x61) </option>';
echo '<option ';
if ( $instance['showfollow'] == 'tiny' ) { echo 'selected '; }
echo 'value="tiny">';
echo 'Tiny (16x16) </option>';
echo '<option ';
if ( $instance['showfollow'] == 'none' ) { echo 'selected '; }
echo 'value="none">';
echo 'None </option>';
?>
</select></label></p>
<?php
}
}
// register_widget('Pinterest_RSS_Widget');
add_action( 'widgets_init', create_function('', 'return register_widget("Pinterest_RSS_Widget");') );
add_filter( 'wp_feed_cache_transient_lifetime', create_function('$a', 'return 600;') );
?><file_sep>/readme.txt
=== Pinterest RSS Widget ===
Contributors: bkmacdaddy, AidaofNubia, thewebprincess, leepettijohn
Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SXTEL7YLUSFFC
Tags: Pinterest, rss, feed, widget
Requires at least: 2.8.4
Tested up to: 4.1.1
Stable tag: trunk
A widget to display thumbnails and titles of the latest Pinterest Pins from a specific user via their Pinterest RSS feed
== Description ==
This plugin allows you to place a widget on your sidebar that fetches the most recent contents of a Pinterest user's RSS feed and displays the corresponding thumbnail images. You can choose whether to show the description below the image, and you can set the height and width of the thumbnails to fit your theme. You also have the option of showing 4 different sizes of the official "Follow Me On Pinterest" button below the list of your pins.
You can also use this plugin from your theme templates, to display images lists anywhere else on your blog and you can easily give them a fixed size or a maximum size with CSS styling.
Starting with plugin version 1.3, you can also add a list of thumbnails of your Pins to a post or a page in the editor using the shortcode [prw username="Your Pinterest Username"]. (See FAQs for instructions).
Version 1.4 adds the capability of showing pins from a specific board in the widget or shortcode, rather than just all of the latest pins from a specific user. (See FAQs for instructions).
Note: This plugin is heavily based on the Image Feed Widget plugin created by <NAME> (http://wordpress.org/extend/plugins/image-feed-widget/). As of version 2.0 it also utilizes the jQuery NailThumb script for image resizing (http://www.garralab.com/nailthumb.php) and no longer utilizes the timthumb.php script.
== Installation ==
1. Upload the folder `pinterest-rss-widget` and its contents to the `/wp-content/plugins/` directory or use the wordpress plugin installer
2. Activate the plugin through the 'Plugins' menu in WordPress
3. A new "Pinterest RSS Widget" will be available under Appearance > Widgets, where you can add it to your sidebar and edit all settings of the plugin.
== Frequently Asked Questions ==
= How do I use the shortcode in the post or page editor? =
While editing the post or page that you want to add your Pins to, enter the shortcode [prw username="Your Pinterest Username"]. At the very minimum you have to include the username parameter, substituting "Your Pinterest Username" with your actual Pinterest username. The rest of the parameters are the same as listed below in the template tags explanation, and the defaults are also the same. Here's an example:
`[prw username="bkmacdaddy" boardname="design-inspiration" maxfeeds="10" divname="myList" printtext="0" target="newwindow" useenclosures="yes" thumbwidth="100" thumbheight="100" showfollow="medium"]`
The above example will show the 10 latest Pins from bkmacdaddy's Design Inspiration board, in a div class titled "pins-feed-myList". Each thumbnail will be 100 x 100 pixels with no description below them. When clicked on, the Pin will open in a new tab/window, and the Follow Me On Pinterest button at the bottom will be the medium sized one.
If you leave out any of the parameters they will revert to the defaults listed below.
= How do I use the plugin in my theme? =
Anywhere in your theme templates, you can display the list of latest Pins thumbnails by placing the following code where you want them to appear:
`<?php get_pins_feed_list($username, $boardname, $maxfeeds, $divname, $printtext, $target, $useenclosures, $thumbwidth, $thumbheight, $showfollow); ?>`
Where:
* **username** is the Pinterest username you wish to display Pins from (mandatory)
* **boardname** is the slug (URL) of a specific board. This must be the actual part of the URL that designates the board (i.e. http://pinterest.com/bkmacdaddy/**design-inspiration**/ - the portion in bold) (optional)
* **maxfeeds** is the maximum number of Pins to display (optional, default = 25)
* **divname** is a name suffix for the list class. "myList" will become "pins-feed-myList" (optional)
* **printtext** must be 1 if you want the first few words of the Pin description to be printed below the thumbnail (optional)
* **target** is "samewindow" or "newwindow", depending on where you want links to open (optional, default = samewindow)
* **useenclosures** is "yes" or "no" (optional, default = yes). Use this if you don't want to use the <enclosure> tag in the feed and force the script to find an image link in the feed item description.
* **thumbwidth** is a number that will set the width in pixels of the Pin's thumbnail (optional, default = 150)
* **thumbheight** is a number that will set the height in pixels of the Pin's thumbnail (optional, default = 150)
* **showfollow** is "large", "medium", "small", "tiny" or "none" (optional, default = none). Use this if you want to show the "Follow Me On Pinterest" button below the thumbnails. Select the size that best fits the space allowed ("large" is 156x26, "medium" is 78x26, "small" is the square 61x61 logo, and "tiny" is the 16x16 logo.)
Example:
`<?php get_pins_feed_list('bkmacdaddy', 'design-inspiration', 10, 'myList', 1, 'newwindow', 'yes', 125, 125, 'large'); ?>`
== Screenshots ==
1. The widget settings
2. Widget on the front end with 9 Pins and titles displaying
3. Choose one of four buttons (or none) to display beneath the list of Pins
== Changelog ==
= 2.2.5 =
* Fixed issue with new Pinterest https URL
= 2.2.4 =
* Added fix for "Call to undefined method WP_Error::set_timeout()"
= 2.2.3 =
* Removed extraneous line left in accidentally in 2.2.2
= 2.2.2 =
* Removed problematic deregistering of WordPress jQuery
* Plugin now uses built-in WordPress jQuery
= 2.2.1 =
* Fixed problem with wrong version in repository
= 2.2 =
* Fixed code to work with latest version of WordPress (3.5)
= 2.01 =
* Added timeout for RSS feed retrieval to avoid Call to undefined method WP_Error::get_item_quantity()
= 2.0 =
* Removed timthumb.php and replaced jQuery NailThumb for image resizing
= 1.5 =
* Updated to latest version of timthumb.php
= 1.4 =
* Added the capability to show pins from a specific board
= 1.3.2 =
* Recoded to remove ob_ functions that were not working on certain server configurations
= 1.3.1 =
* Repaired error in shortcode
= 1.3 =
* Added shortcode for use in posts and pages
= 1.2.5 =
* Added ability to choose 4 different sizes of "Follow Me On Pinterest" buttons
= 1.2.4 =
* Changed location of cache folder for timthumb.php script to /wp-content/uploads/prw_tmp/
* Changed URL of plugin site to http://www.bkmacdaddy.com/pinterest-rss-widget-wordpress-plugin-to-display-your-latest-pins
* Added donation link
= 1.2.3 =
* Added FAQS based on some troubleshooting
* Added 2 contributors for their testing assistance and suggestions
* Tweaked instructions on the widget settings
= 1.2.2 =
* Fixed directory path errors on WP Multisite
= 1.2.1 =
* Corrected "Follow Me On Pinterest" button image errors
= 1.2 =
* Added "Follow Me On Pinterest" button
= 1.1 =
* Improved CSS styles for better universal use
= 1.0 =
* First version
== Upgrade Notice ==
= 1.4 =
|
a5ed9e8379771203d876da89947acaa8f49ed954
|
[
"Text",
"PHP"
] | 2
|
PHP
|
webplantmedia/pinterest-rss-widget
|
2f2e26a2b35752a8752d66d163416cce47d38248
|
c942c8633d2f5ed5bcfe278bc81f7d9efa660a5d
|
refs/heads/master
|
<file_sep>name 'magento'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
license 'GPLv3'
description 'Installs/Configures server software for Magento app'
long_description 'Installs/Configures server software for Magento app'
version '0.1.20'
depends 'vhost'
depends 'php_fpm'
depends 'mysql', '=5.6.1'
depends 'database', '=3.1.0'
depends 'logrotate'
depends 'ecomdev_common'
depends 'redisio', '1.7.1'
depends 'openssl'
depends 'composer'
depends 'n98-magerun'
<file_sep>namespace 'magento', precedence: default do
namespace 'varnish', precedence: default do
port 80
backend node1: { ip: '127.0.0.1', port: '8080', weight: '1' },
admin: 'node1'
probe '/status'
probe_options interval: '30s',
timeout: '0.3s',
window: '8',
threshold: '3',
initial: '3',
expected_response: '200'
balanced_backend_options first_byte_timeout: '300s',
connect_timeout: '5s',
between_bytes_timeout: '2s'
non_balanced_backend_options first_byte_timeout: '6000s',
connect_timeout: '1000s',
between_bytes_timeout: '2s'
balancer [:node1]
device_detect_file 'https://raw.githubusercontent.com/willemk/varnish-mobiletranslate/master/mobile_detect.vcl'
segment_cookie 'segment_checksum'
admin_path 'admin'
ip_local Array.new
ip_admin Array.new
ip_refresh Array.new
hide_varnish_header Array.new
end
end<file_sep>require 'chef/mixin/deep_merge'
application_options = node.deep_fetch!('magento', 'default', 'application').to_hash
Chef::Mixin::DeepMerge.deep_merge!(
{
name: 'magento',
main_domain: 'magento.dev',
directory: '/vagrant'
},
application_options
)
unless node.deep_fetch('magento', 'application').nil?
Chef::Mixin::DeepMerge.deep_merge!(node.deep_fetch('magento', 'application').to_hash, application_options)
end
namespace 'magento' do
application application_options
end<file_sep>actions :create, :delete
attribute :name, :kind_of => [String, Symbol], :name_attribute => true # Name of the database
attribute :user, :kind_of => [String, Symbol], :default => :magento_default # Username that will be created for a database
attribute :password, :kind_of => [String, Symbol], :default => :magento_default # Password for database user
attribute :host, :kind_of => [String, Symbol], :default => :magento_default # Password for database user
attribute :create_test, :kind_of => [TrueClass, FalseClass, Symbol], :default => :magento_default # Flag for creation of test database
attribute :encoding, :kind_of => [String, Symbol], :default => :magento_default # Password for database user
attribute :collation, :kind_of => [String, Symbol], :default => :magento_default # Password for database user
attribute :connection_settings, :kind_of => [Hash, Symbol], :default => :magento_default # User for php process, by default will take value from magento[database][default]
def initialize(*args)
super
@action = :create
end<file_sep>::Chef::Recipe.send(:include, Opscode::OpenSSL::Password)<file_sep>source 'https://rubygems.org'
gem 'rake'
gem 'berkshelf', '~> 3.1.3'
gem 'chef-sugar'
gem 'chefspec', '= 4.1.0'
gem 'chef', '= 11.16.4'
gem 'ecomdev-chefspec', '~> 0.1.9'<file_sep># database::mysql recipe resources
runner [:mysql_database, :mysql_database_user]
matcher :mysql_database, :create
matcher :mysql_database, :drop
matcher :mysql_database_user, :create
matcher :mysql_database_user, :grant
matcher :mysql_database_user, :drop
<file_sep>include_recipe 'magento::default'
require 'chef/mixin/deep_merge'
directives = {
'opcache.memory_consumption' => 128,
'opcache.interned_strings_buffer' => 8,
'opcache.max_accelerated_files' => 4000,
'opcache.revalidate_freq' => 60,
'opcache.fast_shutdown' => 1,
'opcache.enable_cli' => 1
}
current_directives = node.deep_fetch!('php', 'directives').to_hash
Chef::Mixin::DeepMerge.deep_merge!(current_directives, directives)
node.default[:php][:directives] = directives
node.default[:php][:major_version] = '5.4'
if debian?
package 'libssh2-1'
package 'libssh2-1-dev'
elsif rhel?
package 'libssh2'
package 'libssh2-devel'
end
include_recipe 'php_fpm::default'
unless constraint('~>5.5').satisfied_by?(node[:php][:major_version])
php_pear 'zendopcache' do
preferred_state 'beta'
zend_extensions ['opcache.so']
end
end
database_options = node[:magento][:default][:database].to_hash
Chef::Mixin::DeepMerge.deep_merge!(node[:magento][:application][:database_options].to_hash, database_options)
node.default[:magento][:application][:database_options] = database_options
magento_application node[:magento][:application][:name] do
node[:magento][:application].to_hash.each_pair do |key, value|
send(key.to_sym, value)
end
end
<file_sep># Magento recipe resources
runner :magento_database
matcher :magento_database, :create
matcher :magento_database, :delete
runner :magento_application
matcher :magento_application, :create
matcher :magento_application, :delete
runner :magento_user
matcher :magento_user, :create
matcher :magento_user, :delete
<file_sep>runner :php_pear
matcher :php_pear, :install<file_sep>include_recipe 'n98-magerun::default'
package 'htop'
package 'vim'<file_sep>
# Support whyrun
def whyrun_supported?
true
end
action :create do
run_context.include_recipe('magento::default')
options = resource_options
user options[:name] do
if node.recipe?('vhost::nginx') && node[:nginx][:user] == options[:name]
action :modify
uid options[:uid]
else
action :create
uid options[:uid]
gid options[:gid]
system true
shell "/bin/bash"
end
end
end
action :delete do
run_context.include_recipe('magento::default')
user new_resource.name do
action :remove
end
end
private
def resource_options
options = new_resource.dump_attribute_values(node[:magento][:default][:user], :magento_default)
if options[:uid] == :system_default
options[:uid] = nil
end
if options[:gid] == :system_default
options[:gid] = nil
if node.recipe?('vhost::nginx')
options[:gid] = node[:nginx][:group]
end
end
options
end<file_sep>require 'spec_helper'
describe 'magento::application' do
before (:each) { allow_recipe('magento::default') }
let(:chef_run) do
chef_run_proxy.instance.converge(described_recipe)
end
def node(&block)
chef_run_proxy.before(:converge) do |runner|
if block.arity == 1
block.call(runner.node)
end
end
end
it 'should include magento::default recipe' do
expect(chef_run).to include_recipe('magento::default')
end
it 'sets default php version to 5.4' do
expect(chef_run.node[:php][:major_version]).to eq('5.4')
end
it 'installs php opcache extension zendopcache ' do
expect(chef_run).to install_php_pear('zendopcache').with(
preferred_state: 'beta',
zend_extensions: ['opcache.so']
)
end
it 'does not install php_opcode cache if php version is 5.5' do
node do |n|
n.set[:php][:major_version] = '5.5'
end
expect(chef_run).not_to install_php_pear('zendopcache')
end
it 'sets directives for php opcode cache' do
expect(chef_run.node[:php][:directives]).to include(
'opcache.memory_consumption' => 128,
'opcache.interned_strings_buffer' => 8,
'opcache.max_accelerated_files' => 4000,
'opcache.revalidate_freq' => 60,
'opcache.fast_shutdown' => 1,
'opcache.enable_cli' => 1
)
end
it 'sets default database configuration options from magento/default/database attributes' do
expect(chef_run.node.default[:magento][:application][:database_options]).to eq(chef_run.node[:magento][:default][:database])
end
it 'makes possible to override default connection settings' do
node do |n|
n.set['magento']['application']['database_options']['connection_settings']['user'] = 'budy'
end
magento_app = chef_run.magento_application(chef_run.node[:magento][:application][:name])
expect(magento_app.database_options['connection_settings']).to include('user' => 'budy',
'host' => 'localhost')
end
it 'creates a magento application with specified attributes' do
expect(chef_run).to create_magento_application('magento')
.with(
main_domain: 'magento.dev',
user: :system_default,
group: :system_default,
handler: 'index.php'
)
end
context 'on Centos 6.5 it' do
before(:each) do
chef_run_proxy.options(:platform => 'centos', :version => '6.5')
end
it 'installs libssh2' do
expect(chef_run).to install_package 'libssh2'
end
it 'installs libssh2-devel' do
expect(chef_run).to install_package 'libssh2-devel'
end
end
context 'on Ubuntu 13.04 it' do
before(:each) do
chef_run_proxy.options(:platform => 'ubuntu', :version => '13.04')
end
it 'installs libssh2-1' do
expect(chef_run).to install_package 'libssh2-1'
end
it 'installs libssh2-1-devel' do
expect(chef_run).to install_package 'libssh2-1-dev'
end
end
end<file_sep>namespace 'magento', 'default', precedence: default do
namespace 'database', precedence: default do
encoding 'utf8'
user :database_name
password :<PASSWORD>
host '%'
create_test false
namespace 'connection_settings', precedence: default do
host 'localhost'
user 'root'
end
end
namespace 'user', precedence: default do
uid :system_default
gid :system_default
end
namespace 'application', precedence: default do
user :system_default
group :system_default
uid :system_default
status_path '/status'
status_ips Array.new
handler 'index.php'
time_limit '60'
memory_limit '256M'
php_extensions Hash.new
cache_static '30d'
http_port '80'
https_port '443'
log_dir 'var/log'
vhost 'nginx'
deny_paths %w(/app/ /includes/ /lib/ /media/downloadable/ /pkginfo/ /report/config.xml /var/)
domain_map Hash.new
database_options Hash.new
buffers '16 16k'
buffer_size '32k'
composer false
composer_path :system_default
magento_type '1'
namespace 'php_fpm_options', precedence: default do
socket true
socket_user :system_default # Taken from nginx
socket_group :system_default # Taken from nginx
request_terminate_timeout :system_default # Taken from time limit
namespace 'php_admin_flag', precedence: default do
log_errors 'on'
display_errors 'off'
display_startup_errors 'off'
end
namespace 'php_admin_value', precedence: default do
error_log :system_default
error_reporting 'E_ALL'
memory_limit :system_default
max_execution_time :system_default
end
end
end
end<file_sep>
default[:magento][:redis][:cache][:port] = '6379'
default[:magento][:redis][:session][:port] = '6380'<file_sep>require 'chefspec'
require 'chefspec/berkshelf'
require 'ecomdev/chefspec'
module SpecHelper
def test_params(&block)
chef_run_proxy.before(:converge, false) do |runner|
if block.arity == 1
block.call(runner.node.set[:test])
else
block.call(runner.node.set[:test], runner.node)
end
end
end
end
RSpec.configure do |c|
c.include SpecHelper
end
ChefSpec::Coverage.start!<file_sep>require 'spec_helper'
describe 'magento::dev' do
let(:chef_run) do
chef_run_proxy.instance.converge(described_recipe)
end
it 'should include magerun tool recipe' do
expect(chef_run).to include_recipe('n98-magerun::default')
end
it 'should install htop package' do
expect(chef_run).to install_package('htop')
end
it 'should install vim package' do
expect(chef_run).to install_package('vim')
end
end<file_sep># Magento cookbook
Installs nginx, php-fpm and configures vhost in order to run correctly Magento application.
## Build Status
[](https://travis-ci.org/EcomDev/chef-magento) **Next Release Branch**
[](https://travis-ci.org/EcomDev/chef-magento) **Current Stable Release**
# Supported OS
* Ubuntu 12.04, 13.02
* CentOS 6.3, 6.4, 6.5
* Debian 7.4
<file_sep>require 'spec_helper'
describe 'magento_test::user' do
before (:each) { allow_recipe('magento::default', 'vhost::nginx') }
let(:chef_run) do
chef_run_instance.converge(described_recipe)
end
def chef_run_instance(&block)
chef_run_proxy.instance(step_into: 'magento_user') do |node|
node.set[:test][:name] = 'test'
unless block.nil?
block.call(node)
end
end
end
let (:default_params) { chef_run.node.default[:magento][:default][:database] }
let (:connection_settings) { default_params[:connection_settings] }
let (:node) { chef_run.node }
context 'In all systems' do
it 'should invoke a magento_user resource with create action' do
expect(chef_run).to create_magento_user('test')
end
it 'should invoke a system user creation' do
expect(chef_run).to create_user('test').with(uid: nil, gid: nil, system: true, shell: '/bin/bash')
end
it 'should invoke a system user creation with uid' do
test_params do |params|
params[:uid] = 501
end
expect(chef_run).to create_user('test').with(uid: 501, gid: nil, system: true, shell: '/bin/bash')
end
it 'should invoke a system user creation with uid' do
runner = chef_run_instance do |node|
node.set[:test][:name] = 'test'
node.set[:test][:uid] = 501
node.set[:test][:gid] = :system_default
end
runner.converge(described_recipe, 'vhost::nginx')
expect(runner).to create_user('test').with(uid: 501, gid: 'www-data', system: true, shell: '/bin/bash')
end
it 'should not change group to system default if no detection can be done' do
test_params do |params|
params[:uid] = 501
params[:gid] = :system_default
end
expect(chef_run).to create_user('test').with(uid: 501, gid: nil, system: true, shell: '/bin/bash')
end
it 'should modify a system nginx user uid if there is an nginx user' do
runner = chef_run_instance do |node|
node.set[:test][:name] = 'www-data'
node.set[:test][:uid] = 501
end
runner.converge('vhost::nginx', described_recipe)
expect(runner).to create_magento_user('www-data')
expect(runner).to modify_user('www-data').with(uid: 501)
end
it 'removes a user' do
test_params do |params|
params[:action] = 'delete'
end
expect(chef_run).to delete_magento_user('test')
expect(chef_run).to remove_user('test')
end
end
end<file_sep>require 'spec_helper'
describe 'magento_test::database' do
before (:each) { allow_recipe('magento::default', 'database::mysql') }
let(:chef_run) do
chef_run_proxy.instance(step_into: 'magento_database') do |node|
node.set[:test][:name] = 'test'
end.converge(described_recipe)
end
let (:default_params) { {
'encoding' => 'utf8',
'connection_settings' => {
'host' => 'localhost',
'user' => 'root'
}
}}
let (:connection_settings) { default_params['connection_settings'] }
let (:node) { chef_run.node }
it 'should include database' do
expect(chef_run).to include_recipe('database::mysql')
end
it 'should invoke a magento_db resource with create action' do
expect(chef_run).to create_magento_database('test')
end
it 'should invoke a mysql database resource with create action' do
expect(chef_run).to create_mysql_database('test')
.with(
connection: connection_settings,
encoding: default_params['encoding']
)
end
it 'should invoke a mysql database user resource with create action' do
expect(chef_run).to create_mysql_database_user('test')
.with(
connection: connection_settings,
username: 'test',
password: '<PASSWORD>',
host: '%',
database_name: 'test'
)
end
it 'should invoke a mysql database user resource with grant action' do
expect(chef_run).to grant_mysql_database_user('test')
.with(
connection: connection_settings,
username: 'test',
password: '<PASSWORD>',
host: '%',
database_name: 'test'
)
end
it 'should invoke a mysql test database resource with create action' do
test_params do |params|
params[:create_test] = true
end
expect(chef_run).to create_mysql_database('test_test')
.with(
connection: connection_settings,
encoding: default_params['encoding']
)
end
it 'should invoke a mysql test database user resource with grant action' do
test_params do |params|
params[:create_test] = true
end
expect(chef_run).to grant_mysql_database_user('test_test')
.with(
connection: connection_settings,
username: 'test',
password: '<PASSWORD>',
host: '%',
database_name: 'test_test',
)
end
it 'should invoke a magento_db resource with delete action' do
test_params do |params|
params[:action] = :delete
end
expect(chef_run).to include_recipe('database::mysql')
expect(chef_run).to include_recipe('magento::default')
expect(chef_run).to delete_magento_database('test')
expect(chef_run).to drop_mysql_database('test')
.with(
connection: connection_settings
)
expect(chef_run).to drop_mysql_database_user('test')
.with(
connection: connection_settings,
username: 'test',
host: '%'
)
end
end<file_sep>include_recipe 'openssl::upgrade'
if node.recipe?('mysql::server')
node.default[:magento][:default][:database][:connection_settings][:password] = node[:mysql][:server_root_password]
node.default[:magento][:default][:database][:connection_settings][:port] = node[:mysql][:port].to_i
end<file_sep>servers = []
node[:magento][:redis].each_pair do |key, value|
if value.is_a?(Hash) && value.key?(:port)
servers << {port: value[:port], name: key.to_s}
end
end
node.set[:redisio] = {
:servers => servers
}
include_recipe 'redisio::install'
include_recipe 'redisio::enable'<file_sep>require 'spec_helper'
describe 'magento::default' do
before(:each) { allow_recipe('mysql::server') }
let(:chef_run) do
chef_run_proxy.instance(step_into: 'magento_database') do |node|
node.set[:mysql][:server_root_password] = '<PASSWORD>'
node.set[:mysql][:port] = '3307'
end
end
let(:connection_settings) { chef_run.node[:magento][:default][:database][:connection_settings] }
it 'does not change connection attributes if recipe is not included' do
chef_run.converge(described_recipe)
expect(connection_settings.key?(:password)).to eq(false)
expect(connection_settings.key?(:port)).to eq(false)
end
it 'changes connection attributes if recipe is included' do
chef_run.converge(described_recipe, 'mysql::server')
expect(connection_settings[:password]).to eq('<PASSWORD>')
expect(connection_settings[:port]).to eq(3307)
end
it 'includes openssl::upgrade recipe for upgrading openssl library' do
chef_run.converge(described_recipe)
expect(chef_run).to include_recipe('openssl::upgrade')
end
end<file_sep>source "https://supermarket.getchef.com"
metadata
cookbook "magento_test", path: 'test/fixtures/magento_test'
cookbook "php_fpm", github: 'EcomDev/chef-php_fpm', branch: 'master'
cookbook "vhost", github: 'EcomDev/chef-vhost', tag: '0.1.3'
cookbook "ecomdev_common", github: 'EcomDev/chef-ecomdev_common', tag: '0.1.0'<file_sep># Logrotate recipe resources
runner :logrotate_app
matcher :logrotate_app, :create
matcher :logrotate_app, :delete
<file_sep>runner :composer_project
matcher :composer_project, :install
<file_sep>
# Support whyrun
def whyrun_supported?
true
end
action :create do
run_context.include_recipe('magento::default')
options = resource_options
if options[:vhost] == 'nginx'
run_context.include_recipe('vhost::nginx')
end
resource = []
resource <<= magento_user options[:user] do
uid options[:uid] unless options[:uid].nil?
gid options[:gid] unless options[:gid].nil?
end
options[:php_extensions].each_pair do |ext, ext_data|
resource <<= php_pear ext.to_s do
if ext_data.is_a?(Hash)
ini_options = {}
ext_data.each_pair do |key, value|
if respond_to?(key.to_sym)
send(key.to_sym, value)
else
ini_options[key.to_s] = value
end
end
unless ini_options.empty?
directives(ini_options)
end
end
end
end
resource <<= directory options[:directory] do
user options[:user]
group options[:group]
recursive true
ignore_failure true # Known issue with NFS OSX share on permission change
not_if { ::File.exists?(options[:directory]) }
end
if options[:composer]
run_context.include_recipe 'composer::default'
resource <<= composer_project options[:composer_path] do
user options[:user]
group options[:group]
action :install
dev true
quiet false
end
end
if options[:log_dir].start_with?(options[:directory] + ::File::SEPARATOR)
paths = options[:log_dir][
options[:directory].length+1..options[:log_dir].length
].split(::File::SEPARATOR)
# Create all parent directories for log directory with the same rights as project directory
base_path = options[:directory]
paths.each do |path|
base_path = ::File.join(base_path, path)
resource <<= directory base_path do
user options[:user]
group options[:group]
ignore_failure true # Known issue with NFS OSX share on permission change
not_if { ::File.exists?(base_path) }
end
end
else
resource <<= directory options[:log_dir] do
user options[:user]
group options[:group]
recursive true
not_if { ::File.exists?(options[:log_dir]) }
end
end
resource <<= php_fpm_pool options[:name] do
options[:php_fpm_options].each_pair do |key, value|
send(key, value)
end
end
host_run_code = {}
host_run_type = {}
options[:domain_map].each_pair do |key, value|
if value.is_a?(String)
host_run_code[key.to_s] = value
elsif value.is_a?(Hash) && value.key?(:store)
host_run_code[key.to_s] = value[:store]
elsif value.is_a?(Hash) && value.key?(:website)
host_run_type[key.to_s] = 'website'
host_run_code[key.to_s] = value[:website]
end
end
if options[:vhost] == 'nginx'
resource <<= create_vhost_nginx(options, host_run_code, host_run_type)
end
resource <<= magento_database options[:database_options][:name] do
options[:database_options].each_pair do |key, value|
if respond_to?(key)
send(key, value)
end
end
end
logrotate_app 'magento-' + options[:name] do
path ::File.join(options[:log_dir], '*.log')
frequency 'daily'
rotate 8
create "644 #{options[:user]} #{options[:group]}"
end
new_resource.update_from_resources(resource)
end
action :delete do
run_context.include_recipe('magento::default')
Chef::Log.info('No resource deletion possibilities for now')
end
private
def create_vhost_nginx(options, host_run_code, host_run_type)
if options[:magento_type] == '2'
_nginx_vhost_magento_two(options, host_run_code, host_run_type)
else
_nginx_vhost_magento_one(options, host_run_code, host_run_type)
end
end
def _nginx_vhost_magento_one(options, host_run_code, host_run_type)
vhost_nginx options[:main_domain] do
action [:create, :enable]
listen options[:http_port]
if options[:ssl].is_a?(Hash)
listen options[:https_port], %w(ssl)
ssl options[:ssl]
end
document_root options[:directory]
upstream("#{options[:name]}_fpm", [fpm: options[:name]])
http_map("#{options[:name]}_mage_run_code", 'http_host', host_run_code, '')
http_map("#{options[:name]}_mage_run_type", 'http_host', host_run_type, 'store')
custom_directive(
set: {
'$my_ssl' => '""',
'$my_port' => '"80"'
}
)
custom_directive(
if: '$http_x_forwarded_proto ~ "https"',
op: {
set: {
'$my_ssl' => '"on"',
'$my_port' => '"443"'
}
}
)
unless options[:status_path] == ''
location(options[:status_path], [
access_log: 'off',
allow: ['127.0.0.1'].push(options[:status_ips]).flatten,
deny: 'all',
include: 'fastcgi_params',
fastcgi_param: 'SCRIPT_FILENAME $document_root$fastcgi_script_name',
fastcgi_pass: "#{options[:name]}_fpm"
])
end
location('~ /\.',
deny: 'all',
access_log: 'off',
log_not_found: 'off')
options[:deny_paths].each do |path|
location('^~ ' + path, 'deny all')
end
options[:custom_locations].each_pair do |name, value|
location(name, value)
end
location('/',
index: "index.html #{options[:handler]}",
try_files: '$uri $uri/ @magento',
expires: options[:cache_static])
location('@magento', rewrite: "/ /#{options[:handler]}")
location('~ ^.+\.php(/|$)',
expires: 'off',
fastcgi_split_path_info: '^((?U).+\.php)(/?.+)$',
try_files: '$fastcgi_script_name =404',
include: 'fastcgi_params',
fastcgi_param: {
SCRIPT_FILENAME: '$document_root$fastcgi_script_name',
PATH_INFO: '$fastcgi_path_info',
PATH_TRANSLATED: '$document_root$fastcgi_path_info',
MAGE_RUN_CODE: "$#{options[:name]}_mage_run_code",
MAGE_RUN_TYPE: "$#{options[:name]}_mage_run_type",
SERVER_PORT: '$my_port',
HTTPS: '$my_ssl'
},
fastcgi_pass: "#{options[:name]}_fpm",
fastcgi_read_timeout: options[:time_limit] + 's',
fastcgi_index: options[:handler],
fastcgi_buffers: options[:buffers],
fastcgi_buffer_size: options[:buffer_size])
end
end
def _nginx_vhost_magento_two(options, host_run_code, host_run_type)
vhost_nginx options[:main_domain] do
action [:create, :enable]
listen options[:http_port]
if options[:ssl].is_a?(Hash)
listen options[:https_port], %w(ssl)
ssl options[:ssl]
end
document_root options[:directory] + '/pub'
upstream("#{options[:name]}_fpm", [fpm: options[:name]])
custom_directive(
set: {
'$my_ssl' => '""',
'$my_port' => '"80"'
}
)
custom_directive(
if: '$http_x_forwarded_proto ~ "https"',
op: {
set: {
'$my_ssl' => '"on"',
'$my_port' => '"443"'
}
}
)
unless options[:status_path] == ''
location(options[:status_path], [
access_log: 'off',
allow: ['127.0.0.1'].push(options[:status_ips]).flatten,
deny: 'all',
include: 'fastcgi_params',
fastcgi_param: 'SCRIPT_FILENAME $document_root$fastcgi_script_name',
fastcgi_pass: "#{options[:name]}_fpm"
])
end
location('~ /\.',
deny: 'all',
access_log: 'off',
log_not_found: 'off')
options[:custom_locations].each_pair do |name, value|
location(name, value)
end
[
'/media/customer/',
'/media/downloadable/',
'~ /media/theme_customization/.*\.xml$',
'~ cron\.php',
'~ ^/errors/.*\.(xml|phtml)$'
].each do |location|
location(location, 'deny all')
end
location('/static/',
expires: options[:cache_static],
try_files: '$uri @magento_static')
location('/media/',
expires: options[:cache_static],
try_files: '$uri @magento_media')
location('/',
index: "index.html #{options[:handler]}",
try_files: '$uri $uri/ @magento_app')
location('@magento_app', rewrite: "/ /#{options[:handler]}")
location('@magento_media', rewrite: '/ /get.php')
location('@magento_static', rewrite: '^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last')
location('~ ^.+\.php(/|$)',
expires: 'off',
fastcgi_split_path_info: '^((?U).+\.php)(/?.+)$',
try_files: '$fastcgi_script_name =404',
include: 'fastcgi_params',
fastcgi_param: {
SCRIPT_FILENAME: '$document_root$fastcgi_script_name',
PATH_INFO: '$fastcgi_path_info',
PATH_TRANSLATED: '$document_root$fastcgi_path_info',
SERVER_PORT: '$my_port',
HTTPS: '$my_ssl'
},
fastcgi_pass: "#{options[:name]}_fpm",
fastcgi_read_timeout: options[:time_limit] + 's',
fastcgi_index: options[:handler],
fastcgi_buffers: options[:buffers],
fastcgi_buffer_size: options[:buffer_size])
end
end
def transform_keys!(hash, &block)
if hash.is_a?(Hash)
hash.keys.each do |key|
new_key = block.call(key)
hash[new_key] = hash.delete(key)
transform_keys!(hash[new_key], &block)
end
elsif hash.is_a?(Array)
hash.each { |v| transform_keys!(v, &block) }
end
end
def resource_options
options = new_resource.dump_attribute_values(node[:magento][:default][:application], :magento_default)
transform_keys!(options) { |v| v.to_sym }
if options[:user] == :system_default
options[:user] = options[:name]
end
if options[:group] == :system_default
options[:gid] = nil
if options[:vhost] == 'nginx'
options[:group] = node[:nginx][:group]
options[:gid] = node[:nginx][:group]
else
options[:group] = options[:user]
end
else
options[:gid] = options[:group]
end
options[:log_dir] = ::File.expand_path(options[:log_dir], options[:directory])
if options[:composer_path].nil? || options[:composer_path] == :system_default
options[:composer_path] = options[:directory]
else
options[:composer_path] = ::File.expand_path(options[:composer_path], options[:directory])
end
if options[:php_fpm_options].is_a?(Hash)
specify_php_fpm_options(options)
end
if options[:database_options][:name].nil?
options[:database_options][:name] = options[:name]
end
options
end
def specify_php_fpm_options(options)
if options[:php_fpm_options][:socket_user] == :system_default
options[:php_fpm_options][:socket_user] = nil
end
if options[:php_fpm_options][:socket_group] == :system_default
options[:php_fpm_options][:socket_group] = nil
end
if options[:vhost] == 'nginx'
if options[:php_fpm_options][:socket_user] == nil
options[:php_fpm_options][:socket_user] = node[:nginx][:user]
end
if options[:php_fpm_options][:socket_group] == nil
options[:php_fpm_options][:socket_group] = node[:nginx][:group]
end
end
options[:php_fpm_options][:user] = options[:user]
options[:php_fpm_options][:group] = options[:group]
if options[:php_fpm_options][:php_admin_value][:error_log] == :system_default
options[:php_fpm_options][:php_admin_value][:error_log] = ::File.join(options[:log_dir], 'fpm-error.log')
end
if options[:php_fpm_options][:request_terminate_timeout] == :system_default
options[:php_fpm_options][:request_terminate_timeout] = options[:time_limit] + 's'
end
if options[:php_fpm_options][:php_admin_value][:memory_limit] == :system_default
options[:php_fpm_options][:php_admin_value][:memory_limit] = options[:memory_limit]
end
if options[:php_fpm_options][:php_admin_value][:max_execution_time] == :system_default
options[:php_fpm_options][:php_admin_value][:max_execution_time] = options[:time_limit]
end
end<file_sep>
# Support whyrun
def whyrun_supported?
true
end
action :create do
run_context.include_recipe('database::mysql')
run_context.include_recipe('magento::default')
options = resource_options
mysql_database options[:name] do
connection options[:connection_settings]
encoding options[:encoding] if options.key?(:encoding)
collation options[:collation] if options.key?(:collation)
end
mysql_database_user options[:user] do
connection options[:connection_settings]
username options[:user]
password options[:password]
host options[:host]
database_name options[:name]
action [:create, :grant]
end
if options[:create_test]
test_database = options[:name] + '_test'
mysql_database test_database do
connection options[:connection_settings]
encoding options[:encoding] if options.key?(:encoding)
collation options[:collation] if options.key?(:collation)
end
mysql_database_user test_database do
connection options[:connection_settings]
username options[:user]
host options[:host]
password options[:password]
database_name test_database
action :grant
end
end
end
action :delete do
run_context.include_recipe('database::mysql')
run_context.include_recipe('magento::default')
options = resource_options
mysql_database options[:name] do
action :drop
connection options[:connection_settings]
end
mysql_database_user options[:user] do
action :drop
host options[:host]
connection options[:connection_settings]
end
end
private
def resource_options
options = new_resource.dump_attribute_values(node[:magento][:default][:database], :magento_default)
if options[:user] == :database_name
options[:user] = options[:name]
end
if options[:password] == :database_name
options[:password] = options[:name]
end
options
end<file_sep>actions :create, :delete
attribute :name, :kind_of => [String, Symbol], :name_attribute => true # Name of the database
attribute :vhost, :kind_of => [String, Symbol], :default => :magento_default # Type of Vhost
attribute :ssl, :kind_of => [Hash, Symbol], :default => :magento_default # Hash of private and public keys for ssl
attribute :directory, :kind_of => [String, Symbol], :default => :magento_default # Dirname that will be used for application
attribute :main_domain, :kind_of => [String, Symbol], :required => true # Main application domain name
attribute :domains, :kind_of => [Array, Symbol], :default => :magento_default # Additional application domain names
attribute :domain_map, :kind_of => [Hash, Symbol], :default => :magento_default # Additional application domain names
attribute :user, :kind_of => [String, Symbol], :default => :magento_default # Username that will be created for application
attribute :uid, :kind_of => [Integer, Symbol], :default => :magento_default # Username that will be created for application
attribute :group, :kind_of => [String, Symbol], :default => :magento_default # Group password that will be created for application
attribute :handler, :kind_of => [String, Symbol], :default => :magento_default # Magento main php handler
attribute :time_limit, :kind_of => [String, Symbol], :default => :magento_default # Magento time limit in seconds
attribute :memory_limit, :kind_of => [String, Symbol], :default => :magento_default # Magento memory limit in seconds
attribute :php_extensions, :kind_of => [Hash, Symbol], :default => :magento_default # Additional PHP extensions for Magento
attribute :status_path, :kind_of => [String, Symbol], :default => :magento_default # Magento status page (default is php-fpm status)
attribute :status_ips, :kind_of => [Array, Symbol], :default => :magento_default # Ips that allow status page discovery
attribute :store_map, :kind_of => [Hash, Symbol], :default => :magento_default # Map of store or website code to hostname
attribute :http_port, :kind_of => [String, Symbol], :default => :magento_default # Http port setting
attribute :https_port, :kind_of => [String, Symbol], :default => :magento_default # Https port setting
attribute :log_dir, :kind_of => [String, Symbol], :default => :magento_default # Magento log directory
attribute :php_fpm_options, :kind_of => [Hash, Symbol], :default => :magento_default # Magento log directory
attribute :deny_paths, :kind_of => [Array, Symbol], :default => :magento_default # Denied path in Magento configuration
attribute :cache_static, :kind_of => [String, Symbol], :default => :magento_default # Cache static files options
attribute :custom_locations, :kind_of => Hash, :default => {} # Custom locations for nginx
attribute :buffers, :kind_of => [String, Symbol], :default => :magento_default # Fastcgi buffers in nginx
attribute :buffer_size, :kind_of => [String, Symbol], :default => :magento_default # Fastcgi buffer size in nginx
attribute :database_options, :kind_of => [Hash, Symbol], :default => :magento_default # Database connection and creation options
attribute :composer, :kind_of => [TrueClass, FalseClass, Symbol], :default => :magento_default # Flag for auto-composer installation
attribute :composer_path, :kind_of => [String, Symbol], :default => :magento_default # Flag for auto-composer installation
attribute :magento_type, :kind_of => [String, Symbol], :default => :magento_default # Flag for a major Magento version
def initialize(*args)
super
@action = :create
end<file_sep>require 'spec_helper'
describe 'magento_test::application' do
before (:each) { allow_recipe('magento::default', 'vhost::nginx', 'php_fpm::default', 'php_fpm::fpm') }
let(:chef_run) do
chef_run_proxy.instance(step_into: 'magento_application') do |node|
node.set[:test][:name] = 'test'
node.set[:test][:directory] = '/var/www/test.magento.com'
node.set[:test][:main_domain] = 'test.dev'
end.converge(described_recipe)
end
let (:node) { chef_run.node }
it 'should create a magento application named test' do
expect(chef_run).to create_magento_application('test')
end
it 'should include magento::default recipe' do
expect(chef_run).to include_recipe('magento::default')
end
it 'should include vhost::nginx recipe' do
expect(chef_run).to include_recipe('vhost::nginx')
end
it 'should not include vhost::nginx recipe if not specified' do
test_params do |params|
params[:vhost] = 'apache'
end
expect(chef_run).not_to include_recipe('vhost::nginx')
end
it 'should create a system user for application' do
expect(chef_run).to create_magento_user('test')
end
it 'should create a magento database' do
expect(chef_run).to create_magento_database('test')
end
it 'should pass connection_settings to magento database creation' do
test_params do |params|
params[:database_options] = {
connection_settings: {
host: '192.168.0.1',
user: 'root',
password: '<PASSWORD>'
}
}
end
expect(chef_run).to create_magento_database('test').with(connection_settings: {
host: '192.168.0.1',
user: 'root',
password: '<PASSWORD>'
})
end
it 'should custom database name' do
test_params do |params|
params[:database_options] = {
name: 'magento_test'
}
end
expect(chef_run).to create_magento_database('magento_test')
end
it 'should create a system user with params' do
test_params do |params|
params[:user] = 'test-two'
params[:group] = 'test-two'
params[:uid] = 501
end
expect(chef_run).to create_magento_user('test-two').with(
uid: 501,
gid: 'test-two'
)
end
it 'should create a php-fpm pool for user' do
expect(chef_run).to create_php_fpm_pool('test').with(
socket: true,
socket_user: node[:nginx][:user],
socket_group: node[:nginx][:group],
user: 'test',
group: node[:nginx][:group]
)
end
it 'should create a directory for a document root' do
expect(chef_run).to create_directory('/var/www/test.magento.com').with(
user: 'test',
group: node[:nginx][:group]
)
end
it 'should not create a directory for a document root if directory is already exists' do
stub_file_exists('/var/www/test.magento.com')
expect(chef_run).not_to create_directory('/var/www/test.magento.com')
end
it 'should create a directory for a magento logging ' do
expect(chef_run).to create_directory('/var/www/test.magento.com/var').with(
user: 'test',
group: node[:nginx][:group]
)
expect(chef_run).to create_directory('/var/www/test.magento.com/var/log').with(
user: 'test',
group: node[:nginx][:group]
)
end
it 'should create directory for magento logging in absolute path' do
test_params do |params|
params[:log_dir] = '/some/absolute/path/var/log'
end
expect(chef_run).not_to create_directory('/var/www/test.magento.com/var/log')
expect(chef_run).to create_directory('/some/absolute/path/var/log')
.with(
user: 'test',
group: node[:nginx][:group]
)
end
it 'should not create a directory for a magento logging if it is already exists' do
stub_file_exists('/var/www/test.magento.com/var/log')
expect(chef_run).not_to create_directory('/var/www/test.magento.com/var/log')
end
it 'should create a php-fpm pool for user' do
expect(chef_run).to create_php_fpm_pool('test').with(
socket: true,
socket_user: node[:nginx][:user],
socket_group: node[:nginx][:group],
user: 'test',
group: node[:nginx][:group],
request_terminate_timeout: node[:magento][:default][:application][:time_limit] + 's',
php_admin_flag: {
log_errors: 'on',
display_errors: 'off',
display_startup_errors: 'off'
},
php_admin_value: {
error_log: '/var/www/test.magento.com/var/log/fpm-error.log',
error_reporting: 'E_ALL',
memory_limit: node[:magento][:default][:application][:memory_limit],
max_execution_time: node[:magento][:default][:application][:time_limit]
}
)
end
it 'should create a custom user' do
test_params do |params|
params[:user] = 'www-user'
params[:group] = 'www-group'
end
expect(chef_run).to create_magento_user('www-user').with(
gid: 'www-group'
)
end
it 'should create a php-fpm pool with a custom user' do
test_params do |params|
params[:user] = 'www-user'
params[:group] = 'www-group'
end
expect(chef_run).to create_php_fpm_pool('test').with(
user: 'www-user',
group: 'www-group'
)
end
it 'should create a vhost for an application' do
test_params do |params|
params[:status_ips] = ['192.168.0.0/16', '192.168.3.11/24']
params[:deny_paths] = ['/app/', '/lib/']
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
listens: [
{listen: '80', params: []}
],
document_root: '/var/www/test.magento.com',
upstreams: {
'test_fpm' => {
servers: [
{fpm: 'test'}
],
custom: {}
}
},
http_maps: {
'test_mage_run_code' => {
source: 'http_host',
maps: {},
default: '',
hostnames: true
},
'test_mage_run_type' => {
source: 'http_host',
maps: {},
default: 'store',
hostnames: true
}
},
custom_directives: [
'set $my_ssl "";',
'set $my_port "80";',
'if ($http_x_forwarded_proto ~ "https") { ',
' set $my_ssl "on";',
' set $my_port "443";',
'}'
],
locations: {
node[:magento][:default][:application][:status_path] => [
'access_log off;',
'allow 127.0.0.1;',
'allow 192.168.0.0/16;',
'allow 192.168.3.11/24;',
'deny all;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_pass test_fpm;',
],
'~ /\.' => [
'deny all;',
'access_log off;',
'log_not_found off;'
],
'^~ /app/' => ['deny all;'],
'^~ /lib/' => ['deny all;'],
'/' => [
'index index.html ' + node[:magento][:default][:application][:handler] + ';',
'try_files $uri $uri/ @magento;',
'expires ' + node[:magento][:default][:application][:cache_static] + ';'
],
'@magento' => [
'rewrite / /' + node[:magento][:default][:application][:handler] + ';'
],
'~ ^.+\.php(/|$)' => [
'expires off;',
'fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;',
'try_files $fastcgi_script_name =404;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_param PATH_INFO $fastcgi_path_info;',
'fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;',
'fastcgi_param MAGE_RUN_CODE $test_mage_run_code;',
'fastcgi_param MAGE_RUN_TYPE $test_mage_run_type;',
'fastcgi_param SERVER_PORT $my_port;',
'fastcgi_param HTTPS $my_ssl;',
'fastcgi_pass test_fpm;',
'fastcgi_read_timeout ' + node[:magento][:default][:application][:time_limit] + 's;',
'fastcgi_index ' + node[:magento][:default][:application][:handler] + ';',
'fastcgi_buffers ' + node[:magento][:default][:application][:buffers] + ';',
'fastcgi_buffer_size ' + node[:magento][:default][:application][:buffer_size] + ';'
]
}
)
end
it 'should create a vhost for Magento 2 application' do
test_params do |params|
params[:status_ips] = ['192.168.0.0/16', '192.168.3.11/24']
params[:deny_paths] = ['/app/', '/lib/']
params[:magento_type] = '2'
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
listens: [
{listen: '80', params: []}
],
document_root: '/var/www/test.magento.com/pub',
upstreams: {
'test_fpm' => {
servers: [
{fpm: 'test'}
],
custom: {}
}
},
custom_directives: [
'set $my_ssl "";',
'set $my_port "80";',
'if ($http_x_forwarded_proto ~ "https") { ',
' set $my_ssl "on";',
' set $my_port "443";',
'}'
],
locations: {
node[:magento][:default][:application][:status_path] => [
'access_log off;',
'allow 127.0.0.1;',
'allow 192.168.0.0/16;',
'allow 192.168.3.11/24;',
'deny all;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_pass test_fpm;',
],
'~ /\.' => [
'deny all;',
'access_log off;',
'log_not_found off;'
],
'/media/customer/' => ['deny all;'],
'/media/downloadable/' => ['deny all;'],
'~ /media/theme_customization/.*\.xml$' => ['deny all;'],
'~ cron\.php' => ['deny all;'],
'~ ^/errors/.*\.(xml|phtml)$' => ['deny all;'],
'/static/' => [
'expires ' + node[:magento][:default][:application][:cache_static] + ';',
'try_files $uri @magento_static;'
],
'/media/' => [
'expires ' + node[:magento][:default][:application][:cache_static] + ';',
'try_files $uri @magento_media;'
],
'/' => [
'index index.html ' + node[:magento][:default][:application][:handler] + ';',
'try_files $uri $uri/ @magento_app;'
],
'@magento_app' => [
'rewrite / /' + node[:magento][:default][:application][:handler] + ';'
],
'@magento_media' => [
'rewrite / /get.php;'
],
'@magento_static' => [
'rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;'
],
'~ ^.+\.php(/|$)' => [
'expires off;',
'fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;',
'try_files $fastcgi_script_name =404;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_param PATH_INFO $fastcgi_path_info;',
'fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;',
'fastcgi_param SERVER_PORT $my_port;',
'fastcgi_param HTTPS $my_ssl;',
'fastcgi_pass test_fpm;',
'fastcgi_read_timeout ' + node[:magento][:default][:application][:time_limit] + 's;',
'fastcgi_index ' + node[:magento][:default][:application][:handler] + ';',
'fastcgi_buffers ' + node[:magento][:default][:application][:buffers] + ';',
'fastcgi_buffer_size ' + node[:magento][:default][:application][:buffer_size] + ';'
]
}
)
end
it 'should automatically add SSL options to nginx configuration' do
test_params do |params|
params[:ssl] = {
:public => 'a public key',
:private => 'a private key'
}
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
listens: [
{listen: '80', params: []},
{listen: '443', params: ['ssl']}
],
ssl: {
public: 'a public key',
private: 'a private key'
}
)
end
it 'allows to specify custom https and http ports' do
test_params do |params|
params[:http_port] = '8080'
params[:https_port] = '4434'
params[:ssl] = {
:public => 'a public key',
:private => 'a private key'
}
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
listens: [
{listen: '8080', params: []},
{listen: '4434', params: ['ssl']}
],
ssl: {
public: 'a public key',
private: 'a private key'
}
)
end
it 'creates hostmaps based on attributes' do
test_params do |params|
params[:domain_map] = {
'my.test.dev' => 'my',
'my2.test.dev' => {store: 'my2'},
'my3.test.dev' => {website: 'my3'}
}
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
http_maps: {
'test_mage_run_code' => {
source: 'http_host',
maps: {
'my.test.dev' => 'my',
'my2.test.dev' => 'my2',
'my3.test.dev' => 'my3'
},
default: '',
hostnames: true
},
'test_mage_run_type' => {
source: 'http_host',
maps: {
'my3.test.dev' => 'website'
},
default: 'store',
hostnames: true
}
},
)
end
it 'installs additional php_packages' do
test_params do |params|
params[:php_extensions] = {
curl: true,
xdebug: {
preferred_state: 'beta',
zend_extensions: ['xdebug.so']
},
intl: {
preferred_state: 'beta',
'php.ini_value' => 1
}
}
end
expect(chef_run).to install_php_pear('curl')
expect(chef_run).to install_php_pear('xdebug').with(
preferred_state: 'beta',
zend_extensions: ['xdebug.so']
)
expect(chef_run).to install_php_pear('intl').with(
preferred_state: 'beta',
directives: {
'php.ini_value' => 1
}
)
end
it 'allows adding custom locations' do
test_params do |params|
params[:status_ips] = ['192.168.0.0/16', '192.168.3.11/24']
params[:deny_paths] = ['/app/', '/lib/']
params[:custom_locations] = {
'/en-us/' => {
rewrite: '^/([a-z-]+)/.*+$ /$1/index.php?$args'
}
}
end
expect(chef_run).to create_vhost_nginx('test.dev').with(
locations: {
node[:magento][:default][:application][:status_path] => [
'access_log off;',
'allow 127.0.0.1;',
'allow 192.168.0.0/16;',
'allow 192.168.3.11/24;',
'deny all;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_pass test_fpm;',
],
'~ /\.' => [
'deny all;',
'access_log off;',
'log_not_found off;'
],
'^~ /app/' => ['deny all;'],
'^~ /lib/' => ['deny all;'],
'/en-us/' => ['rewrite ^/([a-z-]+)/.*+$ /$1/index.php?$args;'],
'/' => [
'index index.html ' + node[:magento][:default][:application][:handler] + ';',
'try_files $uri $uri/ @magento;',
'expires ' + node[:magento][:default][:application][:cache_static] + ';'
],
'@magento' => [
'rewrite / /' + node[:magento][:default][:application][:handler] + ';'
],
'~ ^.+\.php(/|$)' => [
'expires off;',
'fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;',
'try_files $fastcgi_script_name =404;',
'include fastcgi_params;',
'fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;',
'fastcgi_param PATH_INFO $fastcgi_path_info;',
'fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;',
'fastcgi_param MAGE_RUN_CODE $test_mage_run_code;',
'fastcgi_param MAGE_RUN_TYPE $test_mage_run_type;',
'fastcgi_param SERVER_PORT $my_port;',
'fastcgi_param HTTPS $my_ssl;',
'fastcgi_pass test_fpm;',
'fastcgi_read_timeout ' + node[:magento][:default][:application][:time_limit] + 's;',
'fastcgi_index ' + node[:magento][:default][:application][:handler] + ';',
'fastcgi_buffers ' + node[:magento][:default][:application][:buffers] + ';',
'fastcgi_buffer_size ' + node[:magento][:default][:application][:buffer_size] + ';'
]
}
)
end
it 'includes composer recipe if composer is set to true' do
test_params do |params|
params[:composer] = true
end
expect(chef_run).to include_recipe('composer::default')
end
it 'installs composer and composer package in project directory if composer flag is set to true' do
test_params do |params|
params[:composer] = true
end
expect(chef_run).to install_composer_project('/var/www/test.magento.com')
.with(
user: 'test',
group: 'www-data',
dev: true,
quiet: false
)
end
it 'installs composer in custom composer path' do
test_params do |params|
params[:composer] = true
params[:composer_path] = '../'
end
expect(chef_run).to install_composer_project('/var/www')
end
it 'installs composer in custom absolute composer path' do
test_params do |params|
params[:composer] = true
params[:composer_path] = '/var/test'
end
expect(chef_run).to install_composer_project('/var/test')
end
it 'does not include composer recipe if path is not specified' do
expect(chef_run).not_to include_recipe('composer::default')
end
it 'does not install composer if no flag is specified' do
expect(chef_run).not_to install_composer_project('/var/www/test.magento.com')
end
end<file_sep>actions :create, :delete
attribute :name, :kind_of => [String, Symbol], :name_attribute => true # Name of the database
attribute :uid, :kind_of => [Integer, NilClass, Symbol], :default => :magento_default # UID of the user
attribute :gid, :kind_of => [String, Integer, NilClass, Symbol], :default => :magento_default # GID of the user
def initialize(*args)
super
@action = :create
end<file_sep>
magento_database node[:test][:name] do
if node[:test].attribute?(:action)
action node[:test][:action]
end
attribute_names.each do |attribute|
if node[:test].attribute?(attribute)
send(attribute.to_sym, node[:test][attribute])
end
end
end<file_sep>name 'magento_test'
version '0.0.1'
depends 'magento'<file_sep>require 'spec_helper'
describe 'magento::redis' do
let(:chef_run) do
chef_run_proxy.instance.converge(described_recipe)
end
def node(&block)
chef_run_proxy.before(:converge) do |runner|
if block.arity == 1
block.call(runner.node)
end
end
end
it 'should set redis ports for cache and session' do
expect(chef_run.node[:redisio][:servers]).to include({port: chef_run.node[:magento][:redis][:cache][:port],
name: 'cache'},
{port: chef_run.node[:magento][:redis][:session][:port],
name: 'session'})
end
it 'should include redisio::install' do
expect(chef_run).to include_recipe('redisio::install')
end
it 'should include redisio::enable' do
expect(chef_run).to include_recipe('redisio::install')
end
end
|
c41de411b7d3517331cc6f625c6e2d4bd45a2f87
|
[
"Markdown",
"Ruby"
] | 34
|
Ruby
|
EcomDev/chef-magento
|
be17e0ebc496cad44ea5ea18a0c0980cbf115721
|
019692166b75538c62d308a58c7494544a046da2
|
refs/heads/master
|
<repo_name>elauffenburger/oar<file_sep>/core/common/general.go
package common
import (
"math/rand"
"time"
)
var src = rand.New(rand.NewSource(time.Now().UnixNano()))
func GetRandomValue(list *[]string) string {
return (*list)[rand.Intn(len(*list))]
}
<file_sep>/test/test-can-convert-and-stream-to-sql.sql
insert into TestUser ([FirstName],[LastName],[FullName]) values
('Victor','Abar','<NAME>'),
('Genna','Minassian','<NAME>'),
('Shanice','Palley','<NAME>'),
('Indira','Pribish','<NAME>'),
('Arla','Goll','<NAME>'),
('Lanell','Polley','<NAME>'),
('Fidela','Council','Fidela Council'),
('Larry','Lube','<NAME>'),
('Marla','Muna','<NAME>'),
('Vivan','Lachowski','<NAME>'),
('Beryl','Demming','<NAME>'),
('Kemberly','Fromm','<NAME>'),
('Hyo','Mccaskell','<NAME>'),
('Hien','Anewalt','<NAME>'),
('Graig','Mctush','<NAME>'),
('Christopher','Bizcassa','<NAME>'),
('Kiersten','Decato','<NAME>'),
('Marcell','Heusel','<NAME>'),
('Bambi','Sigwart','<NAME>'),
('Carin','Dooms','<NAME>'),
('Joline','Dutson','<NAME>'),
('Vincenzo','Sabini','<NAME>'),
('Anh','Wilhelmsen','<NAME>'),
('Buffy','Appenzeller','<NAME>'),
('Tammie','Layson','<NAME>'),
('Mariel','Hizkiya','<NAME>'),
('Catalina','Alwine','<NAME>'),
('Valentine','Deshotels','Val<NAME>hotels'),
('Stephine','Wishon','<NAME>'),
('Ines','Jastrebski','<NAME>'),
('Mui','Depena','<NAME>'),
('Lazaro','Rhim','<NAME>'),
('Larissa','Greaux','<NAME>'),
('Dorie','Chemell','<NAME>'),
('Arlette','Menon','<NAME>'),
('Marth','Laos','<NAME>'),
('Alma','Tinnell','<NAME>'),
('Lidia','Fornili','<NAME>'),
('Eden','Joyne','<NAME>'),
('Merrill','Fracasso','<NAME>'),
('Kendra','Loxton','<NAME>'),
('Mabel','Shand','<NAME>'),
('Arline','Pownell','<NAME>'),
('Devin','Dunford','<NAME>'),
('Dorothy','Hartshorn','<NAME>'),
('Lai','Sahli','<NAME>'),
('Debra','Gavin','<NAME>'),
('Mitchel','Marchak','<NAME>'),
('Joni','Ungerman','<NAME>'),
('Mike','Micucci','<NAME>')<file_sep>/core/output/output_formatters.go
package output
import (
"encoding/json"
"fmt"
"strings"
"io"
res "github.com/elauffenburger/oar/core/results"
)
type OutputFormatter interface {
Format(results *res.Results) string
FormatToStream(results *res.Results, stream io.Writer)
}
type JsonOutputFormatter struct {
}
func (formatter *JsonOutputFormatter) Format(results *res.Results) string {
jsonArray := formatter.ToJsonArray(results)
marshalledbytes, err := json.Marshal(&jsonArray)
if err != nil {
panic(fmt.Sprintf("Error marshalling results: '%s", err))
}
return string(marshalledbytes)
}
func (formatter *JsonOutputFormatter) FormatToStream(results *res.Results, stream io.Writer) {
bytes := []byte(formatter.Format(results))
stream.Write(bytes)
}
type JsonObject map[string]string
type JsonArray []*JsonObject
func (obj JsonObject) Keys() []string {
keys := make([]string, len(obj))
i := 0
for key, _ := range obj {
keys[i] = key
i++
}
return keys
}
func (formatter *JsonOutputFormatter) ToJsonArray(results *res.Results) JsonArray {
result := make(JsonArray, results.NumRows())
for i, set := range results.Rows {
object := make(JsonObject)
for _, entry := range set.Values {
object[entry.Name] = entry.Value
}
result[i] = &object
}
return result
}
const maxLinesPerSqlStmt = 1000
type SqlOutputFormatter struct {
TableName string
}
func (formatter *SqlOutputFormatter) Format(results *res.Results) string {
out := ""
formatter.formatInternal(results, func(str *string) {
out += *str
})
return out
}
func (formatter *SqlOutputFormatter) formatInternal(results *res.Results, writeFn func(str *string)) {
if len(results.Rows) == 0 {
return
}
// generate initial "insert into dbo.foobar(...) values" stmt
insertHeaderStr := fmt.Sprintf("insert into %s (", formatter.TableName)
{
row := results.Rows[0]
for i, val := range row.Values {
insertHeaderStr += fmt.Sprintf("[%s]", val.Name)
if i != len(row.Values)-1 {
insertHeaderStr += ","
}
}
}
insertHeaderStr += ") values \n"
writeFn(&insertHeaderStr)
// generate subsequent "(...)" stmts and start new "insert..." stmts as necessary
n := len(results.Rows)
for i, row := range results.Rows {
// Generate (...) stmt for this row
rowstr := "("
for i, val := range row.Values {
// escape 's in values
value := strings.Replace(val.Value, "'", "''", -1)
rowstr += fmt.Sprintf("'%s'", value)
if i != len(row.Values)-1 {
rowstr += ","
}
}
rowstr += ")"
// if we're writing the max allowed insert statement (1000), end the current stmt
if (i+1)%maxLinesPerSqlStmt == 0 {
rowstr += ";\n"
// if we're not writing the last line, start a new insert stmt
if i != n-1 {
rowstr += insertHeaderStr
}
} else {
// otherwise...
// if we're not writing the last line, add a comma separator
if i != n-1 {
rowstr += ",\n"
}
}
writeFn(&rowstr)
}
}
func (formatter *SqlOutputFormatter) FormatToStream(results *res.Results, stream io.Writer) {
formatter.formatInternal(results, func(str *string) {
bytes := []byte(*str)
stream.Write(bytes)
})
}
func NewSqlOutputFormatter(tablename string) *SqlOutputFormatter {
return &SqlOutputFormatter{TableName: tablename}
}
<file_sep>/core/configuration/configuration.go
package configuration
type UseTypeDTO struct {
LoaderArgs UseTypeLoaderArgsDTO `json:"loader"`
}
type UseTypeLoaderArgsDTO struct {
Name string `json:"name"`
Args map[string]interface{} `json:"args"`
}
type Configuration struct {
OutputType OutputType `json:"output"`
Name string `json:"name`
NumRows int `json:"rows"`
Fields ConfigurationFields `json:"fields"`
Options map[string]string `json:"options"`
Types map[string]UseTypeDTO `json:"types"`
}
type OutputType string
const (
JSON OutputType = "json"
SQL OutputType = "sql"
)
func NewConfiguration() *Configuration {
return &Configuration{Options: make(map[string]string), Fields: NewConfigurationFields()}
}
<file_sep>/core/common/filehelpers.go
package common
import (
"io/ioutil"
"os"
"strings"
)
func ReadContentFromFile(path string) (*string, error) {
_, err := os.Stat(path)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
str := string(bytes)
return &str, nil
}
func ReadContentFromFileAndSplit(path string, sep string) ([]string, error) {
content, err := ReadContentFromFile(path)
if err != nil {
return nil, err
}
return strings.Split(*content, sep), nil
}
<file_sep>/core/results/results.go
package results
import (
"fmt"
conf "github.com/elauffenburger/oar/core/configuration"
)
type ResultsRowList []*ResultsRow
type Results struct {
Rows ResultsRowList
}
type ResultRowValueList []*ResultsRowValue
type ResultsRow struct {
Values ResultRowValueList
}
type ResultsRowValue struct {
conf.ConfigurationField
Value string
}
func (entries *ResultRowValueList) GetEntryWithName(name string) (*ResultsRowValue, error) {
for _, entry := range *entries {
if entry.Name == name {
return entry, nil
}
}
return nil, fmt.Errorf("Failed to find an entry with name '%s'", name)
}
func (entries *ResultRowValueList) GetEntryWithType(entryType string) (*ResultsRowValue, error) {
for _, entry := range *entries {
if entry.Type == entryType {
return entry, nil
}
}
return nil, fmt.Errorf("Failed to find an entry with type '%s'", entryType)
}
func NewRowsOfSize(n int) []ResultRowValueList {
return make([]ResultRowValueList, n)
}
func NewRows() []ResultRowValueList {
return NewRowsOfSize(0)
}
func (results *Results) NumRows() int {
return len(results.Rows)
}
func (results *Results) NumEntries() int {
numrows := results.NumRows()
if numrows == 0 {
return 0
}
return len(results.Rows[0].Values) * numrows
}
func (results *Results) ToRows() []ResultRowValueList {
rows := NewRowsOfSize(results.NumRows())
for i, set := range results.Rows {
rows[i] = set.Values
}
return rows
}
<file_sep>/oar.go
package main
import (
"flag"
"fmt"
"os"
"github.com/elauffenburger/oar/core"
)
var configFlag = flag.String("config", "", "json file to load configuration from")
var rowsFlag = flag.Int("rows", 0, "number of rows to generate")
var streamFlag = flag.Bool("stream", false, "Indicates if data should be streamed to stdout")
func main() {
flag.Parse()
configFlagValue := *configFlag
rows := *rowsFlag
if len(configFlagValue) == 0 {
panic("No configuration file provided!")
}
config, err := core.LoadConfigurationFromFile(configFlagValue)
if err != nil {
panic(fmt.Sprintf("Error loading configuration file: %s", err))
}
if rows != 0 {
config.NumRows = rows
}
results, err := core.GenerateResults(config)
if err != nil {
panic(fmt.Sprintf("Error generating results: '%s'", err))
}
// print results to stdout
formatter := core.GetOutputFormatter(config)
if *streamFlag {
formatter.FormatToStream(results, os.Stdout)
} else {
fmt.Fprint(os.Stdout, formatter.Format(results))
}
}
<file_sep>/core/loaders/default_loaders.go
package loaders
import (
"fmt"
"math/rand"
"time"
"github.com/elauffenburger/oar/core/common"
conf "github.com/elauffenburger/oar/core/configuration"
res "github.com/elauffenburger/oar/core/results"
"github.com/satori/go.uuid"
)
type FnTypeLoader struct {
typeLoader
loadFn TypeLoaderLoadFn
generateSingleValueFn TypeLoaderGenerateSingleValueFn
}
func (loader *FnTypeLoader) Load(dto *conf.UseTypeDTO) {
loader.loadFn(dto)
}
func (loader *FnTypeLoader) GenerateSingleValue(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
return loader.generateSingleValueFn(config, set)
}
func addCsvLoaderFactory(ctx *TypeLoaderFactoryContext) {
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
src := dto.LoaderArgs.Args["src"].(string)
sep := dto.LoaderArgs.Args["separator"].(string)
content, _ := common.ReadContentFromFileAndSplit(src, sep)
loader.LoaderData = content
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
content := loader.LoaderData.([]string)
return common.GetRandomValue(&content), nil
}
return loader
}
ctx.AddLoaderFactory("csvloader", fn)
}
func addNumberFactory(ctx *TypeLoaderFactoryContext) {
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
return rand.Int63(), nil
}
return loader
}
ctx.AddLoaderFactory("number", fn)
}
func addDateTimeFactory(ctx *TypeLoaderFactoryContext) {
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
return time.Unix(rand.Int63(), rand.Int63()), nil
}
return loader
}
ctx.AddLoaderFactory("datetime", fn)
}
func addStrFormatFactory(ctx *TypeLoaderFactoryContext) {
type strLoaderArgs struct {
Format string
Args []string
}
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
format := dto.LoaderArgs.Args["format"].(string)
argsRaw := dto.LoaderArgs.Args["args"].([]interface{})
args := make([]string, len(argsRaw))
for i, a := range argsRaw {
args[i] = fmt.Sprintf("%s", a)
}
loader.LoaderData = interface{}(strLoaderArgs{Format: format, Args: args})
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
data := loader.LoaderData.(strLoaderArgs)
args := make([]interface{}, len(data.Args))
for i, k := range data.Args {
value, err := set.Values.GetEntryWithName(k)
if err != nil {
// todo do something about this
continue
}
args[i] = value.Value
}
return fmt.Sprintf(data.Format, args...), nil
}
return loader
}
ctx.AddLoaderFactory("strformat", fn)
}
func addAutoIncrementFactory(ctx *TypeLoaderFactoryContext) {
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
loader.LoaderData = 0
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
val := loader.LoaderData.(int)
val++
loader.LoaderData = val
return val, nil
}
return loader
}
ctx.AddLoaderFactory("autoincrement", fn)
}
func addUUIDFactory(ctx *TypeLoaderFactoryContext) {
fn := func() TypeLoader {
loader := &FnTypeLoader{}
loader.loadFn = func(dto *conf.UseTypeDTO) {
}
loader.generateSingleValueFn = func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error) {
return uuid.NewV4().String(), nil
}
return loader
}
ctx.AddLoaderFactory("uuid", fn)
}
func AddDefaultLoaderFactories(ctx *TypeLoaderFactoryContext) {
addCsvLoaderFactory(ctx)
addNumberFactory(ctx)
addStrFormatFactory(ctx)
addDateTimeFactory(ctx)
addAutoIncrementFactory(ctx)
addUUIDFactory(ctx)
}
<file_sep>/core/core_test.go
package core
import (
"testing"
)
func TestLoadJsonConfiguration(t *testing.T) {
config, err := LoadConfigurationFromJson("{\"fields\":[{\"name\":\"test\", \"value\":\"12345\", \"type\": \"number\"}], \"numRows\":50}")
if err != nil {
t.Errorf("Error loading configuration: %s", err)
t.Fail()
}
if config.NumRows != 50 {
t.Errorf("Number of rows didn't match")
t.Fail()
}
if len(config.Fields) != 1 {
t.Errorf("Number of fields didn't match")
t.Fail()
}
field := config.Fields[0]
if field.Name != "test" || field.Type != "number" {
t.Errorf("Something else weird happened; field: %v", field)
t.Fail()
}
}
<file_sep>/core/loaders/loaders.go
package loaders
import (
conf "github.com/elauffenburger/oar/core/configuration"
res "github.com/elauffenburger/oar/core/results"
)
type TypeLoaderFactoryFn func() TypeLoader
type TypeLoaderLoadFn func(dto *conf.UseTypeDTO)
type TypeLoaderGenerateSingleValueFn func(config *conf.Configuration, set *res.ResultsRow) (interface{}, error)
type TypeLoader interface {
Load(dto *conf.UseTypeDTO)
GenerateSingleValue(config *conf.Configuration, set *res.ResultsRow) (interface{}, error)
}
type typeLoader struct {
LoaderData interface{} `json:"-"`
}
type TypeLoaderFactoryContext map[string]TypeLoaderFactoryFn
func (ctx *TypeLoaderFactoryContext) AddLoaderFactory(name string, factory TypeLoaderFactoryFn) {
(*ctx)[name] = factory
}
<file_sep>/test/test-can-convert-to-sql.sql
insert into TestUser ([FirstName],[LastName],[FullName]) values
('Dave','Hoerner','<NAME>'),
('Nenita','Hadfield','<NAME>'),
('Jeremiah','Mulkins','<NAME>'),
('Lonny','Heckendorf','<NAME>'),
('Alfredia','Gonyo','<NAME>'),
('Leone','Fraine','<NAME>'),
('Mariam','Girard','<NAME>'),
('Whitney','Mcvay','<NAME>'),
('Erna','Garcias','<NAME>'),
('Jerrica','Hulme','<NAME>'),
('Lin','Giorgio','<NAME>'),
('Ericka','Terherst','<NAME>'),
('Rob','Mysliwiec','<NAME>'),
('Latina','Darr','<NAME>'),
('Marivel','Stonebraker','<NAME>'),
('Luciana','Schoenhut','<NAME>'),
('Doyle','Musgrave','<NAME>'),
('Eleanore','Collet','<NAME>'),
('Whitney','Medler','<NAME>'),
('Raymond','Escuriex','<NAME>'),
('Nakisha','Caligiuri','<NAME>'),
('Candi','Winans','<NAME>'),
('Cassy','Rockwood','<NAME>'),
('Christoper','Haddan','<NAME>'),
('Grayce','Lowrance','<NAME>'),
('Lewis','Warm','<NAME>'),
('Jeanelle','Salon','<NAME>'),
('Malvina','Lacouette','<NAME>'),
('Jaymie','Kabba','<NAME>'),
('Valentin','Hobbins','<NAME>'),
('Dara','Mahraun','<NAME>'),
('Caprice','Ravago','<NAME>'),
('Reggie','Tangabekyan','<NAME>'),
('Sharee','Peraha','<NAME>'),
('Norah','Neithercutt','Norah Neithercutt'),
('Kimiko','Yett','<NAME>'),
('Theo','Fentress','The<NAME>'),
('Alease','Glowski','<NAME>'),
('Margarita','Davilla','<NAME>'),
('Tierra','Kleen','<NAME>'),
('Marleen','Zeschke','<NAME>'),
('Randy','Shenassa','<NAME>'),
('Gaylord','Lanehart','<NAME>'),
('Lauryn','Schmalz','<NAME>'),
('Sharie','Janszen','<NAME>'),
('Allegra','Brummond','<NAME>'),
('Wynona','Casoria','<NAME>'),
('Charis','Klugh','<NAME>'),
('Deann','Blacksmith','<NAME>'),
('Brian','Hickmon','<NAME>')<file_sep>/core/configuration/fields.go
package configuration
type ConfigurationField struct {
Name string `json:"name"`
Type string `json:"type"`
}
type ConfigurationFields []*ConfigurationField
func NewConfigurationFields() ConfigurationFields {
return make(ConfigurationFields, 0)
}
<file_sep>/oar_test.go
package main
import (
"fmt"
"testing"
"bufio"
"os"
"github.com/elauffenburger/oar/core"
conf "github.com/elauffenburger/oar/core/configuration"
"github.com/elauffenburger/oar/core/output"
res "github.com/elauffenburger/oar/core/results"
)
func TestCanLoadFromFile(t *testing.T) {
config, err := core.LoadConfigurationFromFile("./test/test.json")
if err != nil {
t.Fail()
}
results, err := core.GenerateResults(config)
if err != nil {
t.Fail()
}
if results.NumRows() != len(results.Rows) {
t.Fail()
}
if results.NumRows() != config.NumRows {
t.Fail()
}
}
func TestCanGenerateNames(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
results, _ := core.GenerateResults(config)
entries := results.Rows[0].Values
firstName, err := entries.GetEntryWithName("FirstName")
if err != nil {
t.Fail()
}
lastName, _ := entries.GetEntryWithName("LastName")
fullName, _ := entries.GetEntryWithName("FullName")
if fmt.Sprintf("%s %s", firstName.Value, lastName.Value) != fullName.Value {
t.Fail()
}
}
func TestCanConvertToRows(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
results, _ := core.GenerateResults(config)
numentries := results.NumEntries()
allEntries := make(map[*res.ResultsRowValue]bool)
count := 0
for _, set := range results.Rows {
for _, entry := range set.Values {
allEntries[entry] = false
count++
}
}
if count != numentries {
t.Fail()
}
rows := results.ToRows()
for _, row := range rows {
if row == nil {
t.Fail()
}
for _, entry := range row {
if entry == nil {
t.Fail()
}
// if we've already seen this entry or the entry isn't in the set of all entries, fail
seenEntry, ok := allEntries[entry]
if !ok || seenEntry {
t.Fail()
}
}
}
}
func TestWillGenerateRandomValues(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
results1, _ := core.GenerateResults(config)
results2, _ := core.GenerateResults(config)
n, n2 := len(results1.Rows[0].Values)-1, len(results2.Rows[0].Values)-1
if n != n2 {
t.Fail()
}
if results1.Rows[0].Values[n].Value == results2.Rows[0].Values[n].Value {
t.Fail()
}
if results1.Rows[0].Values[n].Value == results1.Rows[1].Values[n].Value {
t.Fail()
}
}
func TestCanConvertToJsonArray(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
results, _ := core.GenerateResults(config)
jsonformatter := &output.JsonOutputFormatter{}
jsonarray := jsonformatter.ToJsonArray(results)
keys := jsonarray[0].Keys()
key := keys[len(keys)-1]
val1, _ := (*jsonarray[0])[key]
val2, _ := (*jsonarray[1])[key]
if val1 == val2 {
t.Fail()
}
}
func TestCanConvertToSql(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
config.OutputType = conf.SQL
results, err := core.GenerateResults(config)
if err != nil {
t.Fail()
}
formatter := core.GetOutputFormatter(config)
sql := formatter.Format(results)
file, _ := os.Create("./test/test-can-convert-to-sql.sql")
writer := bufio.NewWriter(file)
writer.WriteString(sql)
writer.Flush()
}
func TestCanConvertAndStreamToSql(t *testing.T) {
config, _ := core.LoadConfigurationFromFile("./test/test.json")
config.OutputType = conf.SQL
results, err := core.GenerateResults(config)
if err != nil {
t.Fail()
}
formatter := core.GetOutputFormatter(config)
filename := "./test/test-can-convert-and-stream-to-sql.sql"
os.Create(filename)
file, _ := os.OpenFile(filename, os.O_RDWR, 777)
writer := bufio.NewWriter(file)
formatter.FormatToStream(results, writer)
writer.Flush()
}
<file_sep>/core/core.go
package core
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"path/filepath"
"sync"
conf "github.com/elauffenburger/oar/core/configuration"
"github.com/elauffenburger/oar/core/loaders"
"github.com/elauffenburger/oar/core/output"
res "github.com/elauffenburger/oar/core/results"
)
func LoadConfigurationFromJson(content string) (*conf.Configuration, error) {
empty := &conf.Configuration{}
config := conf.NewConfiguration()
bytes := []byte(content)
err := json.Unmarshal(bytes, config)
if err != nil {
return empty, errors.New("Failed to parse json")
}
// hook for options to modify config
applyOptions(config)
return config, nil
}
func applyOptions(config *conf.Configuration) {
}
func LoadConfigurationFromFile(path string) (*conf.Configuration, error) {
empty := &conf.Configuration{}
if configPath, err := filepath.Abs(path); err == nil {
bytes, _ := ioutil.ReadFile(configPath)
return LoadConfigurationFromJson(string(bytes))
} else {
return empty, errors.New(fmt.Sprintf("Could not load file at path '%s'", path))
}
}
func GenerateResults(config *conf.Configuration) (*res.Results, error) {
return GenerateResultsWithTypeLoaderContext(config, NewTypeLoaderFactoryContext())
}
func GenerateResultsWithTypeLoaderContext(config *conf.Configuration, loaderFactoryContext *loaders.TypeLoaderFactoryContext) (*res.Results, error) {
var wg sync.WaitGroup
numRows := config.NumRows
results := &res.Results{Rows: make(res.ResultsRowList, numRows)}
// generate type loaders to fulfill this config
types := BuildTypeLoadersForConfig(config, loaderFactoryContext)
for i := 0; i < numRows; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
set := &res.ResultsRow{}
for _, field := range config.Fields {
entry := &res.ResultsRowValue{ConfigurationField: *field}
value, err := GenerateValueForField(config, entry.ConfigurationField, set, types)
if err != nil {
// todo handle error
continue
}
entry.Value = value
set.Values = append(set.Values, entry)
}
results.Rows[index] = set
}(i)
}
wg.Wait()
return results, nil
}
func GenerateValueForField(config *conf.Configuration, field conf.ConfigurationField, set *res.ResultsRow, loaders map[string]loaders.TypeLoader) (string, error) {
loader, ok := loaders[field.Type]
if !ok {
return "", errors.New("Failed to find a loader")
}
val, _ := loader.GenerateSingleValue(config, set)
return fmt.Sprintf("%s", val), nil
}
func GetOutputFormatter(config *conf.Configuration) output.OutputFormatter {
outputtype := config.OutputType
switch outputtype {
case conf.JSON:
return &output.JsonOutputFormatter{}
case conf.SQL:
return output.NewSqlOutputFormatter(config.Name)
}
panic("Couldn't figure out which output formatter to use")
}
func BuildTypeLoadersForConfig(config *conf.Configuration, typeLoaderFactoryCtx *loaders.TypeLoaderFactoryContext) map[string]loaders.TypeLoader {
types := make(map[string]loaders.TypeLoader)
// load custom types
for typename, t := range config.Types {
if _, exists := types[typename]; exists {
continue
}
loadername := t.LoaderArgs.Name
factory, ok := (*typeLoaderFactoryCtx)[loadername]
if !ok {
// todo handle unknown loader
continue
}
// create a loader for this type
loader := factory()
loader.Load(&t)
types[typename] = loader
}
return types
}
func NewTypeLoaderFactoryContext() *loaders.TypeLoaderFactoryContext {
ctx := make(loaders.TypeLoaderFactoryContext)
loaders.AddDefaultLoaderFactories(&ctx)
return &ctx
}
<file_sep>/README.md
# Oar

## What does it do?
* Rows
* Saves Jay $10 :P
|
170c9502867b9e63350027358203ee3afe602b6b
|
[
"Markdown",
"SQL",
"Go"
] | 15
|
Go
|
elauffenburger/oar
|
331ffc01278dd9c890959ef699f931278b8ee756
|
aa31bb1a07396a794082ea642903c98ff8e40854
|
refs/heads/master
|
<file_sep>Rails.application.routes.draw do
get 'topics/new'
get 'sessions/new'
root 'pages#index'
get 'pages/help'
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
resources :users
resources :topics
get 'favorites/index'
post'/favorites',to: 'favorites#create'
get 'comments/new'
post '/comments',to: 'comments#create'
end<file_sep>class User < ApplicationRecord
validates :name,
presence: true
validates :email,
presence: true,
format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
validates :password,
length:{ in: 8..32 },
format: {with: /\A[a-zA-Z0-9]+\z/ }
validates :name,
length: {minimum: 1,maximum: 15,}
has_secure_password
has_many :favorites
has_many :favorite_topics, through: :favorites,source:'topic'
has_many :topics
# def topics
# return Topic.where(user_id: user.id)
# end
has_many :comments
end
|
f83fd5702380315cc604e1ee90dfb6134c5c5999
|
[
"Ruby"
] | 2
|
Ruby
|
mirutowa/pictgram
|
2999c4e246db141a4d6f767fbc1da982772ab29f
|
a29b3a486343beac3896cff5c06177f5ccb79b50
|
refs/heads/master
|
<file_sep>def Bisectionmethod(x):
return (x**3)-(2*x**2)-4
a=2
b=3
print("Bisectionmethod")
for i in range(1,20):
x0=(a+b)/2
print(x0)
fx0=Bisectionmethod(x0)
fa=Bisectionmethod(a)
fb=Bisectionmethod(b)
if fa*fx0<0:
b=x0
else:
a=x0
|
47299d5adfa1e941549c75fc07a567b7c8e82264
|
[
"Python"
] | 1
|
Python
|
csebu/first-assignment-on-solution-of-equation-in-one-variable-IsratMili
|
0748658696a929dcfd1ce2e7d1fd1e34f13c0d2e
|
fc59f7a4ca76a00c8f78eeccab886680d208f42c
|
refs/heads/master
|
<repo_name>SudipBiswasRana/first_spring-mvc_sping-data_CRUD_using-Spring-Boot<file_sep>/simple-springmvc-crud-Springdata-jpa/src/main/java/com/rana/mvc/base/controllers/HomeController.java
package com.rana.mvc.base.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String welcomeUser()
{
return "welcome";
}
}
<file_sep>/simple-springmvc-crud-Springdata-jpa/target/classes/application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.datasource.url =jdbc:mysql://localhost:3306/jpadb
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=spring
spring.datasource.password=<PASSWORD>
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
<file_sep>/README.md
# temp
Simple CRUD Web Application Using Spring Boot
Not Complete CRUD
DELETE has some difficulty , yet to resolve .
<file_sep>/simple-springmvc-crud-Springdata-jpa/src/main/java/com/rana/mvc/base/entities/Donor.java
package com.rana.mvc.base.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Table(name="donortable")
public class Donor
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="first_name")
@NotBlank(message="You Must Provide Your First Name")
private String firstName ;
@Column(name="last_name")
@NotBlank(message="You Must Provide Your Last Name")
private String lastName;
@Column(name="phone_no")
private String phNo ;
@Column(name="blood")
@NotBlank
private String bloodTypes;
public Donor() {
}
public Donor(Long id, String firstName, String lastName, String bloodTypes) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.bloodTypes = bloodTypes;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBloodTypes() {
return bloodTypes;
}
public void setBloodTypes(String bloodTypes) {
this.bloodTypes = bloodTypes;
}
public String getPhNo() {
return phNo;
}
public void setPhNo(String phNo) {
this.phNo = phNo;
}
}
|
977ec452e3a62894a821ac1471e5bbfca087229c
|
[
"Markdown",
"Java",
"INI"
] | 4
|
Java
|
SudipBiswasRana/first_spring-mvc_sping-data_CRUD_using-Spring-Boot
|
8e049b5242021b107919aaed35d195b76be75141
|
6afb1acd1ba15565cc1a04c6dd8246b47abddb87
|
refs/heads/master
|
<file_sep>#!/bin/bash/python
import os
def django_setup():
os.system('yum -y install python-pip')
os.system('pip install virtualenv')
os.system('pip install --upgrade pip')
os.system('mkdir /opt/django')
os.chdir('/opt/django')
os.system('sudo useradd jfernando_vazquez')
os.system('yum -y install epel-release')
os.system('yum -y install python34 python-pip')
def django_install():
os.system('virtualenv -p python3 django')
os.chdir('/opt/django/django')
os.system('source bin/activate')
os.system('pip install django")
os.system('django-admin startproject project1')
os.chdir ('..')
os.system('chown -R jfernando_vazquez django')
os.system('myip=$( curl ifconfig.co ) && sed -i "s/ALLOWED_HOSTS = \[\]/ALLOWED_HOSTS = \[\'"$myip"\'\]/g" /opt/django/django/project1/project1/settings.py')
def django_start():
os.chdir('/opt/django/django')
os.system('sudo -u jfernando_vazquez -E sh -c "source /opt/django/django/bin/activate && /opt/django/django/project1/manage.py runserver 0.0.0.0:8000&"')
django_setup()
django_install()
django_start()
<file_sep># Automatation_python_django
Automatation of python and django
|
08507320c434f16c5ebbee489dcfb63d9c6308ab
|
[
"Markdown",
"Python"
] | 2
|
Python
|
Fernvaz/Automatation_python_django
|
2789482f20cf7d2fd218653b222b3d77eb659bbc
|
baa479691ddee01b8781c64e94b309925fe3dcc9
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
public float spd = 1f;
public GameObject manager;
Animator animator;
Vector3 currentEulerAngles;
Quaternion currentRotation;
public float jumpForce = 1f;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
/*
if ( Input.GetMouseButtonDown (0)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f)) {
GameObject box = hit.collider.gameObject;
if (box.tag == "breakable") {
Debug.Log("break");
Destroy(box);
}
if (box.tag == "coin") {
manager.GetComponent<Manager>().increaseCoins();
}
}
}*/
if (Input.GetKey(KeyCode.Space) && Mathf.Abs(gameObject.GetComponent<Rigidbody>().velocity.y) < 0.05f) {
gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
float moveValue = Input.GetAxis("Horizontal");
//Vector3 newPos = gameObject.transform.position;
//newPos += new Vector3(moveValue * moveMultiply,0,0);
//gameObject.transform.position = newPos;
//gameObject.GetComponent<Rigidbody>().AddForce(Vector3.right);
currentEulerAngles = new Vector3(0,0,0);
if (moveValue > 0f){
currentEulerAngles[1] = 90;
currentRotation.eulerAngles = currentEulerAngles;
gameObject.transform.rotation = currentRotation;
moveRight();
}else if (moveValue < 0f) {
currentEulerAngles[1] = -90;
currentRotation.eulerAngles = currentEulerAngles;
gameObject.transform.rotation = currentRotation;
moveLeft();
}
animator.SetFloat("Blend", Mathf.Abs(moveValue));
}
private void moveRight()
{
gameObject.transform.position += new Vector3(spd,0,0);
}
private void moveLeft()
{
gameObject.transform.position -= new Vector3(spd, 0, 0);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "breakable") {
manager.GetComponent<Manager>().addScore(100);
Destroy(collision.gameObject);
}
if (collision.gameObject.tag == "coin") {
manager.GetComponent<Manager>().addScore(100);
manager.GetComponent<Manager>().increaseCoins();
Destroy(collision.gameObject);
}
if (collision.gameObject.tag == "avoid")
{
manager.GetComponent<Manager>().addScore(-10);
}
if (collision.gameObject.tag == "goal")
{
manager.GetComponent<Manager>().addScore(100);
Debug.Log("You Win!");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Manager : MonoBehaviour
{
int score = 0;
int coins = 0;
float currentTime = 0f;
float startingTime = 100f;
public Text timeText;
public Text coinText;
public Text scoreText;
// Start is called before the first frame update
void Start()
{
currentTime = startingTime;
}
// Update is called once per frame
void Update()
{
if ((int)currentTime <= 0) {
Debug.Log("You Failed");
} else {
currentTime -= 1 * Time.deltaTime;
}
string timeTxt = "Time: " + (int)currentTime;
timeText.text = timeTxt;
string coinTxt = "Coin: " + coins;
coinText.text = coinTxt;
string scoreTxt = "Score: " + score;
scoreText.text = scoreTxt;
}
public void increaseCoins() {
coins++;
}
public void addScore(int increaseScore) {
score += increaseScore;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour
{
public Transform playerPos;
// Update is called once per frame
void Update()
{
gameObject.transform.position = new Vector3(playerPos.position[0],6,-12);
}
}
|
c46ef790086e86e739b35280c4229b4b37eb3e35
|
[
"C#"
] | 3
|
C#
|
isaacHuh/platformer
|
6e8be745639a08f40e1d741ef10af05ac27e33b8
|
eb6c6fa2eecf04b7a0ede935676110be7af726bf
|
refs/heads/master
|
<repo_name>pineoc/BattleShipUnity<file_sep>/Assets/CS/SeaControler.cs
using UnityEngine;
using System.Collections;
public class SeaControler : MonoBehaviour {
public GameObject fogPrefab;
public GameObject firePrefab;
GameObject fog;
GameObject fire;
public int occpied; //현재 타일에 배가 있는지 검사할 때 이용
//GameControler gameController; //여기가 아니라 start에서 초기화해야 한다.
void Start()
{
//gameController = GameObject.FindWithTag("GameController").GetComponent<GameControler>();
occpied = 0;
}
//안개 생성
public void fogOn()
{
fog = (GameObject)Instantiate(fogPrefab, transform.position, Quaternion.identity);
}
//안개 제거
public void fogOff()
{
Destroy(fog);
}
//fire particle
public void fireOn()
{
fire = (GameObject)Instantiate(firePrefab, transform.position, Quaternion.Euler(-90, 0, 0));
}
//get occupied value
public int getOcc()
{ return occpied; }
//set occupied value
public void setOcc(int occ)
{ occpied = occ; }
//decrease occupied value
public void decOcc()
{ occpied--; }
//get occupied value with real x, y
public int getOccupiedWithXY(float x, float y)
{
int gridX, gridY;
int occ = 0;
//change to grid x y
if (x > 0)//user grid
{
/*
* x : 1~10
* z : -5~4
*/
gridX = (int)x-1;
gridY = (int)y + 5;
Debug.Log("USER, getOccupiedWithXY): " + x + " " + y);
}
else //ai grid
{
/*
* x : -11~-2
* z : -5~4
*/
Debug.Log("AI, getOccupiedWithXY): " + x + " " + y);
gridX = (int)x +11;
gridY = (int)y + 5;
}
Debug.Log("SEA CON, getOccupiedWithXY): " + gridY + " " + gridX + " occ : " + occ);
return occ;
}
}
<file_sep>/Assets/CS/Ship.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Ship : MonoBehaviour
{
//direction info
private const int EAST = 1;
private const int WEST = 3;
private const int SOUTH = 2;
private const int NORTH = 0;
public int shipID; //ship number
public int x, y; //배 머리 위치
public int direction; //배 방향
public PlaceShipCtrl placeCtrl;
//public GameObject rotateButPrefab;
//GameObject butCanvas;
public int occ; //occupied number
/*
* switch 문 2개 구현 : prefab, 특수능력
* prefab은 swith문 안만들어도..?
*
*/
//turn flags
public const int USER_TURN = 0;
public const int AI_TURN = 1;
public const int USER_BLOCK = -1;
public const int AI_BLOCK = -2;
// Use this for initialization
void Start()
{
//size
int size = shipID / 10;
switch (size)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
//fuction
int func = shipID % 10;
switch (func)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
// Update is called once per frame
void Update()
{
}
public IEnumerator move()
{
//reset occupied
placeCtrl.setOccupied(shipID / 10, direction, x, y, 0);
//드래그 중
Vector3 scrSpace = Camera.main.WorldToScreenPoint(transform.position);
Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, scrSpace.z));
while (Input.GetMouseButton(0))
{
/*****move*****/
Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, scrSpace.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
//curPosition에서 배가 격자를 벗어나지 않는지 검사
if (placeCtrl.inGrid(shipID / 10, direction, (int)curPosition.x, (int)curPosition.z))
{
//배의 위치가 중복되지 않도록 occupied 검사
if (!placeCtrl.isOccupied(shipID / 10, direction, (int)curPosition.x, (int)curPosition.z))
{
//배의 위치 변경. occupied 변경
x = (int)curPosition.x;
y = (int)curPosition.z;
transform.position = placeCtrl.place(shipID / 10, direction, (int)curPosition.x, (int)curPosition.z);
}
}
yield return null;
}
//드래그 끝
//set occupied
placeCtrl.setOccupied(shipID / 10, direction, x, y, 1);
////Rotate 버튼 생성
//butCanvas = (GameObject)Instantiate(rotateButPrefab,
// new Vector3(transform.position.x, 1, transform.position.z),
// Quaternion.AngleAxis(90.0f, new Vector3(1, 0, 0)));
////리스너 장착
//Button[] buts = butCanvas.GetComponentsInChildren<Button>();
//buts[0].onClick.AddListener(() => rotate());
//buts[1].onClick.AddListener(() => cancle());
}
//rotate 버튼 리스너
public void rotate()
{
//reset occupied
placeCtrl.setOccupied(shipID / 10, direction, x, y, 0);
//curPosition에서 배가 격자를 벗어나지 않는지 검사
if (placeCtrl.inGrid(shipID / 10, (direction + 1) % 4, x, y))
{
//배의 위치가 중복되지 않도록 occupied 검사
if (!placeCtrl.isOccupied(shipID / 10, (direction + 1) % 4, x, y))
{
//방향 변수 변경
direction = (direction + 1) % 4;
//회전
transform.rotation = Quaternion.AngleAxis(direction * 90.0f, Vector3.up);
//배의 위치 변경
transform.position = placeCtrl.place(shipID / 10, direction, x, y);
}
else
{
DialogCtrl dialog = Instantiate(placeCtrl.DialogPrefab).GetComponent<DialogCtrl>();
dialog.setLifetime(2.0f);
dialog.setText("다른 배가 있어 회전할 수 없습니다.");
}
}
else
{
DialogCtrl dialog = Instantiate(placeCtrl.DialogPrefab).GetComponent<DialogCtrl>();
dialog.setLifetime(2.0f);
dialog.setText("격자 밖으로 벗어날 수 있어\n회전할 수 없습니다.");
}
//set occupied
placeCtrl.setOccupied(shipID / 10, direction, x, y, 1);
}
//public void cancle()
//{
// Destroy(butCanvas);
//}
void OnTriggerEnter(Collider other)
{
//if (other.gameObject.tag == "Bullet") Destroy(other.gameObject);
//notify hit
//OnNotify();
}
/* void OnNotify()
{
//notify to game controller
gameController = GameObject.FindWithTag("GameController").GetComponent<GameControler>();
int whoseTurn = gameController.GetTurn();
switch (whoseTurn)
{
case USER_TURN:
break;
case AI_TURN:
break;
case USER_BLOCK:
gameController.turn = USER_TURN;
break;
case AI_BLOCK:
gameController.turn = AI_TURN;
break;
}
}*/
}
<file_sep>/Assets/CS/AIControler.cs
using UnityEngine;
using System.Collections;
public class AIControler : MonoBehaviour {
int turn;
bool firstHit; //두 번 발사하는 배의 경우 몇 번째 발사인지 기록
public GameObject DialogPrefab;
//shot bullet
public GameControler gc;
public Camera camera;
public GameObject bulletPrefab;
public GameObject arrowPrefab; //맞을 지점을 표시할 프리팹
//ai turn
public const int AI_TURN = 1;
public const int USER_TURN = 0;
public const int AI_BLOCK = -2;
//previous target point
int prevX, prevY, prevR;
bool hit;
// Use this for initialization
void Start () {
turn = 5;
gc = GameObject.FindWithTag("GameController").GetComponent<GameControler>();
firstHit = true;
//prev point init
prevX = -1;
prevY = -1;
prevR = -1;
hit = false;
}
// Update is called once per frame
void Update () {
if (gc.turn == AI_TURN)
{
DialogCtrl dialog = Instantiate(DialogPrefab).GetComponent<DialogCtrl>();
dialog.setLifetime(1.0f);
dialog.setText("AI 턴 입니다.");
gc.turn = AI_BLOCK; //block turn
int time = Random.Range(2, 3);
Invoke("shooting", time);
}
}
void shooting()
{
selectTargetPoint();
shot(prevX, prevY);
}
void selectTargetPoint()
{
//target point x y - in user grid
int userGridX, userGridY;
//init
userGridX = 0;
userGridY = 0;
if (prevR == -1 && hit == false)
{
//first shoot - random
userGridX = Random.Range(0,10);
userGridY = Random.Range(0, 10);
//Debug.Log(userGridX + " real " + userGridY);
}
else if(prevR != -1 && hit == false){
userGridX = Random.Range(0, 10);
userGridY = Random.Range(0, 10);
}
prevX = userGridX;
prevY = userGridY;
}
public void shot(int Gx, int Gy)
{
//Gx, Gy -> real x z
//Gx : 0 -> 1
//Gy : 0 -> -5
float realX = Gx + 1;
float realZ = Gy - 5;
//탄환 생성
GameObject bullet = (GameObject)Instantiate(bulletPrefab, new Vector3(-11, 1, 0), Quaternion.identity);
//탄환 코드에 변수값 전달 -> 탄환 스스로 발사
Bullet bc = bullet.GetComponent<Bullet>();
bc.from = new Vector3(-12, 2, 0);
//bullet target transform
//var newTrans = new GameObject().transform;
//Vector3 targetVec = new Vector3(realX, 0, realZ);
//Debug.Log("input : " + Gx + " " + Gy + " real : " + realX + " " + realZ);
//newTrans.position = targetVec;
bc.to = new Vector3(realX, 0, realZ);
//print(realX + " " + realZ);
print(gc.ships[turn].shipID);
//두 발 쏘는 특수기능 처리
if (gc.ships[turn].shipID % 10 == 3) //두 발 쏘기
{
//두 발 중 첫 발
if (firstHit == true)
{
print("firstHit");
firstHit = false;
bc.turnChange = false;
}
else
{
print("secondHit");
//두 발 중 두번째 발
firstHit = true;
bc.turnChange = true;
changeTurn();
}
}
else
{
//한 발 쏘기
bc.turnChange = true;
changeTurn();
}
}
void changeTurn()
{
turn++;
if (turn > 9)
turn = 5;
}
}
|
e35ccea728f5b441e75c340b1f511853e0c4e60e
|
[
"C#"
] | 3
|
C#
|
pineoc/BattleShipUnity
|
4758bbb16ff6a9b9639c94f14888bf8700dbe65a
|
16245aaed4befdc2ba03e8ad3447f612d59a7ef3
|
refs/heads/master
|
<file_sep># Common Commands
alias q=’exit’
alias c=’clear’
alias h=’history’
alias cs=’clear;ls’
alias p=’cat’
alias pd=’pwd’
alias lsa=’ls -a’
alias lsl=’ls -l’
alias pd=’pwd’
alias t=’time’
alias k='kill'
alias null=’/dev/null’
# Directories
alias home='cd ~'
alias root='cd /'
alias dtop='cd ~/Desktop'
# Common project directories
alias o=open
alias ..='cd ..'
alias ...='cd ..; cd ..'
alias ....='cd ..; cd ..; cd ..'
# Github
alias g=’git’
alias st=’git status’
alias com=’git commit -m’
alias clone=’git clone’
alias sth=’git stash’
alias lg=’git log’
alias u=’git add -u’
alias all=’git add .’
# Typos
alias givm='gvim'
alias cta='cat'
alias gerp='grep'
alias sl='ls'
# Fun
alias meow='cat'
|
3d4c8694d15709bdbef2f0a2464f2813c97cd20a
|
[
"Shell"
] | 1
|
Shell
|
KMH19/bashrc
|
86d69f98656f91f74df1586f8d40479248979eb5
|
bbe1db48f30ee57deccdf72ffd6ae702f6358421
|
refs/heads/master
|
<file_sep><?php
require"curl.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movies</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" >
</head>
<body>
<nav class="navbar navbar-expand-lg ">
<a class="navbar-brand" href="index.php">Movies</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form method="GET" action="pages/search_result.php" class="form-inline my-2 my-lg-0">
<input name="q" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- end nav -->
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="css/images/1.jpg" alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="css/images/2.jpg" alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="css/images/3.jpg" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- end slider -->
<section class="top-rate">
<div class="container">
<h2><span>|</span>Top rated movies</h2>
<div class="row text-center">
<?php
$data=movie();
for ($i=0;$i < 4; $i++) {
$title=$data['results'][$i]['title'];
$poster_path=$data['results'][$i]['poster_path'];
$vote_average=$data['results'][$i]['vote_average'];
$id=$data['results'][$i]['id'];
echo '
<div class="col-sm-3">
<a href="pages/movie.php?id='.$id.'"><img class="img-thumbnail" src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/'.$poster_path.'"></a>
<p class="lead">'.$title.'</p>
<p><span>'.$vote_average.'</span> Vote</p>
</div>
';
}
?>
</div>
<!-- end row 1 -->
<div class="view text-center">
<a class="view-all" href="pages/all_movies.php">View all</a>
</div>
<hr>
</div>
</section>
<!-- end top-movies-rate section -->
<section class="top-rate">
<div class="container">
<h2><span>|</span>Top rated TV shows</h2>
<div class="row text-center">
<?php
$tv=tv();
for ($i=0;$i < 4; $i++) {
$title=$tv['results'][$i]['original_name'];
$poster_path=$tv['results'][$i]['poster_path'];
$vote_average=$tv['results'][$i]['vote_average'];
$id=$tv['results'][$i]['id'];
echo '
<div class="col-sm-3">
<a href="pages/tv.php?id='.$id.'"><img class="img-thumbnail" src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/'.$poster_path.'"></a>
<p class="lead">'.$title.'</p>
<p><span>'.$vote_average.'</span> Vote</p>
</div>
';
}
?>
</div>
<!-- end row 1 -->
<div class="view text-center">
<a class="view-all" href="pages/all_tv_show.php">View all</a>
</div>
<hr>
</div>
</section>
<!-- end TV-show section -->
<section class="top-rate">
<div class="container">
<h2><span>|</span>Trending</h2>
<div class="row text-center">
<?php
$trend=trend();
for ($i=0;$i < 4; $i++) {
$title=$trend['results'][$i]['title'];
$poster_path=$trend['results'][$i]['poster_path'];
$vote_average=$trend['results'][$i]['vote_average'];
$id=$trend['results'][$i]['id'];
echo '
<div class="col-sm-3">
<a href="pages/movie.php?id='.$id.'"><img class="img-thumbnail" src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/'.$poster_path.'"></a>
<p class="lead">'.$title.'</p>
<p><span>'.$vote_average.'</span> Vote</p>
</div>
';
}
?>
</div>
<!-- end row 1 -->
<div class="view text-center">
<a class="view-all" href="pages/trend.php">View all</a>
</div>
</div>
</section>
<div class="container">
<section class="footer">
<p>Copyright © movies.net All Rights Reserved</p>
</section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep># Movies
old project to get movies & series detils .I used <code>themoviedb API</code>
<file_sep><?php
$url="https://api.themoviedb.org/3/trending/movie/week?api_key=0d2861372b5b46a514fa633fee10594f";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data=json_decode($result, true);
$count=count($data['results']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movies</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="../css/style.css" >
</head>
<body>
<nav class="navbar navbar-expand-lg ">
<a class="navbar-brand" href="../index.php">Movies</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
<form method="GET" action="search_result.php" class="form-inline my-2 my-lg-0">
<input name="q" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<section class="all_movies">
<div class="container">
<div class="row text-center">
<?php
for ($i=0;$i <$count; $i++) {
$title=$data['results'][$i]['original_title'];
$poster_path=$data['results'][$i]['poster_path'];
$vote_average=$data['results'][$i]['vote_average'];
$id=$data['results'][$i]['id'];
echo '
<div class="col-sm-3">
<a href="movie.php?id='.$id.'"><img class="img-thumbnail" src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/'.$poster_path.'"></a>
<p class="lead">'.$title.'</p>
<p><span>'.$vote_average.'</span> Vote</p>
</div>
<hr>
';
}
?>
</div>
</div>
</section>
</body>
</html><file_sep><?php
function movie(){
$url="https://api.themoviedb.org/3/movie/top_rated?api_key=0d2861372b5b46a514fa633fee10594f&language=en-US";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data=json_decode($result, true);
return $data;
}
function tv(){
$url="https://api.themoviedb.org/3/tv/top_rated?api_key=0d2861372b5b46a514fa633fee10594f&language=en-US";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$tv=json_decode($result, true);
return $tv;
}
function trend(){
$url="https://api.themoviedb.org/3/trending/all/week?api_key=0d2861372b5b46a514fa633fee10594f&language=en-US";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$trend=json_decode($result, true);
return $trend;
}
?><file_sep><?php
$id=$_GET['id'];
$data=json_decode(file_get_contents("https://api.themoviedb.org/3/movie/".$id."?api_key=0d2861372b5b46a514fa633fee10594f&language=en-US"),true);
$title=$data['original_title'];
$poster_path=$data['poster_path'];
$vote=$data['vote_average'];
$overview=$data['overview'];
$release_date=$data['release_date'];
$original_language=$data['original_language'];
$genres=$data['genres'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movies</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="../css/style.css" >
</head>
<body>
<nav class="navbar navbar-expand-lg ">
<a class="navbar-brand" href="../index.php">Movies</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
<form method="GET" action="search_result.php" class="form-inline my-2 my-lg-0">
<input name="q" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<section class="info text-center">
<div class="container">
<div class="row">
<?php
echo '
<div class="col-sm-3">
<img class="img-thumbnail" src="https://image.tmdb.org/t/p/w300_and_h450_bestv2/'.$poster_path.'">
<h3>'.$title.'</h3>
</div>
<div class="col-sm-8">
<h3>Overview</h3>
<p class="lead">'.$overview.'</p>
<ul class="list-unstyled">
<li>Vote: <span>'.$vote.'</span></li>
<li>Release Date: <span>'.$release_date.'</span></li>
<li>Original Language: <span>'.$original_language.'</span></li>
<li>genres:
';
for ($i=0; $i <count($genres) ; $i++) {
echo'<span>'.$genres[$i]['name'].' </span>';
}
echo '
</li>
</ul>
</div>
';
?>
</div>
</div>
</section>
</body>
</html>
|
5c9d898310cfc08ddbdd6ba0ed29c8b79fb3298f
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
karrarjasim/Movies
|
eaaafd19337fe139b85c202dd0b69631727c8f5e
|
d0771ae8bbacfa7a3fa8f09d3c8bf0f063c93b6b
|
refs/heads/master
|
<repo_name>mateusmcg/poker-azure-devops<file_sep>/PokerAzureDevops/Util/Util.cs
using System;
using System.Collections.Generic;
using PokerAzureDevops.Enums;
using PokerAzureDevops.Model;
namespace PokerAzureDevops.Util
{
public static class Util
{
public static List<Carta> GetBaralho()
{
return new List<Carta>
{
new Carta { NumCarta = NumCarta.Dois, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Tres, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Quatro, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Cinco, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Seis, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Sete, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Oito, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Nove, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Dez, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Valete, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Dama, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Rei, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.As, Naipe = Naipes.Copa },
new Carta { NumCarta = NumCarta.Dois, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Tres, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Quatro, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Cinco, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Seis, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Sete, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Oito, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Nove, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Dez, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Valete, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Dama, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Rei, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.As, Naipe = Naipes.Espadas },
new Carta { NumCarta = NumCarta.Dois, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Tres, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Quatro, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Cinco, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Seis, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Sete, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Oito, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Nove, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Dez, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Valete, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Dama, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Rei, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.As, Naipe = Naipes.Ouro },
new Carta { NumCarta = NumCarta.Dois, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Tres, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Quatro, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Cinco, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Seis, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Sete, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Oito, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Nove, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Dez, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Valete, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Dama, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.Rei, Naipe = Naipes.Paus },
new Carta { NumCarta = NumCarta.As, Naipe = Naipes.Paus },
};
}
}
}<file_sep>/PokerAzureDevops.Tests/PokerDomainTests.cs
using System.Collections.Generic;
using NUnit.Framework;
using PokerAzureDevops.Domain;
using PokerAzureDevops.Enums;
using PokerAzureDevops.Model;
using PokerAzureDevops.Util;
namespace Tests
{
[TestFixture]
public class PokerDomainTests
{
private PokerDomain pokerDomain;
[SetUp]
public void Setup()
{
pokerDomain = new PokerDomain();
}
[Test]
public void ShouldReturnFiveCardsAndDecreaseBaralhoCount()
{
var baralho = Util.GetBaralho();
var cartasJogador1 = pokerDomain.DistribuirCartas(baralho);
var cartasJogador2 = pokerDomain.DistribuirCartas(baralho);
Assert.IsNotNull(cartasJogador1);
Assert.IsNotNull(cartasJogador2);
Assert.AreEqual(5, cartasJogador1.Count);
Assert.AreEqual(5, cartasJogador2.Count);
Assert.AreEqual(42, baralho.Count);
}
[Test]
public void ShouldReturnAWinner()
{
var winner = pokerDomain.IniciarPartida(new Jogador("Jogador 1"), new Jogador("Jogador 2"));
Assert.NotNull(winner);
}
}
}<file_sep>/PokerAzureDevops/Enums/NumCarta.cs
namespace PokerAzureDevops.Enums
{
public enum NumCarta
{
Dois = 2,
Tres = 3,
Quatro = 4,
Cinco = 5,
Seis = 6,
Sete = 7,
Oito = 8,
Nove = 9,
Dez = 10,
Valete = 11,
Dama = 12,
Rei = 13,
As = 14
}
}<file_sep>/AtividadeAula05/Respostas.md
# Repostas Exercício 1
## Integração Contínua:
- Na integração contínua, o desenvolvedor realiza a integração do código criado ou
modificado ao projeto principal na mesma frequência que as funcionalidade são criadas, com a integração sendo feita uma ou mais vezes durante o dia.
Um dos principais objetivos da integração contínua, é a certificação que as alterações ou funcionalidades criadas não estão gerando defeitos no projeto existente. Essa integração pode ser feita através de processos manuais ou automatizados, podendo utilizar ferramentas para auxiliar nessa integração contínua.
Para que a integração contínua seja feita corretamente, a equipe tem que trabalhar em conjunto, e utilizando um controle de versão. Esse controle de versão é essencial para fluxo do trabalho da equipe de desenvolvimento, fazendo com que as informações sejam compartilhadas, evitando o retrabalho.
Existem várias ferramentas que realizam esse controle de versão, permitindo que os desenvolvedores trabalhem em conjunto, acessando, visualizando, modificando e enviando novos códigos para o servidor responsável pelo versionamento do sistema.
Existem metodologias que têm uma visão da entrega completa do código, somente depois que o desenvolvedor terminar e testar todo o projeto ou módulo, ele será entregue para ser colocado em produção. Essa metodologia pode causar grande perda da qualidade do produto, gerando retrabalho e insatisfação com o produto.
A integração contínua resolve esse problema, com as pequenas entregas, automatização de teste, facilitando a localização e correção de erros, automatização de builds, evitando erros em processos de builds, por serem automáticos e não ter influência de processos manuais. Pois em processos manuais, cada pessoa pode fazer o build de forma diferente, possibilitando falhas nas entregas e a não detecção de erros.
**Benefícios de integração contínua:**
- Contribui com a produtividade dos desenvolvedores, liberando eles das tarefas manuais e incentivando em ações que contribui para a melhoria de código e identificação de erros.
- Com testes mais frequentes, contribui para descobrir bugs e evitar futuros problemas com o produto.
- Distribuição mais frequente de atualizações do produto para os clientes.
## Entrega Contínua:
- São entregas feitas em pequenas partes, garantindo uma qualidade e rapidez na entrega do produto. Ao invés da equipe de desenvolvimento fazer uma só entrega do produto finalizado, dando a possibilidade de entregar um produto com baixa qualidade, a equipe pode fazer pequenas entregas, onde será mais fácil a manutenção, identificação de melhorias, garantindo uma qualidade na entrega dessas pequenas partes do produto.
Umas das principais características da entrega contínua, são o uso de automação de testes, infraestrutura e deploy, viabilizando mais velocidade nos versionamentos. Algumas das vantagens da entrega contínua são a minimização de riscos nos lançamentos, mais velocidade, mais qualidade, menores custos, equipe mais satisfeita:
- **Minimização de riscos nos lançamentos: **
Entrega contínua permite deploys constantes e rápidos, com deploys menores, correm menos riscos de erros e podem ser feitos a qualquer momento, dependendo da demanda, e muitos nem são percebidos pelos usuários.
- **Mais velocidade:**
Entrega contínua elimina as fases de integração, testes e correção, que podem gerar atrasos na entrega do produto. A equipe trabalha em conjunto, dentro do conceito DevOps, onde os processos de homologação de ambientes, testes e deploy são automatizados, ganhando tempo e reduzindo o retrabalho.
- **Mais qualidade:**
Com os testes automatizados, os erros são encontrados mais rapidamentes e os desenvolvedores conseguem aprofundar mais no desenvolvimento, garantindo a qualidade final do produto. Outros tipos de teste podem ser mais explorados, garantindo uma cobertura maior de código, performance, usabilidade, segurança e dentre outras qualidades.
- **Menores custos:**
Com a eliminação de trabalhos repetitivos de testes, infra e deploy, o trabalho da equipe fica mais eficiente, reduzindo os custos.
- **Equipe mais satisfeita:**
Ao liberar os desenvolvedores de realizarem ciclos de testes repetitivos, proporciona mais satisfação e tempo para que a equipe possa pensar em novas ideias e melhorias no produto.
Mas para que a entrega contínua seja feita corretamente, é necessário uma maior participação de toda a equipe e que estejam preparados para lidar com grande fluxo de entregas e responsabilidades. Outro pilar da entrega contínua, é a participação dos responsáveis pelo produto, atuando nos processos de validação do produto.
## Implantação Contínua:
-
# Repostas Exercício 2
a) A startup ABC trabalha com soluções PHP, MYSQL e quer usar uma infraestrutura baseada em Docker e Kubernetes.
CI / CD para contêineres - É possível obter clusters de contêineres replicáveis e gerenciáveis.
Em alguns casos, talvez você não consiga atribuir a função necessária à entidade de serviço AKS gerada automaticamente, concedendo-lhe acesso ao ACR. Por exemplo, devido ao modelo de segurança da sua organização, talvez você não tenha permissões suficientes em seu locatário do Azure Active Directory para atribuir uma função à entidade de serviço gerada pelo AKS. Atribuir uma função a uma entidade de serviço exige que sua conta do Azure AD tenha permissão de gravação para seu locatário do Azure AD. Se você não tiver permissão, poderá criar uma nova entidade de serviço e conceder acesso ao registro do contêiner usando um segredo de recepção de imagem do Kubernetes.
b) A empresa XYZ trabalha com Java e já possui o Jenkins como solução de CI para automação de seus builds. Visão geral da CI/CD de Infraestrutura Imutável usando Jenkins e Terraform na Arquitetura virtual do Azure. O servidor Jenkins delega trabalho para um ou mais agentes para permitir que uma única instalação Jenkins hospede um número grande de projetos ou para fornecer ambientes diferentes, necessários para compilações ou testes.
c) A empresa XPTO não tem profissional que conheça de infraestrutura com profundidade e que implantar um pipeline CD do DevOps com o menor custo possível.
CI / CD para aplicativos da Web do Azure - O Azure Web Apps é uma maneira rápida e simples. Neste exemplo, o pipeline de CI/CD implanta um aplicativo Web do .NET de duas camadas para o Serviço de Aplicativo do Azure.
<file_sep>/PokerAzureDevops/Model/Carta.cs
using PokerAzureDevops.Enums;
namespace PokerAzureDevops.Model
{
public class Carta
{
public NumCarta NumCarta { get; set; }
public Naipes Naipe { get; set; }
}
}<file_sep>/README.md
# poker-azure-devops <file_sep>/PokerAzureDevops.Tests/HandCheckerTests.cs
using System.Collections.Generic;
using NUnit.Framework;
using PokerAzureDevops.Enums;
using PokerAzureDevops.Model;
using PokerAzureDevops.Util;
namespace PokerAzureDevops.Tests
{
[TestFixture]
public class HandCheckerTests
{
[Test]
public void ShouldCheckIfIsHighCard()
{
var cartasJogador1 = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.Dama},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Seis},
};
var cartasJogador2 = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.Tres},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Cinco},
};
var jogador1 = new Jogador("Fulano")
{
Cartas = cartasJogador1
};
var jogador2 = new Jogador("Fulano 2")
{
Cartas = cartasJogador2
};
var jogadorHighCard = HandChecker.CheckHighCard(jogador1, jogador2);
Assert.AreEqual(jogadorHighCard, jogador1);
}
[Test]
public void ShouldCheckIfIsAPair()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Oito},
};
var cartasIguais = HandChecker.IsPair(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAPair()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Nove},
};
var cartasIguais = HandChecker.IsPair(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsTwoPairs()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Oito},
};
var cartasIguais = HandChecker.IsTwoPairs(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotTwoPairs()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Oito},
};
var cartasIguais = HandChecker.IsTwoPairs(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsATrinca()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Oito},
};
var cartasIguais = HandChecker.IsTrinca(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotATrinca()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Tres},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Oito},
};
var cartasIguais = HandChecker.IsTrinca(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsAStraight()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.Nove},
new Carta() { NumCarta = NumCarta.Dez},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Dama},
};
var cartasIguais = HandChecker.IsStraight(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAStraight()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Oito},
new Carta() { NumCarta = NumCarta.Nove},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Valete},
new Carta() { NumCarta = NumCarta.Dama},
};
var cartasIguais = HandChecker.IsStraight(cartas);
Assert.False(cartasIguais);
}
[Test]
public void ShouldCheckIfItIsNotAFlush()
{
var cartas = new List<Carta>
{
new Carta() { Naipe = Naipes.Espadas},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa}
};
var cartasIguais = HandChecker.IsFlush(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsAFlush()
{
var cartas = new List<Carta>
{
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa},
new Carta() { Naipe = Naipes.Copa}
};
var cartasIguais = HandChecker.IsFlush(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsAFullHouse()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dama},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dama},
};
var cartasIguais = HandChecker.IsFullHouse(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAFullHouse()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dama},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dois},
new Carta() { NumCarta = NumCarta.Dama},
};
var cartasIguais = HandChecker.IsFullHouse(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsAQuadra()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.Dama},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
};
var cartasIguais = HandChecker.IsQuadra(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAQuadra()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
new Carta() { NumCarta = NumCarta.As},
};
var cartasIguais = HandChecker.IsQuadra(cartas);
Assert.IsFalse(cartasIguais);
}
[Test]
public void ShouldCheckIfIsARoyalFlush()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Dez, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Valete, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Dama, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Rei, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.As, Naipe = Naipes.Ouro},
};
var cartasIguais = HandChecker.IsRoyalFlush(cartas);
Assert.True(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAARoyalFlushByNaipes()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Dez, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Valete, Naipe = Naipes.Espadas},
new Carta() { NumCarta = NumCarta.Dama, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Rei, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.As, Naipe = Naipes.Ouro},
};
var cartasIguais = HandChecker.IsRoyalFlush(cartas);
Assert.False(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAARoyalFlushByNumCard()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Dez, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Cinco, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Dama, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Rei, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.As, Naipe = Naipes.Ouro},
};
var cartasIguais = HandChecker.IsRoyalFlush(cartas);
Assert.False(cartasIguais);
}
[Test]
public void ShouldCheckIfIsAStraightFlush()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Dois, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Tres, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Quatro, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Cinco, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Seis, Naipe = Naipes.Ouro},
};
var cartasIguais = HandChecker.IsStraightFlush(cartas);
Assert.IsTrue(cartasIguais);
}
[Test]
public void ShouldCheckIfIsNotAStraightFlush()
{
var cartas = new List<Carta>
{
new Carta() { NumCarta = NumCarta.Dez, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Valete, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Dama, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.Rei, Naipe = Naipes.Ouro},
new Carta() { NumCarta = NumCarta.As, Naipe = Naipes.Ouro},
};
var cartasIguais = HandChecker.IsStraightFlush(cartas);
Assert.IsFalse(cartasIguais);
}
}
}<file_sep>/PokerAzureDevops/Enums/Naipes.cs
namespace PokerAzureDevops.Enums
{
public enum Naipes
{
Ouro,
Copa,
Espadas,
Paus
}
}<file_sep>/PokerAzureDevops/Model/Jogador.cs
using System.Collections.Generic;
using PokerAzureDevops.Enums;
using PokerAzureDevops.Util;
namespace PokerAzureDevops.Model
{
public class Jogador
{
public Jogador(string nome)
{
this.Nome = nome;
}
public List<Carta> Cartas { get; set; }
public string Nome { get; set; }
public Hands GetHand()
{
if (HandChecker.IsRoyalFlush(this.Cartas))
return Hands.RoyalFlush;
if (HandChecker.IsStraightFlush(this.Cartas))
return Hands.StraightFlush;
if (HandChecker.IsQuadra(this.Cartas))
return Hands.Quadra;
if (HandChecker.IsFullHouse(this.Cartas))
return Hands.FullHouse;
if (HandChecker.IsFlush(this.Cartas))
return Hands.Flush;
if (HandChecker.IsStraight(this.Cartas))
return Hands.Straight;
if (HandChecker.IsTrinca(this.Cartas))
return Hands.Trinca;
if (HandChecker.IsTwoPairs(this.Cartas))
return Hands.TwoPair;
if (HandChecker.IsPair(this.Cartas))
return Hands.Pair;
return Hands.HighCard;
}
public override string ToString()
{
var result = "";
foreach (var carta in this.Cartas)
{
var cartaStr = carta.NumCarta.ToString() + "(" + carta.Naipe.ToString() + ")";
result = result + " / " + cartaStr;
}
return result;
}
}
}<file_sep>/PokerAzureDevops.Tests/UtilTests.cs
using NUnit.Framework;
using PokerAzureDevops.Enums;
using System.Linq;
namespace PokerAzureDevops.Tests
{
[TestFixture]
public class UtilTests
{
[Test]
public void ShouldReturnADeckWith52Cards()
{
var baralho = Util.Util.GetBaralho();
Assert.IsNotNull(baralho);
Assert.AreEqual(52, baralho.Count);
}
[Test]
public void ShouldReturnADeckWith13CopaCards()
{
var baralho = Util.Util.GetBaralho();
var copas = baralho.Where(carta => carta.Naipe == Naipes.Copa);
Assert.IsNotNull(copas);
Assert.AreEqual(13, copas.Count());
}
[Test]
public void ShouldReturnADeckWith13EspadasCards()
{
var baralho = Util.Util.GetBaralho();
var espadas = baralho.Where(carta => carta.Naipe == Naipes.Espadas);
Assert.IsNotNull(espadas);
Assert.AreEqual(13, espadas.Count());
}
[Test]
public void ShouldReturnADeckWith13OuroCards()
{
var baralho = Util.Util.GetBaralho();
var ouro = baralho.Where(carta => carta.Naipe == Naipes.Ouro);
Assert.IsNotNull(ouro);
Assert.AreEqual(13, ouro.Count());
}
[Test]
public void ShouldReturnADeckWith13PausCards()
{
var baralho = Util.Util.GetBaralho();
var paus = baralho.Where(carta => carta.Naipe == Naipes.Paus);
Assert.IsNotNull(paus);
Assert.AreEqual(13, paus.Count());
}
}
}<file_sep>/PokerAzureDevops/Model/Partida.cs
using PokerAzureDevops.Enums;
namespace PokerAzureDevops.Model
{
public class Partida
{
public Jogador Vencedor { get; set; }
public Hands MaoVencedora { get; set; }
}
}<file_sep>/PokerAzureDevops/Util/HandChecker.cs
using System.Collections.Generic;
using PokerAzureDevops.Model;
using System.Linq;
using PokerAzureDevops.Enums;
namespace PokerAzureDevops.Util
{
public static class HandChecker
{
public static Jogador CheckHighCard(Jogador jogador1, Jogador jogador2)
{
var highCardJogador1 = jogador1.Cartas.OrderByDescending(carta => carta.NumCarta).First();
var highCardJogador2 = jogador2.Cartas.OrderByDescending(carta => carta.NumCarta).First();
if (highCardJogador1.NumCarta > highCardJogador2.NumCarta)
return jogador1;
else
return jogador2;
}
public static bool IsPair(List<Carta> cartas)
{
return CheckHandAndQuantity(cartas, HandCheck.Pair, 1);
}
public static bool IsTwoPairs(List<Carta> cartas)
{
return CheckHandAndQuantity(cartas, HandCheck.Pair, 2);
}
public static bool IsTrinca(List<Carta> cartas)
{
return CheckHandAndQuantity(cartas, HandCheck.Trinca, 1);
}
public static bool IsStraight(List<Carta> cartas)
{
var cartasEmOrdem = cartas.OrderBy(carta => carta.NumCarta).ToList();
var valorPrimeiraCarta = (int)cartasEmOrdem.First().NumCarta;
for (int i = 1; i < cartasEmOrdem.Count; i++)
{
var valorCartaAtual = (int)cartasEmOrdem[i].NumCarta;
if ((valorPrimeiraCarta + i) != valorCartaAtual)
{
return false;
}
}
return true;
}
public static bool IsFlush(List<Carta> cartas)
{
return !cartas.Any(o => o.Naipe != cartas.First().Naipe);
}
public static bool IsFullHouse(List<Carta> cartas)
{
return IsPair(cartas) && IsTrinca(cartas);
}
public static bool IsQuadra(List<Carta> cartas)
{
return CheckHandAndQuantity(cartas, HandCheck.Quadra, 1);
}
public static bool IsStraightFlush(List<Carta> cartas)
{
return IsFlush(cartas) && IsStraight(cartas) && !IsRoyalFlush(cartas);
}
public static bool IsRoyalFlush(List<Carta> cartas)
{
return IsFlush(cartas) && IsRoyalStraight(cartas);
}
private static bool IsRoyalStraight(List<Carta> cartas)
{
var cartasEmOrdem = cartas.OrderBy(carta => carta.NumCarta).ToList();
return IsStraight(cartasEmOrdem) && cartasEmOrdem.First().NumCarta == NumCarta.Dez;
}
private static bool CheckHandAndQuantity(List<Carta> cartas, HandCheck hand, int qtd)
{
var groups = cartas.GroupBy(carta => carta.NumCarta).ToList();
var pairsCount = 0;
groups.ForEach(group =>
{
if (group.Count() == (int)hand)
{
pairsCount++;
}
});
return pairsCount == qtd;
}
}
}<file_sep>/PokerAzureDevops/Enums/HandCheck.cs
namespace PokerAzureDevops.Enums
{
public enum HandCheck
{
Pair = 2,
Trinca = 3,
Quadra = 4
}
}<file_sep>/PokerAzureDevops/Program.cs
using System;
using PokerAzureDevops.Domain;
using PokerAzureDevops.Model;
namespace PokerAzureDevops
{
public class Program
{
static void Main(string[] args)
{
var domain = new PokerDomain();
Console.WriteLine("Gerando jogadores!");
Console.WriteLine("Iniciando Partida!");
var jogador1 = new Jogador("Jogador 1");
var jogador2 = new Jogador("Jogador 2");
var partida = domain.IniciarPartida(jogador1, jogador2);
if (partida == null)
{
System.Console.WriteLine("\nHouve um empate de High Card! Cartas:\n");
System.Console.WriteLine(string.Format("Jogador1: {0} \nJogador2: {1} ", jogador1.ToString(), jogador2.ToString()));
return;
}
Console.WriteLine(string.Format("\nO vencedor é: {0} ({1})", partida.Vencedor.Nome, partida.MaoVencedora.ToString()));
System.Console.WriteLine(string.Format("\nCartas Jogador1: {0} \nCartas Jogador2: {1} ", jogador1.ToString(), jogador2.ToString()));
Console.ReadKey();
}
}
}
<file_sep>/PokerAzureDevops/Domain/PokerDomain.cs
using System.Collections.Generic;
using PokerAzureDevops.Model;
using System.Linq;
using PokerAzureDevops.Enums;
using System;
using PokerAzureDevops.Util;
namespace PokerAzureDevops.Domain
{
public class PokerDomain
{
private const int NUM_CARTAS = 5;
public PokerDomain() { }
/// <summary>
/// Este método inicia uma partida de poker entre dois jogadores e retorna um vencedor
/// </summary>
public Partida IniciarPartida(Jogador jogador1, Jogador jogador2)
{
var baralho = Util.Util.GetBaralho();
jogador1.Cartas = DistribuirCartas(baralho);
jogador2.Cartas = DistribuirCartas(baralho);
return DefinirVencedor(jogador1, jogador2);
}
public List<Carta> DistribuirCartas(List<Carta> baralho)
{
var cartas = new List<Carta>();
for (int i = 0; i < NUM_CARTAS; i++)
{
var random = new Random().Next(0, baralho.Count - 1);
var carta = baralho[random];
cartas.Add(carta);
baralho.Remove(carta);
}
return cartas;
}
private Partida DefinirVencedor(Jogador jogador1, Jogador jogador2)
{
var jogador1Hand = jogador1.GetHand();
var jogador2Hand = jogador2.GetHand();
if (jogador1Hand == Hands.HighCard && jogador2Hand == Hands.HighCard)
{
return DefinirVencedorHighCard(jogador1, jogador2);
}
else
{
if (jogador1Hand > jogador2Hand)
{
return new Partida
{
Vencedor = jogador1,
MaoVencedora = jogador1Hand
};
}
else if (jogador1Hand < jogador2Hand)
{
return new Partida
{
Vencedor = jogador2,
MaoVencedora = jogador2Hand
};
}
else
return DefinirVencedorHighCard(jogador1, jogador2);
}
}
private Partida DefinirVencedorHighCard(Jogador jogador1, Jogador jogador2)
{
var jogador1HighCard = jogador1.Cartas.OrderByDescending(carta => carta.NumCarta).First();
var jogador2HighCard = jogador2.Cartas.OrderByDescending(carta => carta.NumCarta).First();
if (jogador1HighCard.NumCarta > jogador2HighCard.NumCarta)
{
return new Partida
{
Vencedor = jogador1,
MaoVencedora = Hands.HighCard
};
}
else if (jogador1HighCard.NumCarta < jogador2HighCard.NumCarta)
{
return new Partida
{
Vencedor = jogador2,
MaoVencedora = Hands.HighCard
};
}
else
return null;
}
}
}
|
0f12b8d12bc6ffaadd7683005bf2bf48bb0b6458
|
[
"Markdown",
"C#"
] | 15
|
C#
|
mateusmcg/poker-azure-devops
|
ad49e072166fa1bd44757dca3a648b2a91e4db8a
|
87e29037ed5495c0361b15b2175f71fb4ffd55a8
|
refs/heads/master
|
<repo_name>gracepowell145/wr5_react-and-redux_review<file_sep>/src/Components/Header.js
import React from 'react';
function Header() {
return (
<header className='header'>
<h1>Mood Journal</h1>
<h4>"See how you deteriorate over time, in real time!"</h4>
</header>
)
}
export default Header;<file_sep>/src/App.js
import React from 'react';
import './App.css';
import Header from './Components/Header';
import MoodInput from './Components/MoodInput';
import MoodHistory from './Components/MoodHistory';
class App extends React.Component {
constructor() {
super();
this.state = {
name: ''
}
}
componentDidMount() {
const userName = window.prompt('What is your name?');
this.setState({ name: userName })
}
sendEntry = moodObj => {
const newEntries = [ moodObj, ...this.state.entries]
this.setState({ entries: newEntries });
}
render() {
return (
<div className="App">
<Header />
<MoodInput sendEntry={this.sendEntry} userName={this.state.name} />
<MoodHistory />
</div>
);
}
}
export default App;
|
fdd29017b8d76c0bf5287dd0ceda4e02aec275a4
|
[
"JavaScript"
] | 2
|
JavaScript
|
gracepowell145/wr5_react-and-redux_review
|
1ba8bd71c4104f4f21d1d6191b4944ef3bafb420
|
beab0913cea5093a006a55381fe2ed6e5acbba97
|
refs/heads/master
|
<repo_name>mhuang0711/health-farm<file_sep>/README.md
# health-farm
<file_sep>/story.js
$(document).ready(function(){
//menu
$(".menu").click(function(){
//if($('.menu').hasClass('open')) {
$("body").css("backgroundImage","url(home-menu.jpg)");
$(".story-page").css("display","none");
$(".background-img").css("display","block");
$(".menu-footer").css("display","block");
//$(".background-img").hover(function(){ -----unfinished------
$(".border-line").fadeIn(3000);
//});
//} else {
// $(".menu").addClass("open");
// }
});
});<file_sep>/product.js
$(document).ready(function(){
//menu
$(".menu").click(function(){
//if($('.menu').hasClass('open')) {
$("body").css("backgroundImage","url(home-menu.jpg)");
$(".product").css("display","none");
$(".background-img").css("display","block");
$(".menu-footer").css("display","block");
//$(".background-img").hover(function(){ -----unfinished------
$(".border-line").fadeIn(3000);
//});
//} else {
// $(".menu").addClass("open");
// }
});
//$(".fruits").hover(function(){
// $("body").css("backgroundImage","url(product.jpg)");
//});
//$(".cakes").hover(function(){
// $("body").css("backgroundImage","url(cakes.jpg)");
//});
//$(".cookies").hover(function(){
// $("body").css("backgroundImage","url(marcron.jpg)");
//});
});<file_sep>/home.js
$(document).ready(function(){
//menu
$(".menu").click(function(){
//if($('.menu').hasClass('open')) {
$("body").css("backgroundImage","url(home-menu.jpg)");
$(".background-img p").css("display","none");
$(".background-img h2").css("fontFamily","ItalicRoman");
$(".background-img label").css("display","none");
$(".background-img > div").css("height","100px");
$(".menu-footer").css("display","block");
//$(".background-img").hover(function(){ -----unfinished------
$(".border-line").fadeIn(3000);
//});
//} else {
// $(".menu").addClass("open");
// }
});
//$('.heading').click(function() {
// $('.heading').each(function(i) {
// if($(this).text() === $('.heading').eq(i).text()) {
// $(this).removeClass('open');
// }
// });
// $(this).addClass('open');
// var height, height2, that = $(this);
//
// $('.menu.open').css('height', '350px');
//
// setTimeout(function() {
// height = that.parent().find('ul').height();
// height2 = $('.menu.open').height();
// $('.menu.open').css('height' , height + height2);
// }, 1000);
});<file_sep>/healthy-farm-animation.js
$(document).ready(function(){
//menu
$("#menu-after").click(function(){
if($('.menu').hasClass('open')) {
$(".menu").removeClass("open");
$('.menu.open').css('height', '350px');
} else {
$(".menu").addClass("open");
}
});
$('.heading').click(function() {
$('.heading').each(function(i) {
if($(this).text() === $('.heading').eq(i).text()) {
$(this).removeClass('open');
}
});
$(this).addClass('open');
var height, height2, that = $(this);
$('.menu.open').css('height', '350px');
setTimeout(function() {
height = that.parent().find('ul').height();
height2 = $('.menu.open').height();
$('.menu.open').css('height' , height + height2);
}, 1000);
});
//animation
//$(".bottom-imgs li").hover(function(){
// var opacityval=$(this).find(".opacity-box").css("opacity");
// console.log(opacityval);
// if(opacityval==0){
// $(this).find(".opacity-box").css("opacity","0.7");
// $(this).find(".opacity-box p,span").animate({opacity:'1'},1000);
// $(this).find(".square").animate({opacity:'1',marginTop:'0px'},1000);
// $(this).find(".arrow").animate({opacity:'1',marginTop:'-15px'},1000);
//}
// else{
// $(this).find(".opacity-box").css("opacity","0");
// $(this).find(".opacity-box p,span").css("opacity","0");
// $(this).find(".square").css( {"opacity":"0","margin-top":"-50px"} );
// $(this).find(".arrow").css( {"opacity":"0","margin-top":"20px"} );
// }
//});
});
|
bdc012ae8159c696a899781e124b371d6cc1b1e7
|
[
"Markdown",
"JavaScript"
] | 5
|
Markdown
|
mhuang0711/health-farm
|
831e38a03bcd9ced79c84d932d3a418f0fd105c4
|
a2a1f0306b46838c36569f38a393a3f4aa8af33a
|
refs/heads/master
|
<repo_name>A1caida/matrix_sort<file_sep>/masiv s diog/masiv s diog.cpp
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
srand(time(NULL));
const int n = 5;
int** ar;
ar = new int* [n];
for (int i = 0; i < n; i++)
{
ar[i] = new int[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
ar[i][j] = rand() % 10;
cout << ar[i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
for (int owo = 0; owo < n - 1; owo++) //owo - строка
{
for (int uwu = owo + 1; uwu < n; uwu++)
{
if (ar[i][j] < ar[owo][uwu])
{
swap(ar[i][j], ar[owo][uwu]);
}
}
}
}
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
for (int owo = 1; owo < n; owo++)
{
for (int uwu = 0; uwu < owo; uwu++)
{
if (ar[i][j] > ar[owo][uwu])
{
swap(ar[i][j], ar[owo][uwu]);
}
}
}
}
}
cout << endl;
cout << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << ar[i][j] << "\t";
}
cout << endl;
}
}
|
4cb85abbadaeda15385187a07ec1a30dc33c39c8
|
[
"C++"
] | 1
|
C++
|
A1caida/matrix_sort
|
fb3895fc1a60428da011194e15abb29e57958b8d
|
5acf82b55c3cba4c9bf961bce746456afd03081a
|
refs/heads/master
|
<file_sep>class ChangeStartDateMeetings < ActiveRecord::Migration[5.0]
def change
change_column :meetings, :start_date, :datetime
change_column :meetings, :end_date, :datetime
end
end
<file_sep>class Person < ApplicationRecord
has_many :meeting
end
<file_sep>class Meeting < ApplicationRecord
belongs_to :person
end
<file_sep>json.extract! meeting, :id, :start_date, :end_date, :room, :person_id, :created_at, :updated_at
json.url meeting_url(meeting, format: :json)
|
7164d8e12256230fddebda9cadb6ef82e70ea520
|
[
"Ruby"
] | 4
|
Ruby
|
JackGerbert/SimonDoes
|
9042be5fa2416ac0250079e152f94266cc0e0f96
|
0ecaba5a703078e6cc6f05a146eeea5ffa562fb5
|
refs/heads/main
|
<repo_name>Anhxinhtrai/case-md2<file_sep>/case-md2/App/Models/Category.php
<?php
namespace App\Model;
class Category extends Model
{
public function getCategory()
{
$sql= "SELECT category_id,categoriesName FROM categories";
$stmt=$this->conn->query($sql);
return $stmt->fetchAll();
}
}<file_sep>/case-md2/App/Models/Language.php
<?php
namespace App\Model;
class Language extends Model
{
public function getLanguage()
{
$sql= "SELECT language_id,languageName FROM languages";
$stmt=$this->conn->query($sql);
return $stmt->fetchAll();
}
}<file_sep>/library_manager (1).sql
-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Máy chủ: localhost
-- Thời gian đã tạo: Th5 19, 2021 lúc 10:54 AM
-- Phiên bản máy phục vụ: 8.0.25-0ubuntu0.20.04.1
-- Phiên bản PHP: 7.4.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Cơ sở dữ liệu: `library_manager`
--
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `authors`
--
CREATE TABLE `authors` (
`author_id` int NOT NULL,
`authorName` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `authors`
--
INSERT INTO `authors` (`author_id`, `authorName`) VALUES
(1, '<NAME>'),
(6, '<NAME>');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `books`
--
CREATE TABLE `books` (
`book_id` int NOT NULL,
`year` int DEFAULT NULL,
`bookName` varchar(255) DEFAULT NULL,
`amount` int DEFAULT NULL,
`category_id` int DEFAULT NULL,
`language_id` int DEFAULT NULL,
`author_id` int DEFAULT NULL,
`location_id` int DEFAULT NULL,
`storage_id` int DEFAULT NULL,
`publisher_id` int DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `books`
--
INSERT INTO `books` (`book_id`, `year`, `bookName`, `amount`, `category_id`, `language_id`, `author_id`, `location_id`, `storage_id`, `publisher_id`) VALUES
(22, 1988, 'Cuộc đời của Trọng', 100, 1, 1, 1, 1, 6, 1);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `borrowing_cards`
--
CREATE TABLE `borrowing_cards` (
`card_id` int NOT NULL,
`user_id` int DEFAULT NULL,
`book_id` int DEFAULT NULL,
`borrowing_date` date DEFAULT NULL,
`return_date` date DEFAULT NULL,
`status` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `borrowing_cards`
--
INSERT INTO `borrowing_cards` (`card_id`, `user_id`, `book_id`, `borrowing_date`, `return_date`, `status`) VALUES
(88, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(89, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(90, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(91, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(92, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(93, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(94, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(95, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(96, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(97, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(98, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(99, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(100, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(101, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(102, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(103, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(104, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(105, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(106, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(107, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(108, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(109, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(110, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(111, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(112, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(113, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(114, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(115, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(116, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(117, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(118, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(119, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(120, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(121, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(122, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(123, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(124, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(125, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(126, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(127, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(128, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(129, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(130, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(131, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(132, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(133, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(134, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(135, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(136, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(137, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(138, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(139, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(140, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(141, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(142, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(143, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(144, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(145, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(146, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(147, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(148, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(149, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(150, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(151, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(152, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(153, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(154, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(155, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(156, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(157, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(158, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(159, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(160, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(161, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(162, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(163, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(164, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(165, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(166, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(167, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(168, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(169, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(170, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(171, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(172, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(173, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(174, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(175, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(176, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(177, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(178, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(179, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(180, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(181, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(182, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(183, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(184, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(185, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(186, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(187, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(188, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(189, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(190, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(191, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(192, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(193, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(194, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(195, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(196, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(197, NULL, NULL, '2021-05-18', '2021-05-18', 'not return'),
(198, NULL, NULL, '2021-05-19', '2021-05-19', 'not return'),
(199, NULL, NULL, '2021-05-19', '2021-05-19', 'not return'),
(200, NULL, NULL, '2021-05-19', '2021-05-19', 'not return'),
(201, NULL, NULL, '2021-05-19', '2021-05-19', 'not return'),
(202, NULL, NULL, '2021-05-19', '2021-05-19', 'not return'),
(203, NULL, NULL, '2021-05-19', '2021-05-19', 'not return');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `categories`
--
CREATE TABLE `categories` (
`category_id` int NOT NULL,
`categoriesName` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `categories`
--
INSERT INTO `categories` (`category_id`, `categoriesName`) VALUES
(1, 'hư cấu'),
(2, 'Kiếm Hiệp'),
(3, 'Trữ tình');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `languages`
--
CREATE TABLE `languages` (
`language_id` int NOT NULL,
`languageName` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `languages`
--
INSERT INTO `languages` (`language_id`, `languageName`) VALUES
(1, 'Viet Nam'),
(2, 'China'),
(3, 'English');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `locations`
--
CREATE TABLE `locations` (
`location_id` int NOT NULL,
`area` varchar(255) DEFAULT NULL,
`shelf` varchar(255) DEFAULT NULL,
`drawer` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `locations`
--
INSERT INTO `locations` (`location_id`, `area`, `shelf`, `drawer`) VALUES
(1, 'k<NAME> 1', 'háng thứ 4', 'ngăn thứ nhất'),
(2, '<NAME>', 'Giá 12', 'ngắn 8');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `publishers`
--
CREATE TABLE `publishers` (
`publisher_id` int NOT NULL,
`publisherName` varchar(255) DEFAULT NULL,
`publisherAddress` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `publishers`
--
INSERT INTO `publishers` (`publisher_id`, `publisherName`, `publisherAddress`) VALUES
(1, '<NAME>', 'Cam Cọn - Bảo Yên - Lào Cai'),
(2, '<NAME>', 'Cam Cọn - Bảo Yên - Lào Cai'),
(3, 'giáo dục việt nam', 'Hà');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `storage`
--
CREATE TABLE `storage` (
`storage_id` int NOT NULL,
`storageName` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `storage`
--
INSERT INTO `storage` (`storage_id`, `storageName`) VALUES
(6, 'Kho số 1'),
(25, 'Kho số 4');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `users`
--
CREATE TABLE `users` (
`id` int NOT NULL,
`userName` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone` int DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Đang đổ dữ liệu cho bảng `users`
--
INSERT INTO `users` (`id`, `userName`, `password`, `name`, `phone`) VALUES
(8, 'trong', '13123', 'trong', 113),
(9, 'trong1', '1', '1', 1),
(10, 'Duy', '123', 'Trong', 1234243),
(11, 'Tuan', '123', '123', 123),
(12, 'trum2k1', '123', '123', 1234243),
(13, 'admin', '123', '<NAME>', 911),
(14, 'Trang ne', '123', '<NAME>', 998),
(15, 'test', '1', 'Quaan', 1234243),
(16, 'Hoang', '1', 'Hoang dz', 113);
--
-- Chỉ mục cho các bảng đã đổ
--
--
-- Chỉ mục cho bảng `authors`
--
ALTER TABLE `authors`
ADD PRIMARY KEY (`author_id`);
--
-- Chỉ mục cho bảng `books`
--
ALTER TABLE `books`
ADD PRIMARY KEY (`book_id`),
ADD KEY `category_id` (`category_id`),
ADD KEY `language_id` (`language_id`),
ADD KEY `author_id` (`author_id`),
ADD KEY `location_id` (`location_id`),
ADD KEY `storage_id` (`storage_id`),
ADD KEY `publisher_id` (`publisher_id`);
--
-- Chỉ mục cho bảng `borrowing_cards`
--
ALTER TABLE `borrowing_cards`
ADD PRIMARY KEY (`card_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `book_id` (`book_id`);
--
-- Chỉ mục cho bảng `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`category_id`);
--
-- Chỉ mục cho bảng `languages`
--
ALTER TABLE `languages`
ADD PRIMARY KEY (`language_id`);
--
-- Chỉ mục cho bảng `locations`
--
ALTER TABLE `locations`
ADD PRIMARY KEY (`location_id`);
--
-- Chỉ mục cho bảng `publishers`
--
ALTER TABLE `publishers`
ADD PRIMARY KEY (`publisher_id`);
--
-- Chỉ mục cho bảng `storage`
--
ALTER TABLE `storage`
ADD PRIMARY KEY (`storage_id`);
--
-- Chỉ mục cho bảng `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT cho các bảng đã đổ
--
--
-- AUTO_INCREMENT cho bảng `authors`
--
ALTER TABLE `authors`
MODIFY `author_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT cho bảng `books`
--
ALTER TABLE `books`
MODIFY `book_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT cho bảng `borrowing_cards`
--
ALTER TABLE `borrowing_cards`
MODIFY `card_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=204;
--
-- AUTO_INCREMENT cho bảng `categories`
--
ALTER TABLE `categories`
MODIFY `category_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT cho bảng `languages`
--
ALTER TABLE `languages`
MODIFY `language_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT cho bảng `locations`
--
ALTER TABLE `locations`
MODIFY `location_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT cho bảng `publishers`
--
ALTER TABLE `publishers`
MODIFY `publisher_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT cho bảng `storage`
--
ALTER TABLE `storage`
MODIFY `storage_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;
--
-- AUTO_INCREMENT cho bảng `users`
--
ALTER TABLE `users`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- Các ràng buộc cho các bảng đã đổ
--
--
-- Các ràng buộc cho bảng `books`
--
ALTER TABLE `books`
ADD CONSTRAINT `books_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`category_id`),
ADD CONSTRAINT `books_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`language_id`),
ADD CONSTRAINT `books_ibfk_3` FOREIGN KEY (`author_id`) REFERENCES `authors` (`author_id`),
ADD CONSTRAINT `books_ibfk_4` FOREIGN KEY (`location_id`) REFERENCES `locations` (`location_id`),
ADD CONSTRAINT `books_ibfk_5` FOREIGN KEY (`storage_id`) REFERENCES `storage` (`storage_id`),
ADD CONSTRAINT `books_ibfk_6` FOREIGN KEY (`publisher_id`) REFERENCES `publishers` (`publisher_id`);
--
-- Các ràng buộc cho bảng `borrowing_cards`
--
ALTER TABLE `borrowing_cards`
ADD CONSTRAINT `borrowing_cards_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `borrowing_cards_ibfk_2` FOREIGN KEY (`book_id`) REFERENCES `books` (`book_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/case-md2/App/Controllers/BookController.php
<?php
namespace App\Controller;
use App\Model\Book;
use App\Model\Author;
use App\Model\Category;
use App\Model\Language;
use App\Model\Location;
use App\Model\Model;
use App\Model\Publisher;
use App\Model\Storage;
class BookController
{
protected $bookModel;
public function __construct()
{
$book = new Book();
$this->bookModel = $book;
}
public function deleteBook($book_id)
{
return $this->bookModel->deteleBook($book_id);
}
public function editBook($id,$request)
{
try {
$this->bookModel->updateBook($id,$request);
header("location: list.php");
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
public function addBook($request)
{
$year = $request["year"];
$bookName = $request["bookName"];
$amount = $request["amount"];
$category_id = $request["category_id"];
$language_id = $request["language_id"];
$author_id = $request["author_id"];
$location_id = $request["location_id"];
$storage_id = $request["storage_id"];
$publisher_id = $request["publisher_id"];
try {
$this->bookModel->addBook($year,
$bookName,
$amount,
$category_id,
$language_id,
$author_id,
$location_id,
$storage_id,
$publisher_id);
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
public function getBookById($book_id)
{
return $this->bookModel->getBookById($book_id);
}
public function getAllBook()
{
return $this->bookModel->getAllBook();
}
public function getAuthor()
{
$author = new Author();
return $author->getAuthor();
}
public function getCategory()
{
$category = new Category();
return $category->getCategory();
}
public function getLanguage()
{
$language = new Language();
return $language->getLanguage();
}
public function getLocation()
{
$location = new Location();
return $location->getLocation();
}
public function getPublisher()
{
$publisher = new Publisher();
return $publisher->getPublisher();
}
public function getStorage()
{
$storage = new Storage();
return $storage->getStorage();
}
}<file_sep>/case-md2/App/Models/Location.php
<?php
namespace App\Model;
class Location extends Model
{
public function getLocation()
{
$sql= "SELECT location_id FROM locations";
$stmt=$this->conn->query($sql);
return $stmt->fetchAll();
}
}<file_sep>/case-md2/App/Controllers/RegisterController.php
<?php
namespace App\Controller;
use App\Model\Register;
class RegisterController
{
protected $registerModel;
public function __construct()
{
$register = new Register();
$this->registerModel=$register;
}
public function register($user)
{
$userName = $user["userName"];
$password = $user["<PASSWORD>"];
$name = $user["name"];
$phone = $user["phone"];
$result = $this->registerModel->checkDup($userName);
if (!$result){
$this->registerModel->createUser($userName,$password,$name,$phone);
header("location: login.php");
}else{
echo "tài khoản đã có người đăng kí";
die();
}
}
}<file_sep>/case-md2/App/Models/Login.php
<?php
namespace App\Model;
class Login extends Model
{
public function checkLogin($userName,$password)
{
$sql = "SELECT id,name,userName,password FROM users WHERE userName=? AND password=?";
$stmt=$this->conn->prepare($sql);
$stmt->bindParam(1,$userName);
$stmt->bindParam(2,$password);
$stmt->execute();
return $stmt->fetch();
}
}<file_sep>/case-md2/App/Models/Book.php
<?php
namespace App\Model;
class Book extends Model
{
public function updateBook($book_id, $request)
{
$year = $request["year"];
$bookName = $request["bookName"];
$amount = $request["amount"];
$category_id = $request["category_id"];
$language_id = $request["language_id"];
$author_id = $request["author_id"];
$location_id = $request["location_id"];
$storage_id = $request["storage_id"];
$publisher_id = $request["publisher_id"];
$sql = "UPDATE books SET year=$year,
bookName='$bookName',
amount=$amount,
category_id=$category_id,
language_id=$language_id,
author_id=$author_id,
location_id=$location_id,
storage_id=$storage_id,
publisher_id=$publisher_id WHERE book_id=$book_id";
$stmt = $this->conn->query($sql);
return $stmt->execute();
}
public function deteleBook($book_id)
{
$sql = "DELETE FROM books WHERE book_id=?";
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $book_id);
return $stmt->execute();
}
public function addBook($year,
$bookName,
$amount,
$category_id,
$language_id,
$author_id,
$location_id,
$storage_id,
$publisher_id)
{
$sql = "INSERT INTO books VALUE (null,$year,'$bookName','$amount',$category_id,$language_id,$author_id,$location_id,$storage_id,$publisher_id)";
$stmt = $this->conn->query($sql);
return $stmt->execute();
}
public function getBookById($book_id)
{
$sql = "SELECT books.book_id,books.amount,books.bookName,categories.categoriesName,authors.authorName,books.year,publishers.publisherName,languages.languageName,storage.storageName
FROM books
JOIN categories ON books.category_id=categories.category_id
JOIN authors ON books.author_id=authors.author_id
JOIN publishers ON books.publisher_id=publishers.publisher_id
JOIN languages ON books.language_id=languages.language_id
JOIN storage ON books.storage_id=storage.storage_id WHERE books.book_id=$book_id";
$stmt = $this->conn->query($sql);
return $stmt->fetch();
}
public function getAllBook()
{
$sql = "SELECT books.book_id,books.bookName,categories.categoriesName,authors.authorName,books.year,publishers.publisherName,languages.languageName,storage.storageName
FROM books
JOIN categories ON books.category_id=categories.category_id
JOIN authors ON books.author_id=authors.author_id
JOIN publishers ON books.publisher_id=publishers.publisher_id
JOIN languages ON books.language_id=languages.language_id
JOIN storage ON books.storage_id=storage.storage_id";
$stmt = $this->conn->query($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}<file_sep>/case-md2/Resource/Views/Pages/register.php
<?php
require_once "../../../vendor/autoload.php";
use App\Controller\RegisterController;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$loginController = new RegisterController();
$loginController->register($_REQUEST);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lumino - Login</title>
<link href="../../../public/css/bootstrap.min.css" rel="stylesheet">
<link href="../../../public/css/datepicker3.css" rel="stylesheet">
<link href="../../../public/css/styles.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="../../../public/js/html5shiv.min.js"></script>
<script src="../../../public/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form role="form" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="<NAME>" name="userName" type="text" autofocus="">
</div>
<div class="form-group">
<input class="form-control" placeholder="<PASSWORD>" name="<PASSWORD>" type="<PASSWORD>" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Name" name="name" type="text" autofocus="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Phone" name="phone" type="number" autofocus="">
</div>
<button type="submit" class="btn btn-primary">Register</button></fieldset>
</form>
</div>
</div>
</div><!-- /.col-->
</div><!-- /.row -->
<script src="../../../public/js/jquery-1.11.1.min.js"></script>
<script src="../../../public/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>/case-md2/Resource/Function/Books/delete.php
<?php
require_once "../../../vendor/autoload.php";
use App\Controller\BookController;
$bookController = new BookController();
session_start();
$userLogin = $_SESSION['userLogin'];
if($userLogin["userName"]!="admin"){
header("location: ../../Views/Books/list.php");
}
if($_SERVER["REQUEST_METHOD"]=="GET"){
$book_id = $_GET["delete-book"];
$bookController->deleteBook($book_id);
header("location: ../../Views/Books/list.php");
}<file_sep>/case-md2/App/Models/Storage.php
<?php
namespace App\Model;
class Storage extends Model
{
public function getStorage()
{
$sql = "SELECT storage_id,storageName FROM storage";
$stmt = $this->conn->query($sql);
return $stmt->fetchAll();
}
}<file_sep>/case-md2/App/Controllers/CardController.php
<?php
namespace App\Controller;
use App\Model\BorrowingCard;
class CardController
{
protected $cardModel;
public function __construct()
{
$card = new BorrowingCard();
$this->cardModel = $card;
}
public function addCard($request)
{
$user_id = $request["user_id"];
$book_id = $request["book_id"];
try {
$this->cardModel->createCard($book_id, $user_id);
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
public function getAllCardById($user_id)
{
return $this->cardModel->getCardByUserId($user_id);
}
}<file_sep>/case-md2/Resource/Views/Pages/login.php
<?php
require_once "../../../vendor/autoload.php";
use App\Controller\LoginController;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$loginController = new LoginController();
$loginController->login($_REQUEST);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lumino - Login</title>
<link href="../../../public/css/bootstrap.min.css" rel="stylesheet">
<link href="../../../public/css/datepicker3.css" rel="stylesheet">
<link href="../../../public/css/styles.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="../../../public/js/html5shiv.min.js"></script>
<script src="../../../public/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">Log in</div>
<div class="panel-body">
<form role="form" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="<NAME>" name="userName" type="text" autofocus="">
</div>
<div class="form-group">
<input class="form-control" placeholder="<PASSWORD>" name="<PASSWORD>" type="<PASSWORD>" value="">
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
</div>
<small class="text-break">nếu chưa có tài khoản vui lòng <a href="register.php">Đăng kí</a></small><br>
<button type="submit" class="btn btn-primary">Login</button></fieldset>
</form>
</div>
</div>
</div><!-- /.col-->
</div><!-- /.row -->
<script src="../../../public/js/jquery-1.11.1.min.js"></script>
<script src="../../../public/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>/case-md2/App/Models/BorrowingCard.php
<?php
namespace App\Model;
class BorrowingCard extends Model
{
public function createCard($book_id, $user_id)
{
$sql = "INSERT INTO borrowing_cards VALUE (null,?,?,now(),(now()+5),'not return')";
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $user_id);
$stmt->bindParam(2, $book_id);
return $stmt->execute();
}
public function getAllCard()
{
$sql = "SELECT * FROM borrowing_cards";
$stmt=$this->conn->query($sql);
return $stmt->fetchAll();
}
public function getCardByUserId($user_id)
{
$sql = "SELECT borrowing_cards.card_id,users.name,books.bookName,borrowing_cards.borrowing_date,borrowing_cards.return_date,borrowing_cards.status
FROM borrowing_cards
JOIN users ON borrowing_cards.user_id=users.id
JOIN books ON borrowing_cards.book_id=books.book_id
WHERE user_id=?";
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $user_id);
$stmt->execute();
return $stmt->fetchAll();
}
}<file_sep>/case-md2/App/Models/Register.php
<?php
namespace App\Model;
class Register extends Model
{
public function checkDup($userName)
{
$sql ="SELECT userName FROM users WHERE userName=?";
$stmt=$this->conn->prepare($sql);
$stmt->bindParam(1,$userName);
$stmt->execute();
return $stmt->fetch();
}
public function createUser($userName,$password,$name,$phone)
{
$sql="INSERT INTO users VALUE (null,?,?,?,?)";
$stmt=$this->conn->prepare($sql);
$stmt->bindParam(1,$userName);
$stmt->bindParam(2,$password);
$stmt->bindParam(3,$name);
$stmt->bindParam(4,$phone);
return $stmt->execute();
}
}<file_sep>/case-md2/index.php
<?php
if (empty($_SESSION["userLogin"])){
header("location: Resource/Views/Pages/login.php");
}<file_sep>/case-md2/App/Models/Model.php
<?php
namespace App\Model;
class Model
{
protected \PDO $conn;
public function __construct()
{
$db = new Database();
$this->conn = $db->connect();
}
}<file_sep>/case-md2/App/Models/Database.php
<?php
namespace App\Model;
class Database
{
private string $dsn;
private string $username;
private string $password;
public function __construct()
{
$this->dsn = 'mysql:host=localhost;dbname=library_manager';
$this->username = 'root';
$this->password = '<PASSWORD>';
}
function connect(): \PDO
{
try {
return new \PDO($this->dsn, $this->username, $this->password);
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
}<file_sep>/case-md2/App/Controllers/LoginController.php
<?php
namespace App\Controller;
session_start();
use App\Model\Login;
class LoginController
{
protected $loginModel;
public function __construct()
{
$login = new Login();
$this->loginModel = $login;
}
public function login($request)
{
$userName = $request["userName"];
$password = $request["password"];
$result = $this->loginModel->checkLogin($userName, $password);
if ($result) {
$_SESSION["userLogin"] = $result;
header("location: ../Books/list.php");
}
}
}<file_sep>/case-md2/Resource/Views/Cards/list.php
<?php
require_once "../../../vendor/autoload.php";
use App\Controller\CardController;
session_start();
$userLogin = $_SESSION['userLogin'];
if (empty($_SESSION["userLogin"])) {
header("location: login.php");
}
$cardController = new CardController();
$cards = $cardController->getAllCardById($userLogin["id"]);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lumino - Dashboard</title>
<link href="../../../public/css/bootstrap.min.css" rel="stylesheet">
<link href="../../../public/css/font-awesome.min.css" rel="stylesheet">
<link href="../../../public/css/datepicker3.css" rel="stylesheet">
<link href="../../../public/css/styles.css" rel="stylesheet">
<!--Custom Font-->
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i"
rel="stylesheet">
<!--[if lt IE 9]>
<script src="../../../public/js/html5shiv.min.js"></script>
<script src="../../../public/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#sidebar-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button>
<a class="navbar-brand" href="#"><span>Lumino</span>Admin</a>
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown"><a class="dropdown-toggle count-info" data-toggle="dropdown" href="#">
<em class="fa fa-envelope"></em><span class="label label-danger">15</span>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<div class="dropdown-messages-box"><a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="http://placehold.it/40/30a5ff/fff">
</a>
<div class="message-body"><small class="pull-right">3 mins ago</small>
<a href="#"><strong><NAME></strong> commented on <strong>your photo</strong>.</a>
<br/><small class="text-muted">1:24 pm - 25/03/2015</small></div>
</div>
</li>
<li class="divider"></li>
<li>
<div class="dropdown-messages-box"><a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="http://placehold.it/40/30a5ff/fff">
</a>
<div class="message-body"><small class="pull-right">1 hour ago</small>
<a href="#">New message from <strong><NAME></strong>.</a>
<br/><small class="text-muted">12:27 pm - 25/03/2015</small></div>
</div>
</li>
<li class="divider"></li>
<li>
<div class="all-button"><a href="#">
<em class="fa fa-inbox"></em> <strong>All Messages</strong>
</a></div>
</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle count-info" data-toggle="dropdown" href="#">
<em class="fa fa-bell"></em><span class="label label-info">5</span>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li><a href="#">
<div><em class="fa fa-envelope"></em> 1 New Message
<span class="pull-right text-muted small">3 mins ago</span></div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div><em class="fa fa-heart"></em> 12 New Likes
<span class="pull-right text-muted small">4 mins ago</span></div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div><em class="fa fa-user"></em> 5 New Followers
<span class="pull-right text-muted small">4 mins ago</span></div>
</a></li>
</ul>
</li>
</ul>
</div>
</div><!-- /.container-fluid -->
</nav>
<div id="sidebar-collapse" class="col-sm-3 col-lg-2 sidebar">
<div class="profile-sidebar">
<div class="profile-userpic">
<img src="http://placehold.it/50/30a5ff/fff" class="img-responsive" alt="">
</div>
<div class="profile-usertitle">
<div class="profile-usertitle-name"><?php echo $userLogin["name"] ?></div>
<div class="profile-usertitle-status"><span class="indicator label-success"></span>Online</div>
</div>
<div class="clear"></div>
</div>
<div class="divider"></div>
<form role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
</form>
<ul class="nav menu">
<li><a href="../Books/list.php"><em class="fa fa-dashboard"> </em>Book List</a></li>
<li class="active"><a href=""><em class="fa fa-calendar"> </em>Lịch sử mượn</a></li>
<li class="parent "><a data-toggle="collapse" href="#sub-item-1">
<em class="fa fa-navicon"> </em> Multilevel <span data-toggle="collapse" href="#sub-item-1"
class="icon pull-right"><em
class="fa fa-plus"></em></span>
</a>
<ul class="children collapse" id="sub-item-1">
<li><a class="" href="#">
<span class="fa fa-arrow-right"> </span> Sub Item 1
</a></li>
<li><a class="" href="#">
<span class="fa fa-arrow-right"> </span> Sub Item 2
</a></li>
<li><a class="" href="#">
<span class="fa fa-arrow-right"> </span> Sub Item 3
</a></li>
</ul>
</li>
<li><a href="login.html"><em class="fa fa-power-off"> </em> Logout</a></li>
</ul>
</div><!--/.sidebar-->
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Dashboard</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Lịch Sử Mượn Sách </h1</div>
</div><!--/.row-->
<?php foreach ($cards as $item){ ?>
<div class="col-md-4">
<div class="<?php if($item["status"]=="not return"){
echo "panel panel-danger";
}else{
echo "panel panel-primary";
}?>">
<div class="panel-heading"><?php echo $item["bookName"] ?></div>
<div class="panel-body">
<p><?php echo "Người mượn: " .$item["name"] ?></p>
<p><?php echo "Ngày mượn: " .$item["borrowing_date"] ?></p>
<p><?php echo "Ngày trả: " .$item["return_date"] ?></p>
<p><?php echo "Trạng thái: " .$item["status"] ?></p>
<p><?php echo "Mã số thẻ mượn: " .$item["card_id"] ?></p>
<?php if ($item["status"]=="not return"){?><a href="" class="btn btn-primary">Trả ngay</a><?php }?>
</div>
</div>
</div>
<?php } ?>
</div>
<script src="../../../public/js/jquery-1.11.1.min.js"></script>
<script src="../../../public/js/bootstrap.min.js"></script>
<script src="../../../public/js/chart.min.js"></script>
<script src="../../../public/js/chart-data.js"></script>
<script src="../../../public/js/easypiechart.js"></script>
<script src="../../../public/js/easypiechart-data.js"></script>
<script src="../../../public/js/bootstrap-datepicker.js"></script>
<script src="../../../public/js/custom.js"></script>
<script>
window.onload = function () {
var chart1 = document.getElementById("line-chart").getContext("2d");
window.myLine = new Chart(chart1).Line(lineChartData, {
responsive: true,
scaleLineColor: "rgba(0,0,0,.2)",
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleFontColor: "#c5c7cc"
});
};
</script>
</body>
</html><file_sep>/case-md2/App/Models/Author.php
<?php
namespace App\Model;
class Author extends Model
{
public function getAuthor()
{
$sql= "SELECT author_id,authorName FROM authors";
$stmt=$this->conn->query($sql);
return $stmt->fetchAll();
}
}
|
a789f3100eebf542e944f7859f041a619cba2e2f
|
[
"SQL",
"PHP"
] | 21
|
PHP
|
Anhxinhtrai/case-md2
|
522d5412eb46b4173c68245d65c0d3197e047a87
|
722cc246720e336886a21fc78408efb184c47e65
|
refs/heads/master
|
<file_sep>/*
* vrs_cv5.h
*
* Created on: 18. 10. 2016
* Author: P3k
*/
#ifndef VRS_CV5_H_
#define VRS_CV5_H_
#include "stm32l1xx.h"
void blikaj(uint16_t AD_value); //blikanie led
uint16_t nacitaj(void);
void adc_init(void); //inicializacia adc
void led(void); //inicializacia led
void adc_irq(void); //inicializacia ADC prerusenia
void ADC1_IRQHandler(void); //prerusenie na naciatanie vstupu-rychlost blikania led
void USART1_IRQHandler(void); //prerusenie USART
void USART_IRQ(void); //inicializacia USART preruseni
void Usart(void); //GPIO USART
void ParseData(void);
#endif /* VRS_CV5_H_ */
<file_sep>/*
* vrs_cv5.c
*
* Created on: 18. 10. 2016
* Author: P3k
*/
#include "vrs_cv5.h"
volatile uint16_t vstup;
uint8_t stoj = 0;
uint8_t buffer[5][2];
void blikaj(uint16_t AD_value)
{
int i = 0;
for(i=0;i<(4000+50*AD_value);i++);
}
uint16_t nacitaj(void)
{
ADC_SoftwareStartConv(ADC1);
uint16_t vstup;
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC)){}
vstup=ADC_GetConversionValue(ADC1);
}
void adc_init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
/* Enable GPIO clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);//Opraviť a upraviť
/* Configure ADCx Channel 2 as analog input */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Enable the HSI oscillator */
RCC_HSICmd(ENABLE);
/* Check that HSI oscillator is ready */
while(RCC_GetFlagStatus(RCC_FLAG_HSIRDY) == RESET);
/* Enable ADC clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
/* Initialize ADC structure */
ADC_StructInit(&ADC_InitStructure);
/* ADC1 configuration */
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; //.....
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC1, &ADC_InitStructure);
/* ADCx regular channel8 configuration */
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_16Cycles);
/* Enable the ADC */
ADC_Cmd(ADC1, ENABLE);
/* Wait until the ADC1 is ready */
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_ADONS) == RESET) { }
/* Start ADC Software Conversion */
ADC_SoftwareStartConv(ADC1); }
void adc_irq(void){
// NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = ADC1_IRQn; //zoznam prerušení nájdete v súbore stm32l1xx.h
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);
ADC_ITConfig(ADC1, ADC_IT_OVR, ENABLE);
}
void ADC1_IRQHandler(void)
{
if(ADC1->SR & ADC_SR_EOC){ //osetrenie ci sa jedna o moje prerusenie EOC
if(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC)){
vstup = ADC1->DR;
//flag EOC sa resetuje automaticky po precitani hodnoty, preto ho nemusim tu -> prerusnie ma byt rychle
//ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
}
}
}
void led(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*Configure LED*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART1_IRQHandler(void) //startup_stm32l1xx_hd.s
{
//static uint8_t buffer[]={"2.93V"};
static uint8_t poc=0;
// static uint8_t buffer[]={"2.93V"};
if(USART1->SR & USART_FLAG_RXNE)
{
if(USART_ReceiveData(USART1) == 'm')
USART_ClearFlag(USART1, USART_FLAG_RXNE);
}
if(USART1->SR & USART_FLAG_TC){
USART_ClearFlag(USART1, USART_FLAG_TC);
//odosielame data
USART_SendData(USART1, buffer[poc][stoj]);
poc++;
if(poc>=(5)){ //odosielame 5 znakov..
poc=0;
if(stoj){
stoj = 0;
}
else{
stoj = 1;
}
}
}
}
void Usart(void)
{
/* PA10->RX PA9->TX */
GPIO_InitTypeDef GPIO_InitStructure;
USART_Cmd(USART1, ENABLE);
}
void USART_IRQ(void){
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
}
void ParseData(void)
{
static uint8_t stoj2 = 1;
if(stoj2 != stoj)
{
buffer[0][stoj] = vstup/1000 + '0';
buffer[1][stoj] = (vstup/100) % 10 + '0';
buffer[2][stoj] = (vstup/10) % 10 + '0';
buffer[3][stoj] = vstup % 10 + '0';
buffer[4][stoj] = '\n';
}
}
|
9bab123cc052de11099f29656768f815ccd6595f
|
[
"C"
] | 2
|
C
|
qwer456/vrs_cv5
|
a4228bf45a0cd635f6a0b5d23cc73a8148c92380
|
dd91db0756541df27c7b1631f5c12ba265624f3d
|
refs/heads/main
|
<repo_name>SeabassJames/Bird-and-Squirrel-The-Get-to-the-Goal-Puzzle-Game<file_sep>/src/sfoye-final-project/MyPathPlanner.cpp
#include "MyPathPlanner.h"
#include "MyGame.h"
#include <iostream>
#include <queue>
using namespace mathtool;
namespace GMUCS425
{
MyPathPlanner::MyPathPlanner(MyScene * scene, MyAgent * agent)
{
m_scene=scene;
m_agent=agent;
}
//
//TODO: (10 pts)
//about 15~20 lines of code
//
//return true if m_agent collide with a non-movable object
//at a given location
//
bool MyPathPlanner::collision_detection(const Point2d& pos)
{
//brute force collision detection
//Hint:
//methods to use: collide(), getX(), getY(), tranlateTo() in MyAgent
//get_agents() in MyScene
//remember original position
float x0 = m_agent->getX();
float y0 = m_agent->getY();
//move to pos
m_agent->tranlateTo(pos[0], pos[1]);
//check every agent
const std::list<MyAgent * > & listOfAgents = m_scene->get_agents();
for (std::list<MyAgent *>::const_iterator ma = listOfAgents.begin(); ma != listOfAgents.end(); ma++){
//for (const MyAgent & ma : listOfAgents) {
if (! (*ma)->is_movable()) {//only static objects
//if (m_agent->collide(&ma)) {
if ((*ma)->collide(m_agent)) {
m_agent->tranlateTo(x0, y0);
return true;
}
}
}
m_agent->tranlateTo(x0, y0);
return false;
}
//TODO: (10 pts)
//estimate the cost of traveling from pos1 to pos2
//distance between pos1 and pos2 scaled using the values generated by Perlin noise
float MyPathPlanner::cost(const Point2d& pos1, const Point2d& pos2)
{
const Uint32 * terrain = m_scene->get_terrain();
int terrain_width = getMyGame()->getScreenWidth();
int terrain_height = getMyGame()->getScreenHeight();
//terrain is a (terrain_width X terrain_height) array
float scale=1; //Note: the scale must be larger than 1
//TODO:
//estimate the scale here, if the terrain value is 0, the scale should be 1
//if the terrain value is high, the scale should be larger, therefore the cost
//of going from pos1 to pos2 is higher
//Hint: there are many correct implementations, use your imagination
float scales = 0;
float dx = pos2[0] - pos1[0];
float dy = pos2[1] - pos1[1];
float dist = sqrt(dx * dx + dy * dy);
float c = 0;
int iters = 10;
if ((dist < 1) && (m_agent->isSquirrel)) { //don't apply terrain to bird
for (int i = 0; i < iters; i++) {
int x = pos1[0] + dx * i / iters;
int y = pos1[1] + dx * i / iters;
Uint32 watery = terrain[((int)y)*terrain_width + ((int)x)] & 255;
float scale = (2 - watery * 1.0f / 255); //1~2
scales += scale; //(terrain[(int)(pos1[0] + (i / dist)*dx) + (int)(pos1[1] + (i / dist)*dy)*terrain_width]) / 10;
//c += scale / 10;
}
return scales/iters * (pos1 - pos2).norm(); //scale this by the value in terrain
}
else {
return 1 * (pos1 - pos2).norm(); //scale this by the value in terrain
}
//return c;
return scale * (pos1-pos2).norm(); //scale this by the value in terrain
}
//------------
//TODO: (20 pts)
bool MyGridPathPlanner::build() //build a grid
{
if(!m_grid.empty()) return false; //build only if the grid is empty
m_grid=std::vector< std::vector<Node> >( m_height, std::vector<Node>(m_width,Node()) );
float cell_w=getMyGame()->getScreenWidth()*1.0f/m_width;
float cell_h=getMyGame()->getScreenHeight()*1.0f/m_height;
//TODO: go through the nodes (cells) in the grid, and initial the data for each node
for(int i=0;i<m_height;i++)
{
for(int j=0;j<m_width;j++)
{
Node & n=m_grid[i][j];
//determine the values of n.pos, n.free and n.neighbors
//pos
n.pos = Point2d(j*cell_w, i*cell_h);
//free
n.free = !collision_detection(n.pos);
/*
if (n.free) {
if ((i > 0)){// && !collision_detection(Point2d((n.pos[0] ), (n.pos[0] - cell_h / 2)))) {// top edge
n.neighbors.push_front(&m_grid[i - 1][j]);
}
if ((j > 0) ) {//&& !collision_detection(Point2d((n.pos[0] - cell_w / 2), (n.pos[0] )))) {//left edge
n.neighbors.push_front(&m_grid[i][j - 1]);
}
if ((j < m_width-1)) {// && !collision_detection(Point2d((n.pos[0] + cell_w / 2), (n.pos[0])))) {//right edge
n.neighbors.push_front(&m_grid[i][j + 1]);
}
if ((i < m_height-1)) {//&& !collision_detection(Point2d((n.pos[0]), (n.pos[0] - cell_h / 2)))) {//bottom edge
n.neighbors.push_front(&m_grid[i + 1][j]);
}
}
//Note:
// We consider 4-connection neighbors here. (N, W, E, S)
// A node n has a neighobor node m iff both m and n are free (i.e. not occupied)
// Thus, if a node is not free (i.e. occupied), it should not have any neighbors
*/
if (n.free) {
//if ((j > 0) && (i > 0) && !collision_detection(Point2d((n.pos[0] - cell_w/2), (n.pos[0] - cell_h/2)))) {//top left corner
if ((j > 0) && (i > 0) && !collision_detection(Point2d((n.pos[0] - cell_w / 2), (n.pos[0]))) && !collision_detection(Point2d((n.pos[0]), (n.pos[0] - cell_h / 2)))) {//top left corner
n.neighbors.push_front(&m_grid[i - 1][j - 1]);
}
if ((i > 0) /*&& !collision_detection(Point2d((n.pos[0] ), (n.pos[0] - cell_h / 2)))*/) {// top edge
n.neighbors.push_front(&m_grid[i - 1][j]);
}
if ((j < m_width - 1) && (i > 0) && !collision_detection(Point2d((n.pos[0]), (n.pos[0] - cell_h / 2))) && !collision_detection(Point2d((n.pos[0] + cell_w / 2), (n.pos[0])))) {//top right corner
n.neighbors.push_front(&m_grid[i - 1][j + 1]);
}
if ((j > 0) /*&& !collision_detection(Point2d((n.pos[0] - cell_w / 2), (n.pos[0] )))*/) {//left edge
n.neighbors.push_front(&m_grid[i][j - 1]);
}
if ((j < m_width - 1) /*&& !collision_detection(Point2d((n.pos[0] + cell_w / 2), (n.pos[0])))*/) {//right edge
n.neighbors.push_front(&m_grid[i][j + 1]);
}
if ((j > 0) && (i < m_height - 1) && !collision_detection(Point2d((n.pos[0]), (n.pos[0] + cell_h / 2))) && !collision_detection(Point2d((n.pos[0] - cell_w / 2), (n.pos[0])))) {//bottom left corner
n.neighbors.push_front(&m_grid[i + 1][j - 1]);
}
if ((i < m_height - 1) /*&& !collision_detection(Point2d((n.pos[0]), (n.pos[0] - cell_h / 2)))*/) {//bottom edge
n.neighbors.push_front(&m_grid[i + 1][j]);
}
if ((j < m_width - 1) && (i < m_height - 1) && !collision_detection(Point2d((n.pos[0]), (n.pos[0] + cell_h / 2))) && !collision_detection(Point2d((n.pos[0] + cell_w / 2), (n.pos[0])))) {//bottom right corner
n.neighbors.push_front(&m_grid[i + 1][j + 1]);
}
}
//Note:
// We consider 8-connection neighbors here. (N, W, E, S, NE, NW, SE, SW)
// A node n has a neighobor node m iff both m and n are free (i.e. not occupied)
// Thus, if a node is not free (i.e. occupied), it should not have any neighbors
}//end j
}//end i
return true;
}
//finding a path using A*
bool MyGridPathPlanner::find_path( const Point2d& start, const Point2d& goal, std::list<Point2d>& path )
{
//check if the start and goal are valid (i.e., inside the screen)
if(start[0]<0 || start[1]>=getMyGame()->getScreenWidth()) return false;
if(goal[0]<0 || goal[1]>=getMyGame()->getScreenWidth()) return false;
float cell_w=getMyGame()->getScreenWidth()*1.0f/m_width;
float cell_h=getMyGame()->getScreenHeight()*1.0f/m_height;
//vector<Node *> open, close;
Node * S=&m_grid[(int)(start[1]/cell_h)][(int)(start[0]/cell_w)];
Node * G=&m_grid[(int)(goal[1]/cell_h)][(int)(goal[0]/cell_w)];
if (!S->free) {
cerr << "! Error: Start point makes the agent collide with something" << endl;
path.clear();
path.push_front(goal); //replace this
path.push_front(start); //replace this
return false;
}
if (!G->free) {
cerr << "! Error: Goal point makes the agent collide with something" << endl;
path.clear();
path.push_front(goal); //replace this
path.push_front(start); //replace this
return false;
}
bool found = true;
//dummy path planning, replace the following two lines with A*
//reset grid data
for (int i = 0;i < m_height;i++)
{
for (int j = 0;j < m_width;j++)
{
Node & no = m_grid[i][j];
no.parent = NULL;
no.f = no.g = FLT_MAX;
no.visited = false;
}
}
path.clear();
//path.push_front(goal); //replace this
//path.push_front(start); //replace this
//
//priority_queue<Point2d> open;
//priority_queue<Point2d> closed;
priority_queue<Node *, vector<Node *>, decltype(&comp)> openlist(comp);
priority_queue<Node *, vector<Node *>, decltype(&comp)> closedlist(comp);
priority_queue<Node *, vector<Node *>, decltype(&comp)> templist(comp);
int j = start[0]/cell_w, i = start[1]/cell_h;//j is x, i is y
// m_grid[i][j].f = sqrt(pow((i - goal[0]), 2) + pow((j - goal[1]), 2));
m_grid[i][j].f = cost(start, goal);
m_grid[i][j].g = 0;
m_grid[i][j].parent = NULL;
//open.push(Point2d(i, j));
openlist.push(&m_grid[i][j]);
while (!openlist.empty()) {
Node * n = openlist.top();
//i = openlist.top()
openlist.pop();
closedlist.push(n);
n->visited = true;
if ((abs(n->pos[0] - goal[0]) < cell_w) && (abs(n->pos[1] - goal[1]) < cell_h) ) {
//goal found
while (n != NULL) {//fill path
path.push_front(n->pos);
n = n->parent;
}
path.push_front(start);
return true;
break;
}
else {
double gNew, fNew;
for (Node * neighbor : n->neighbors) {
//screen space
int nx = neighbor->pos[0];// x of neighbor in screen space
int ny = neighbor->pos[1];
//grid space
int nj = nx * cell_w;
int ni = ny * cell_h;
//set parent
float ng = cost(n->pos, neighbor->pos);
//check if neighbor is in closedlist
//if neighbor is visited, skip
if (neighbor->visited) {
continue;
}
if ((/*neighbor->parent == NULL ||*/ neighbor->g > ng) ) {
neighbor->parent = n;
//set f and g
neighbor->g = n->g + cost(n->pos, neighbor->pos);
neighbor->f = neighbor->g + cost(neighbor->pos, goal);
}
//check if neighbor is in openlist
bool isInOpen = false;
while (!isInOpen && !openlist.empty()) {
Node * check = openlist.top();
if (neighbor == check) {
isInOpen = true;
}
else {
templist.push(check);
openlist.pop();
}
}
//put openlist back together
while (!templist.empty()) {
Node * check = templist.top();
openlist.push(check);
templist.pop();
}
//if neighbor not in openlist, add it to openlist
if (! isInOpen) {
openlist.push(neighbor);
}
}
}
}
path.push_front(start);
//
return false;
return found;
}
//TODO: shorten and smooth the path (20 pts, 10 pts each)
//To smooth, use Quadratic Bezier curves
void MyPathPlanner::shorten_and_smooth(std::list<Point2d>& path)
{
//We assume that the agent can travel along the path without colliding with
//any static obstacles/objects
//
//
//Note: "path" is both input and output
//
//Hints:
// shorten: Pick a pair of points on the path
// make sure the line connecting the points are collision free
// replace all points in between with the line
//
// smooth: Pick 3 points on the path
// Compute the Quadratic Bezier curve from these 3 points
// Replace all points in between with the curve
//
// combined: Pick 3 points and smooth the path.
// If failed, use 1st and 3rd point to shorten the path.
//iterate through every 3 points
std::list<Point2d>::iterator p2 = path.begin();
std::list<Point2d>::iterator p0 = p2 ++;
std::list<Point2d>::iterator p1 = p2++;
int na = 0;
for (p0 = path.begin(); p2 != path.end() && p1 != path.end(); na += 0)
{
//try to smooth path
bool success = true;
//cannot dereference iterator, cannot access members, I don't know how to smooth with these restrictions
/*if (!collision_detection(Point2d((p0->v[0] + p2[0]) / 2, (p0[1] + p2[1]) / 2))) { //if no collision between p0 and p2
for (float t = 1; t >= 0; t -= 0.1) {
Point2d pb = Point2d((1 - t)*((1 - t) * (*p0)[0] + t * (*p1)[0]) + t * ((1 - t)*(*p1)[0] + t * (*p2)[0]), (1 - t)*((1 - t) * (*p0)[1] + t * (*p1)[1]) + t * ((1 - t)*(*p1)[1] + t * (*p2)[1]));
//if (!collision_detection(pb)) {
path.insert(p1, pb);
//}
}
p0 = p1;
path.remove(*p1);
p1 = p2;
p2++;
//}*/
//else {
//move forward
p0++;
p1++;
p2++;
//}*/
}
}
}//end namespace GMUCS425
<file_sep>/src/sfoye-final-project/MyAgent.h
#pragma once
#include "MySprite.h"
#include "mathtool/Point.h"
//#include "MyAgent.h"
//#include "MyGame.h"
//#include <SDL_image.h>
//#include <SDL_ttf.h>
//#include <sstream>
#include "mathtool/Box.h"
namespace GMUCS425
{
//this defines the transform of the agent
class MyAgent
{
public:
/*
//movable: true if this agent can move
//collision: true if this agent can collision with other agents
MyAgent(bool movable=true, bool collision=true)
{
x=y=degree=0;
scale=1;
visible=true;
sprite=NULL;
this->movable=movable;
this->collision=collision;
}
*/
//movable: true if this agent can move
//bird/squirrel collision: true if this agent can collision with other agents
MyAgent(bool movable = true, bool bcollision = true, bool scollision = true, bool collision = true)
{
x = y = degree = 0;
scale = 1;
visible = true;
sprite = NULL;
this->movable = movable;
this->birdcollision = bcollision;
this->squirrelcollision = scollision;
this->collision = collision;
this->isBird = false;
this->isSquirrel = false;
this->isAlive = true;
this->isBad = false;
}
//react to the events
virtual void handle_event(SDL_Event & e);
//update this agent's motion, looks, sound, etc
virtual void update();
//render this agent
virtual void display();
//show HUD (heads-up display) or status bar
virtual void draw_HUD();
//transforms
void rotate(float degree){ this->degree+=degree; }
void rotateTo(float degree){ this->degree=degree; }
void tranlate(float x, float y){ this->x+=x; this->y+=y; }
void tranlateTo(float x, float y){ this->x=x; this->y=y; }
void scaleTo(float s){ this->scale=s; }
//display
void show(){ visible=true; }
void hide(){ visible=false; }
//sprite, aks costume
void setSprite(MySprite * sprite){ this->sprite=sprite; }
MySprite* getSprite() { return this->sprite; }
MySprite* getSprite() const { return this->sprite; }
//float getWidth() const { return getSprite()->getWidth(scale); }
//float getHeight() const { return getSprite()->getHeight(scale); }
//motion/animation
//void glide(float x, float y, float seconds);
bool collide(MyAgent * other);
bool MyAgent::collide(MyAgent * other) const
{
mathtool::Box2d box1, box2;
box1.x = x;
box1.y = y;
box1.width = this->sprite->getWidth(scale);
box1.height = this->sprite->getHeight(scale);
box2.x = other->x;
box2.y = other->y;
box2.width = other->sprite->getWidth(other->scale);
box2.height = other->sprite->getHeight(other->scale);
return box1.intersect(box2);
}
//ACCESS METHODS
bool is_movable() const { return movable; }
bool is_visible() const { return visible; }
float getX() const { return x; }
float getY() const { return y; }
float getAngle() const { return degree; }
float getScale() const { return scale; }
//protected:
void draw_bounding_box();
//current position and orientations
float x,y;
float degree; //rotation
float scale;
bool visible;
bool movable;
bool collision;
bool birdcollision;
bool squirrelcollision;
bool isBird;
bool isSquirrel;
bool isBad;
bool isAlive;
MySprite * sprite; //current sprite
//it is possible that you can have more than one sprites
//vector<MySprite *> sprites; //the sprites
};
class MyZombieAgent : public MyAgent
{
public:
MyZombieAgent(bool movable=true, bool collision=true)
:MyAgent(movable, false, collision){
orig_x=INT_MAX; left=true; collide_with=NULL;
this->isBad = true;
}
virtual void update();
virtual void display();
virtual void handle_event(SDL_Event & e);
private:
int orig_x;
bool left;
MyAgent * collide_with;
int collision_free_timer=10;
};
class MyChickenAgent : public MyAgent
{
public:
MyChickenAgent(bool movable=true, bool collision=true):MyAgent(movable,collision, false)
{radius=FLT_MAX; center_x=center_y=INT_MAX; ccw=false; collide_with=NULL;
this->isBad = true;
}
virtual void update();
virtual void display();
virtual void handle_event(SDL_Event & e);
private:
float radius;
int center_x, center_y;
bool ccw;
MyAgent * collide_with;
int collision_free_timer=10;
};
class MyNetAgent : public MyAgent
{
public:
MyNetAgent(bool movable = false, bool collision = true) :MyAgent(false, true, false, true)
{
//radius = FLT_MAX; center_x = center_y = INT_MAX; ccw = false; collide_with = NULL;
}
//virtual void update();
//virtual void display();
//virtual void handle_event(SDL_Event & e);
private:
//float radius;
//int center_x, center_y;
//bool ccw;
//MyAgent * collide_with;
//int collision_free_timer = 10;
};
class MyPondAgent : public MyAgent
{
public:
MyPondAgent(bool movable = false, bool collision = true) :MyAgent(false, false, true, true)
{
//radius = FLT_MAX; center_x = center_y = INT_MAX; ccw = false; collide_with = NULL;
}
//virtual void update();
//virtual void display();
//virtual void handle_event(SDL_Event & e);
private:
//float radius;
//int center_x, center_y;
//bool ccw;
//MyAgent * collide_with;
//int collision_free_timer = 10;
};
}//end namespace
<file_sep>/README.md
# Bird-and-Squirrel-The-Get-to-the-Friend-Puzzle-Game
sfoye CS425 final project
Team members: <NAME>
Game name: Bird and Squirrel: The Get-to-the-Friend Puzzle Game
The game takes place in a top-down 2d grid. The player solves puzzles by moving Bird and Squirrel the goal, where the goal is to meet each other, while maneuvering past various obstacles.
The game uses motion planning, as the bird and squirrel will need to move to where the player clicks
The game also uses level loading where users can make levels in a text file to play
The game uses the engine from our PA assignments, specifically from PA03-Pathing
The game is interesting/exciting because it will allow the player to control multiple agents separately
Controls:
Move Bird: left click or wasd
Move Squirrel: right click or arrow keys
Objective:
Get Bird and Squirrel to meet each other
Obstacles:
Bird and Squirrel can each pass by some obstacles that the other can't.
Bird can fly past water while Squirrel is blocked by water.
Squirrel can go under nets while Bird is blocked by nets.
Chickens will kill Bird but fly past Squirrel.
Zombies will kill Squirrel but Bird will fly past zombies.
|
4837297f31286cc536561bc5e6fd68825242d7bb
|
[
"Markdown",
"C++"
] | 3
|
C++
|
SeabassJames/Bird-and-Squirrel-The-Get-to-the-Goal-Puzzle-Game
|
8dfc7669cb4d913354a5a9d5f5f9b5b744066aa4
|
bc7d208c3f4f3d013bc7ab626a29f671d6525b8f
|
refs/heads/master
|
<file_sep>const c1 = () => import(/* webpackChunkName: "page--src--templates--project-post-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/templates/ProjectPost.vue")
const c2 = () => import(/* webpackChunkName: "page--src--templates--journal-post-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/templates/JournalPost.vue")
const c3 = () => import(/* webpackChunkName: "page--src--pages--journal-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/pages/Journal.vue")
const c4 = () => import(/* webpackChunkName: "page--src--pages--contact-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/pages/Contact.vue")
const c5 = () => import(/* webpackChunkName: "page--src--pages--about-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/pages/About.vue")
const c6 = () => import(/* webpackChunkName: "page--node-modules--gridsome-0-7-23-gridsome--app--pages--404-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/node_modules/_gridsome@0.7.23@gridsome/app/pages/404.vue")
const c7 = () => import(/* webpackChunkName: "page--src--pages--index-vue" */ "/Users/zhangziru/font-end/Gridsome-demo/my-gridsome-site/src/pages/Index.vue")
export default [
{
path: "/projects/sunk/",
component: c1
},
{
path: "/journal/use-gridsome-vuejs/",
component: c2
},
{
path: "/projects/ios-concept/",
component: c1
},
{
path: "/journal/macos-development-environment/",
component: c2
},
{
path: "/projects/chelsea-landmark/",
component: c1
},
{
path: "/journal/gridsome-forestry-cms/",
component: c2
},
{
path: "/journal/a-journal-entry/",
component: c2
},
{
path: "/projects/3d-graff/",
component: c1
},
{
path: "/journal/",
component: c3
},
{
path: "/contact/",
component: c4
},
{
path: "/about/",
component: c5
},
{
name: "404",
path: "/404/",
component: c6
},
{
name: "home",
path: "/",
component: c7
},
{
name: "*",
path: "*",
component: c6
}
]
|
a686b38c3f2db38ef339c2f304c02848944276ee
|
[
"JavaScript"
] | 1
|
JavaScript
|
Norazz/gridsome-blog
|
c8f0540ee9c1483e36e4c96a832cb6a30a26ea17
|
45171276b18f4f906dd1afc15b8b88a461c275ad
|
refs/heads/master
|
<repo_name>Sevencloud0217/Login<file_sep>/boke/boke/bokeson/migrations/0002_auto_20190916_1000.py
# Generated by Django 2.2.1 on 2019-09-16 02:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bokeson', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'verbose_name_plural': '文章'},
),
migrations.AlterModelOptions(
name='author',
options={'verbose_name_plural': '作者'},
),
migrations.AlterModelOptions(
name='type',
options={'verbose_name_plural': '类型'},
),
migrations.AlterField(
model_name='article',
name='auther',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='bokeson.Author', verbose_name='所属作者'),
),
migrations.AlterField(
model_name='article',
name='content',
field=models.TextField(verbose_name='主题'),
),
migrations.AlterField(
model_name='article',
name='date',
field=models.DateField(auto_now=True, verbose_name='日期'),
),
migrations.AlterField(
model_name='article',
name='description',
field=models.TextField(verbose_name='描述'),
),
migrations.AlterField(
model_name='article',
name='title',
field=models.CharField(max_length=32, verbose_name='文章'),
),
migrations.AlterField(
model_name='article',
name='type',
field=models.ManyToManyField(to='bokeson.Type', verbose_name='所属类型'),
),
migrations.AlterField(
model_name='author',
name='age',
field=models.IntegerField(verbose_name='年龄'),
),
migrations.AlterField(
model_name='author',
name='email',
field=models.CharField(max_length=32, verbose_name='邮箱'),
),
migrations.AlterField(
model_name='author',
name='gender',
field=models.IntegerField(choices=[(1, '男'), (2, '女')], verbose_name='性别'),
),
migrations.AlterField(
model_name='author',
name='name',
field=models.CharField(max_length=32, verbose_name='作者名字'),
),
migrations.AlterField(
model_name='type',
name='description',
field=models.TextField(verbose_name='类型描述'),
),
migrations.AlterField(
model_name='type',
name='name',
field=models.CharField(max_length=32, verbose_name='类型名字'),
),
]
<file_sep>/boke/boke/bokeson/migrations/0006_auto_20190916_2120.py
# Generated by Django 2.2.1 on 2019-09-16 13:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bokeson', '0005_auto_20190916_2112'),
]
operations = [
migrations.AddField(
model_name='article',
name='click',
field=models.ImageField(default=0, upload_to='', verbose_name='点击率'),
),
migrations.AddField(
model_name='article',
name='recommend',
field=models.ImageField(default=0, upload_to='', verbose_name='推荐'),
),
]
<file_sep>/boke/boke/bokeson/models.py
from django.db import models
from ckeditor.fields import RichTextField
# Create your models here.
GENDER_LIST=(
(1,'男'),
(2,'女')
)
class Author(models.Model):
name=models.CharField(max_length=32,verbose_name='作者名字')
age=models.IntegerField(verbose_name='年龄')
# gender=models.CharField(max_length=8,verbose_name='性别')
gender=models.IntegerField(choices=GENDER_LIST,verbose_name='性别')
email=models.CharField(max_length=32,verbose_name='邮箱')
def __str__(self):
return self.name
class Meta:
db_table='auther'
verbose_name_plural='作者'
class Type(models.Model):
name=models.CharField(max_length=32,verbose_name='类型名字')
description=models.TextField(verbose_name='类型描述')
def __str__(self):
return self.name
class Meta:
db_table='type'
verbose_name_plural='类型'
class Article(models.Model):
title=models.CharField(max_length=32,verbose_name='文章')
date=models.DateField(auto_now=True,verbose_name='日期')
# content=models.TextField(verbose_name='内容')
content =RichTextField()
# description=models.TextField(verbose_name='描述')
description = RichTextField()
#图片类型
picture=models.ImageField(upload_to='images')
#推荐
recommend=models.IntegerField(verbose_name='推荐',default=0)
#点击率
click=models.IntegerField(verbose_name='点击率',default=0)
author=models.ForeignKey(to=Author,on_delete=models.SET_DEFAULT,default=1,verbose_name='所属作者')
type=models.ManyToManyField(to=Type,verbose_name='所属类型')
def __str__(self):
return self.title
class Meta:
db_table='article'
verbose_name_plural='文章'
class User(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=32)
class Meta:
db_table='user'<file_sep>/boke/boke/bokeson/migrations/0005_auto_20190916_2112.py
# Generated by Django 2.2.1 on 2019-09-16 13:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bokeson', '0004_auto_20190916_2100'),
]
operations = [
migrations.AlterField(
model_name='article',
name='pricture',
field=models.ImageField(default='boke/static/images/01.jpg', upload_to='images'),
),
]
<file_sep>/demo/app01/models.py
from django.db import models
# Create your models here.
class Person(models.Model):
# id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32,verbose_name='姓名')
age=models.IntegerField(verbose_name='性别')
height=models.DecimalField(max_digits=5,decimal_places=2,verbose_name='身高')
birthday=models.DateField(verbose_name='生日')
def __str__(self):
return self.name
class Meta:
db_table='persion'#修改名字
verbose_name='用户'
verbose_name_plural=verbose_name
class Publish(models.Model):
name=models.CharField(max_length=32,verbose_name='出版社')
address=models.CharField(max_length=32,verbose_name='地址')
def __str__(self):
return self.name
class Meta:
db_table='publish'
verbose_name_plural='出版社'
class Book(models.Model):
name = models.CharField(max_length=32,verbose_name='书名')
num=models.IntegerField(default=10)
stell=models.IntegerField(default=10)
publish = models.ForeignKey(to=Publish,to_field='id',on_delete=models.DO_NOTHING,verbose_name='出版社')
def __str__(self):
return self.name
class Meta:
db_table = 'book'
verbose_name_plural='书本'
class Teacher(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
gender=models.CharField(max_length=12)
person = models.ManyToManyField(to=Person)
class Meta:
db_table='teacher'<file_sep>/demo/app02/models.py
from django.db import models
# Create your models here.
class Seven(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
age=models.IntegerField()
height=models.DecimalField(max_digits=5,decimal_places=2)
birthday=models.DateField()<file_sep>/demo/app01/urls.py
from django.urls import path,re_path,include
from .views import *
# from app01 import views as app01views
urlpatterns = [
path('index/',index),
path('addperson/',addperson),
path('queryset/',queryset),
path('updata/',updata),
path('drop/',drop),
path('addonemore/',addonemore),
path('getonemore/',getonemore),
path('updataonemore/',updataonemore),
path('deleteonemore/',deleteonemore),
path('manytomanyadd/',manytomanyadd),
path('manytomanyget/',manytomanyget),
path('manytomanyupdate/',manytomanyupdate),
path('manytomanydelete/',manytomanydelete),
path('jhtest/',jhtest),
path('Ftest/',Ftest),
path('Qtest/',Qtest),
]
<file_sep>/boke/boke/bokeson/migrations/0007_auto_20190916_2125.py
# Generated by Django 2.2.1 on 2019-09-16 13:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bokeson', '0006_auto_20190916_2120'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='pricture',
),
migrations.AddField(
model_name='article',
name='picture',
field=models.ImageField(default='images/01.jpg', upload_to='images'),
preserve_default=False,
),
]
<file_sep>/boke/boke/bokeson/migrations/0003_auto_20190916_1551.py
# Generated by Django 2.2.1 on 2019-09-16 07:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bokeson', '0002_auto_20190916_1000'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='auther',
new_name='author',
),
migrations.AddField(
model_name='article',
name='pricture',
field=models.ImageField(default='images/01.jpg', upload_to='images'),
preserve_default=False,
),
migrations.AlterField(
model_name='article',
name='content',
field=models.TextField(verbose_name='内容'),
),
]
<file_sep>/demo/app01/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
def index(request):
return HttpResponse('hello')
def addperson(request):
#1.save
#第一种
# person = Person(name='lisi',age=19,height=170,birthday='1999-08-08')
# person.save()
#第二种
# person=Person()
# person.name='mingming'
# person.age=17
# person.height=180
# person.birthday='1998-08-07'
# person.save()
# return HttpResponse('增加数据')
#crate
# data=dict(name='xiaohong',age=17,height=190,birthday='1992-02-18')
# Person.objects.create(**data)
return HttpResponse('增加数据')
#查询
def queryset(request):
#all方法
# data=Person.objects.all()
# print(data)
#get
# data=Person.objects.get(id=1)
# print(data.name)
# print(data.age)
#filter
# data=Person.objects.filter(name='lisi')
# print(data)
#first方法和last
# data=Person.objects.filter(name='wangwu').first()
# print(data.age)
# data=Person.objects.filter(name='wangwu').last()
# print(data.age)
#order_by
# data=Person.objects.order_by('age')
# for one in data:
# print(one.age)
#exclud
# data=Person.objects.exclude(name='wangwu')
# for one in data:
# print(one.name)
#reverse对查询结果反向排序 逆序
# data=Person.objects.order_by('-id').reverse()
# print(data)
# value queryset[对象,对象]
# data=Person.objects.filter(name='wangwu').values()
# print(data)
#count
# data=Person.objects.filter(name='wangwu').count()
# print(data)
#切片
# data = Person.objects.order_by('id')[2:5]
# print(data)
#双下划线查询
#__lt小于
# data=Person.objects.filter(id__lt=3)
# print(data)
#gt
# data=Person.objects.filter(id__gt=3)
# print(data)
#gte
# data=Person.objects.filter(id__gte=3)
# print(data)
#in 包含 select * from stu where id in [1,2,3];
# data=Person.objects.filter(id__in=[1,2,3])
# print(data)
#excloude 不包含
#range 范围
# data=Person.objects.filter(id__range=[1,5])
# print(data)
#startswith 像 like j% endswith 像 %j
# data= Person.objects.filter(name__startswith='w')
# print(data)
#endswith是后边结尾
#__contains 包含 大小敏感
# data=Person.objects.filter(name__contains='m')
# print(data)
#__icontains 包含 大小写不敏感
# ss=Person.objects.filter(name__icontains='m')
# print(ss)
return HttpResponse('查询数据')
def updata(request):
#save
#先查询查询到数据,然后重新赋值进行,然后save复制
# data=Person.objects.get(id=2)
# data.name='python'
# data.save()
# data=Person.objects.filter(name='wangwu').all()
# for one in data:
# if one.id==4:
# one.age=22
# else:
# one.age=19
# one.save()
#updata
# Person.objects.filter(id=3).update(name='Mary')
return HttpResponse('修改数据')
def drop(request):
#delete
# Person.objects.filter(id=6).delete()
return HttpResponse('删除数据')
#一对多增加
def addonemore(request):
#增加出版社
# Publish.objects.create(name='清华出版社',address='北京')
# Publish.objects.create(name='河南出版社',address='河南')
# Publish.objects.create(name='河北出版社',address='河北')
# #增加书
# Book.objects.create(name='python入门',publish_id=1)
# Book.objects.create(name='web入门',publish_id=1)
#第二种方法
# publish=Publish.objects.get(name='河南出版社')
# Book.objects.create(name='docker入门',publish_id=publish.id)
#第三种方法
#正向操作 从外键所在的表到主表叫正向
# book=Book()
# # book.name='笨办法学web'
# # book.publish=Publish.objects.get(name='河南出版社')
# # book.save()
#反向操作 从主表到从表 叫反向
# publish_obj=Publish.objects.get(name='河北出版社')
# publish_obj.book_set.create(name='pythonweb开发')
return HttpResponse("一对多关系增加")
#一对多查询
def getonemore(request):
#第一种查询方法
# publish=Publish.objects.get(name='清华出版社')
# book=Book.objects.filter(publish_id=publish.id).all()
# for one in book:
# print(one.name)
#第二种查询方法
#正向查询 从外键所在的表到主表 叫正向
book = Book.objects.filter(name='pythonWeb开发').first()
print(book.name)
print(book.publish.name)
#第三种查询
#反向查询 从主键到外键所在的表 叫反向
publish=Publish.objects.get(name='河北出版社')
book=publish.book_set.all()
for one in book:
print(one.name)
return HttpResponse("一对多关系查询")
#一对多修改
def updataonemore(request):
#save 方法
# book=Book.objects.filter(name='mysql入门',id=5).first()
# book=Book.objects.get(id=5)
# book.publish=Publish.objects.get(name='清华出版社')
# book.save()
#update
# Book.objects.filter(name='mysql入门',id=5).update(publish=Publish.objects.get(name='河北出版社'))
#set
# publish=Publish.objects.get(name='河南出版社')
# book=Book.objects.get(id=3)
# book_s=Book.objects.get(id=5)
# publish.book_set.set([book,book_s])
return HttpResponse("一对多关系修改")
#一对多删除
def deleteonemore(request):
return HttpResponse("一对多关系删除")
#多对多
def manytomanyadd(request):
#老师
# Teacher.objects.create(name='laozhang',gender='女',age=32)
# Teacher.objects.create(name='老王',gender='女',age=32)
# Teacher.objects.create(name='老边',gender='男',age=32)
# Teacher.objects.create(name='老岳',gender='女',age=32)
# Teacher.objects.create(name='老云',gender='男',age=32)
#新学生 创建关系 create 正向操作
# teacher_obj=Teacher.objects.filter(name='老边').first()
# teacher_obj.person.create(name='Jason',age=17,height=170,birthday='1888-09-07')
#老学生 创建关系 add 正向操作
# teacher_obj=Teacher.objects.filter(name='老岳').first()
# person_obj=Person.objects.filter(name='mingming').first()
# teacher_obj.person.add(person_obj)
#反向操作
# teacher_obj=Teacher.objects.filter(name='laozhang').first()
# person_obj=Person.objects.filter(name='Jason').first()
# person_obj.teacher_set.add(teacher_obj)
return HttpResponse('多对多添加')
def manytomanyget(request):
#正向查询
teacher_obj=Teacher.objects.filter(name='laozhang').first()
person=teacher_obj.person.all().values()
print(person)
#反向查询
person_obj=Person.objects.filter(name='Jason').first()
teacher_obj=person_obj.teacher_set.all().values()
print(teacher_obj)
return HttpResponse('多对多查询')
def manytomanyupdate(request):
#正向
#第一种
# teacher_obj=Teacher.objects.filter(name="laozhang").first()
# teacher_obj.person.set([1,2,3,4,])
#第二种
# teacher_obj=Teacher.objects.filter(name='老王').first()
# person1 = Person.objects.filter(name='wy').first()
# person2=Person.objects.filter(name='xiaohong').first()
# teacher_obj.person.set([person1,person2])
#反向
# 第一种
# person_obj=Person.objects.filter(name='mingming').first()
# person_obj.teacher_set.set([2])
#第二种
person_obj = Person.objects.filter(name='wy').first()
teacher1 = Teacher.objects.filter(name='老王').first()
teacher2 = Teacher.objects.filter(name='老岳').first()
person_obj.teacher_set.set([teacher1,teacher2])
return HttpResponse('多对多修改')
def manytomanydelete(request):
# remove
# 正向
# person_obj=Person.objects.filter(name='mingming').first()
# teacher_obj=Teacher.objects.filter(name='老岳').first()
# teacher_obj.person.remove(person_obj)
#反向
# person_obj = Person.objects.filter(name='lisi').first()
# teacher_obj=Teacher.objects.filter(name='laozhang').first()
# person_obj.teacher_set.remove(teacher_obj)
# delete
# 删除老师
# Teacher.objects.filter(name='laozhang').first().delete()
#删除同学
# Person.objects.filter(name='lise').delete()
return HttpResponse('多对多删除')
from django.db.models import *
def jhtest(request):
data=Person.objects.all().aggregate(Avg('age'))
print(data)
data=Person.objects.all().aggregate(avg_age=Avg('age'),sum_age=Sum('age'))
print(data)
return HttpResponse('聚合函数,查询')
#F对象
def Ftest(request):
##查询存num 大于销量salled num_get=3
data=Book.objects.filter(num__gt=F('stell'))
print(data)
return HttpResponse('F 对象')
def Qtest(request):
# data=Book.objects.filter(Q(num=10)&Q(stell=100))
# print(data)
data = Book.objects.filter(Q(num=10)|Q(stell=100)).all()
print(data)
data = Book.objects.filter(~Q(num=10) | ~Q(stell=100)).all()
print(data)
return HttpResponse('Q对象')<file_sep>/boke/boke/bokeson/apps.py
from django.apps import AppConfig
class BokesonConfig(AppConfig):
name = 'bokeson'
<file_sep>/boke/boke/boke/views.py
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render
from bokeson.models import *
def loginVaild(fun):
def inner(request,*arge,**kwargs):
username = request.COOKIES.get('username')
username_session=request.session.get('username')
print(username_session)
if username:
return fun(request,*arge,**kwargs)
else:
return HttpResponseRedirect('/login/')
return inner
@loginVaild
def about(request):
return render(request,'about.html')
@loginVaild
def index(request):
#获取cookie 获取用户名
# username= request.COOKIES.get('username')
# print(request.COOKIES)
# print(username)
# if username:
#来源
url = request.META.get('HTTP_REFERER')
print(url)
article = Article.objects.order_by('-date')[:6]
recommend_acticle=Article.objects.order_by('-date').all()[:7]
click_article=Article.objects.order_by('-click')[:12]
# else:
# return HttpResponseRedirect('/login/')
return render(request, 'index.html', locals())
def listpic(request):
return render(request,'listpic.html')
def newslistpic(request,type,page=1):
page=int(page)
# article=Article.objects.order_by('-date')
article = Type.objects.get(name=type).article_set.order_by("-date")
paginator = Paginator(article,6)#每页6个
page_obj = paginator.page(page)
#获取当前页
current_page = page_obj.number
start = current_page - 3
if start < 1:
start=0
end = current_page + 2
if end > paginator.num_pages:
end = paginator.num_pages
if start == 0:
end = 5
if end == 17:
start=12
page_range = paginator.page_range[start:end]
return render(request,'newslistpic.html',locals())
def base(request):
return render(request,'base.html')
def addariticle(request):
# for x in range(100):
# article=Article()
# article.title='title_%s'%x
# article.content='content_%s'%x
# article.description='description_%s'%x
# article.auther=Article.objects.first()
# article.save()
# article.type.add(Type.objects.first())
# article.save()
return HttpResponse('增加数据')
def xiangxi(request,id):
article=Article.objects.get(id=int(id))
return render(request,'xiangxi.html',locals())
from django.core.paginator import Paginator
def fytest(request):
article=Article.objects.all().order_by("-date")
# print(article)
#每次显示 5条数据
paginator =Paginator(article,5)#设置每一页显示多少条数据
# print(paginator.count)#返回内容的总条数
# print(paginator.page_range)#可迭代内容的总条数
# print(paginator.num_pages)#最大页数
# page_obj=paginator.page(2)
# print(page_obj)
# for one in page_obj:
# print(one.content)
# print(page_obj.number)#当前的页数
# print(page_obj.has_next())#有没有下一页
# print(page_obj.has_previous())#有没有上一页
# print(page_obj.next_page_number())#返回下一页的页码
# print(page_obj.previous_page_number())#返回上一页
return HttpResponse('分页管理')
def reqtest(request):
##获取get请求传递的参数
# data=request.GET
#获取post的请求参数
data = request.POST
print(data)
print(data.get('name'))
print(type(data.get('name')))
print(data.get("age"))
return HttpResponse("姓名:%s年龄:%s"%(data.get("name"),data.get('age')))
# print(dir(request))
# print(request.COOKIES)
# print(request.FILES)
# print(request.GET)
# print(request.POST)
# print(request.scheme)
# print(request.method)
# print(request.path)
#
# print(request.body)
# meta=request.META
# print(meta)
# for key in meta:
# print(key)
# print('*******')
# print(request.META.get('OS'))
# print(request.META.get('HTTP_USER_AGENT'))
# print(request.META.get('HTTP_HOST'))
# print(request.META.get('HTTP_REFERE'))
# return HttpResponse('请求测试')
def fromtest(request):
#get请求
data=request.GET
serach=data.get('serach',"")
print(serach)
#通过from提交的数据
#通过模型查询
article=Article.objects.filter(title__contains=serach).all()
print(article)
print(request.method)
data=request.POST
print(data.get('username'))
print(data.get('password'))
return render(request,"fromtest.html",locals())
from bokeson.froms import Register
# def register(request):
# register_form = Register() #返回一个form表单
# if request.method=="POST":
# # username=request.POST.get("username")
# username=request.POST.get("name")
# password=request.POST.get("password")
# content = '参数不全'
# if username and password:
# # if password != <PASSWORD>:
# # content='两次密码不一样'
# # pass
# # else:
# user = User()
# user.name=username
# # user.password=<PASSWORD>
# #加密密码
# user.password = setPassword(password)
# user.save()
# content='添加成功'
# return render(request,"register.html",locals())
import hashlib
def setPassword(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
def register(request):
register_form = Register() #返回一个form表单
error=""
if request.method=="POST":
# username=request.POST.get("username")
data=Register(request.POST)#将post请求过来的数据,交给from表单进行效验
if data.is_valid(): #判断效验是否通过,通过 返回一个Ture否则 是通过False
clean_data = data.cleaned_data
# 获取数据库
username=clean_data.get("name")
password=clean_data.get("password")
user = User()
user.name = username
#加密密码
user.password = <PASSWORD>)
user.save()
error='添加成功'
else:
error = data.errors
print(error)
return render(request,"register.html",locals())
def ajax_get(request):
return render(request,'ajax_get.html')
def ajax_get_data(request):
result = {"code":10000,"content":""}
data = request.GET
username = data.get('username')
password = data.get('<PASSWORD>')
if len(password) == 0 or len(password) == 0:
result['code'] = 10001
result['content'] = '请求参数为空'
else:
user=User.objects.filter(name=username,password=<PASSWORD>(<PASSWORD>)).first()
if user:
result["code"]=10000
result["content"]='用户可登入'
else:
result["code"] = 10002
result["content"] = '用户名的密码不存在'
return JsonResponse(result)
# return HttpResponse('ajax的请求')
def ajax_post(request):
return render(request,"ajax_post.html")
def ajax_post_data(request):
result = {}
username = request.POST.get('username')
password = request.POST.get("password")
print(request.POST)
print (username)
if len(username) == 0 or len(password) == 0:
result['code'] = 10001
result['content'] = '请求参数为空'
else:
user = User()
user.name=username
user.password=<PASSWORD>(<PASSWORD>)
# user=User.objects.filter(name=username,password=setPassword(password)).first()
# if user:
try:
user.save()
result["code"]=10000
result["content"]='添加成功'
except:
result["code"] = 10002
result["content"] = '用户名的密码不存在'
return JsonResponse(result)
##效验账户是否存在
def checkusername(request):
result = {'code':10001,'content':""}
#get 请求
username =request.GET.get('name')
print(username)
#判断用户是否存在
user = User.objects.filter(name=username).first()
print(user)
if user:
result = {"code":10001,'content':"用户已存在"}
else:
result = {'code':10000,"content":'用户不存在'}
return JsonResponse(result)
from django.http import HttpResponseRedirect
def login(request):
result=''
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('<PASSWORD>')
user = User.objects.filter(name=username).first()
if user:
if user.password == <PASSWORD>(password):
# # 密码正确
# #跳转首页 状态码
# return HttpResponseRedirect('/index/')
response = HttpResponseRedirect('/index/')
response.set_cookie('username',username)
request.session['username']=username
return response
return render(request,"login.html")
#登出
def logout(request):
response = HttpResponseRedirect('/index/')
response.delete_cookie('username')
del request.session['username']#删除指定的
request.session.flush()#删除所有的
return response<file_sep>/demo/app01/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-09-11 02:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Person',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='姓名')),
('age', models.IntegerField(verbose_name='性别')),
('height', models.DecimalField(decimal_places=2, max_digits=5, verbose_name='身高')),
('birthday', models.DateField(verbose_name='生日')),
],
options={
'db_table': 'persion',
'verbose_name': '用户',
'verbose_name_plural': '用户',
},
),
migrations.CreateModel(
name='Publish',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32)),
('address', models.CharField(max_length=32)),
],
options={
'db_table': 'publish',
},
),
]
<file_sep>/demo/app01/migrations/0007_auto_20190912_1516.py
# Generated by Django 2.2.1 on 2019-09-12 07:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app01', '0006_teacher_age'),
]
operations = [
migrations.AddField(
model_name='book',
name='num',
field=models.IntegerField(default=10),
),
migrations.AddField(
model_name='book',
name='stell',
field=models.IntegerField(default=10),
),
]
|
9c818d6dc539239d0199bac02ec9ed762e02cf29
|
[
"Python"
] | 14
|
Python
|
Sevencloud0217/Login
|
ac8797b0fc3c230ae06399ee18b17b406009b2d9
|
86ee715919ac285aec0ef3c4edaad8e6c7898f1f
|
refs/heads/master
|
<repo_name>janzenz/learning-redux<file_sep>/webpack.config.js
var webpack = require('webpack')
var path = require('path')
// Represent the directory path of the bundle file output
var BUILD_DIR = path.resolve(__dirname, 'public/assets/js/')
// Holds the directory path of the application codebase
var APP_DIR = path.resolve(__dirname, 'src/')
var config = {
// Specifies the entry file where the bundling process starts.
// It also supports multiple entry points.
entry: APP_DIR + '/index.js',
// Instructs Webpack what to do after the bundling process has been completed.
// Here we are instructing it to output the bundled file under BUILD_DIR with the
// name of bundle.js
output: {
path: BUILD_DIR, // string
// the target directory for all output files
filename: 'bundle.js',
// the filename template for entry chunks
publicPath: '/assets/js/'
// the url to the output directory resolved relative to the HTML page
},
module: {
rules: [
{
test: /\.jsx?$/, // Accepts both .js and .jsx files using regex
include: [
APP_DIR // Specifies what is the directory to be used to look for those recursively
],
//issuer: {test, include},
// Loader are what Webpack uses to transpile the code base and translate it to
// a browser readable version. Here the *loaders* property accepts an array of
// loaders.
loader: 'babel-loader' // Represents the name of the loader
}
]
},
devtool: "cheap-eval-source-map",
devServer: {
contentBase: path.join(__dirname, "public"),
compress: true,
port: 8080,
historyApiFallback: true
}
}
module.exports = config
<file_sep>/src/components/TodoList.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import TodoItem from './TodoItem'
import * as actions from '../actions'
class TodoList extends Component {
_onTodoClick = (id) => {
this.props.dispatch(actions.toggleTodo(id))
}
render() {
const { todos } = this.props;
return <ul>
{todos.map(todo =>
<TodoItem
key={todo.id}
{...todo}
onTodoClick={this._onTodoClick}
/>
)}
</ul>
}
}
TodoList.propType = {
todos: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
complete: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}).isRequired)
}
const calculateTodos = (state, filter) => {
switch(filter) {
case actions.VisibilityFilters.SHOW_COMPLETED:
return state.todos.filter(t => t.completed)
case actions.VisibilityFilters.SHOW_ACTIVE:
return state.todos.filter(t => !t.completed)
case actions.VisibilityFilters.SHOW_ALL:
default:
return state.todos
}
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(actions.toggleTodo(id))
}
}
}
const mapStateToProps = (state, ownProps) => {
return {
todos: calculateTodos(state, ownProps.filter)
}
}
export default connect(mapStateToProps)(TodoList)
<file_sep>/src/reducers.js
/**
* Reducer is a PURE function that takes a previous state and an Action and returns a New State.
* (previousState, action) => newState
*/
/* It's a good idea to think of its shape before writing any code. */
/*
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
*/
import { combineReducers } from 'redux'
import * as constants from './actions.js';
const todoApp = combineReducers({
visibilityFilter,
todos
})
/* This code block is literrally the `combineReducers` implementation */
/*
const todoApp = (state = {}, action) => {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
}
}
*/
export default todoApp
/* Reducer compositions */
function visibilityFilter(state = constants.VisibilityFilters.SHOW_ALL, action) {
switch (action.type) {
case constants.SET_VISIBILITY_FILTER:
return action.filter
default:
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case constants.ADD_TODO:
return [
...state,
{
id: action.id,
text: action.text,
completed: false
}
]
case constants.TOGGLE_TODO:
return state.map((todo) => {
if (todo.id === action.index) {
return Object.assign({}, todo, {
completed: !todo.completed
})
}
return todo
})
default:
return state
}
}
<file_sep>/README.md
These are my notes learning Redux, some phrases are directly copied from the Redux documentation but I will try to update this next time and make it more personalized. #note-to-self
## Tips
- Start with one file for your app to easily identify the relationships of the Actions > Reducers > Store
- If you need to, spell out the variables, don't neglect the tedium of learning what's inside each abstraction.
Here's a quick diagram of how a Redux workflow:
`Root Reducer -> store.dispatch() [Actions (Action Creators)] -> (Old) Store -> Reducers (Entire State) -> (New) Store -> Components -> (Repeat)`
## Actions
Actions are payloads of information that send data from the application to the store. They are the only source of information for the store. There are two types of Actions:
- Action Type (Constants)
- Action Creators (Creates the Actions to be done by the Reducers)
## Reducers
Action specifies the work to be done while Reducers do the work and mutate the state. In my own understand, the Reducers define the data structure of your state.
Redux provides a utility called `combineReducers()` which basically creates a single Reducer from a bunch of Reducers, this is how it works:
```
export default function todoApp(state = {}, action) {
return {
visibilityFilter: visibilityFilter(state.visibilityFilter, action),
todos: todos(state.todos, action)
}
}
```
To this:
```
const todoApp = combineReducers({
visibilityFilter,
todos
})
```
The output of a Reducer is just a Javascript Object that consists the mutated state (not modified because it's an entirely new instance of the old one).
## Store
Notice the singular word Store unlike the Actions & Reducers. In Redux there should only be ONE Store to manage your Application State, it is a ONE source of truth which I think is the gist of Redux. This is important in order to understand your Application State easily and so you can have an overview of the current State of your Application. A Store is just a container of your Application's State (both UI and Data).
To initialize the Store we can do:
```
const initialState = {
dummy: 'This does not matter, this will be overwritten by
what is returned by the root reducer or todosReducer
in this case.'
}
const store = createStore(todosReducer, initialState)
```
<file_sep>/src/components/AddTodo.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../actions'
class AddTodo extends Component {
_handleSubmit = (e) => {
e.preventDefault();
// Add to do here.
this.props.dispatch(actions.addTodo(this.textInput.value))
}
render() {
return <form onSubmit={this._handleSubmit}>
<input
type="text"
ref={ input => this.textInput = input }
/>
<input
type="submit"
value="Add"
onClick={this.focus}
/>
</form>
}
}
export default connect()(AddTodo)<file_sep>/src/components/TodoItem.js
import React, { Component, PropTypes } from 'react'
class TodoItem extends Component {
_onClick = (e) => {
this.props.onTodoClick(this.props.id)
}
render() {
const { id, text, completed } = this.props;
return <li
onClick={this._onClick}
style={{
textDecoration: completed ?
'line-through' :
'none'
}}
>
{text}
</li>
}
}
TodoItem.propType = {
id: PropTypes.number.isRequired,
complete: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}
export default TodoItem
<file_sep>/src/index.js
import React, { Component, PropTypes } from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux';
import { Router, Route, browserHistory } from 'react-router'
import configureStore from './store'
import DevTools from './components/DevTools'
import App from './components/App'
const store = configureStore()
const Root = ({ store }) => (
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/(:filter)" component={App} />
<DevTools />
</Router>
</Provider>
)
Root.propTypes = {
store: PropTypes.object.isRequired
}
render(<Root store={store} />, document.getElementById('app'))
<file_sep>/src/components/Footer.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import FilterLink from './FilterLink'
import * as actions from '../actions'
class Footer extends Component {
_handleFilter = (filter) => {
this.props.dispatch(actions.setVisibilityFilter(filter))
}
render() {
return <div>
<FilterLink filter={actions.VisibilityFilters.SHOW_COMPLETED} handleFilter={this._handleFilter}>
Show Completed
</FilterLink>{", "}
<FilterLink filter={actions.VisibilityFilters.SHOW_ACTIVE} handleFilter={this._handleFilter}>
Show Active
</FilterLink>{", "}
<FilterLink filter={actions.VisibilityFilters.SHOW_ALL} handleFilter={this._handleFilter}>
Show All
</FilterLink>
</div>
}
}
export default connect()(Footer)<file_sep>/src/components/FilterLink.js
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
class FilterLink extends Component {
render() {
const { filter, children } = this.props
return <Link
to={filter === 'all' ? '' : filter}
>
{children}
</Link>
}
}
FilterLink.propType = {
filter: PropTypes.string.isRequired
}
export default FilterLink
|
46bf3c123b1de037cf2a2dc49f3f9fa7aa729c58
|
[
"JavaScript",
"Markdown"
] | 9
|
JavaScript
|
janzenz/learning-redux
|
c17e4717103f4cce7e3a23fe19cd64174bb79386
|
8c5bdf17b796d0299b9d1c4fe7fd4262f39f79a7
|
refs/heads/master
|
<file_sep>package golangexamples
import "github.com/ehteshamz/greetings"
// returns the contents of the slice concatenated together and separated by a dash (-).
func ConcatSlice(sliceToConcat []byte) string {
concatedString := ""
for i,elem := range sliceToConcat{
concatedString+=string(elem)
if i!=len(sliceToConcat)-1 {
concatedString+="-"
}
}
return concatedString
}
func Encrypt(sliceToEncrypt []byte, ceaserCount int) {
for i,_ := range sliceToEncrypt{
sliceToEncrypt[i]+=byte(ceaserCount)
}
}
func EZGreetings(name string) string {
return greetings.PrintGreetings(name)
}
|
5583765a4e31f68e045c1e0b482bd52d3f246a48
|
[
"Go"
] | 1
|
Go
|
mairafarooq97/golangexamples
|
abf88255d07b505a40029f636103d3650aceda71
|
c3e2e74280a99a0f61fce41e4d9d75502ebc9ac0
|
refs/heads/master
|
<file_sep>#include "crash.h"
#include <complex.h>
#include <inttypes.h>
#include <stdio.h>
void enable_alignment_check(void);
typedef complex double cdbl;
int main(void) {
enable_alignment_check();
/* An overlay of complex values and bytes. */
union {
cdbl val[2];
unsigned char buf[sizeof(cdbl[2])];
} toocomplex = {
.val =
{
0.5 + 0.5 * I,
0.75 + 0.75 * I,
},
};
printf("size/alignment:␣%zu/%zu\n", sizeof(cdbl), _Alignof(cdbl));
/* Run over all offsets, and crash on misalignment. */
for (size_t offset = sizeof(cdbl); offset; offset /= 2) {
printf("offset\t%zu:\t", offset);
fflush(stdout);
cdbl *bp = (cdbl *)(&toocomplex.buf[offset]); // align!
printf("%g\t+%gI\t", creal(*bp), cimag(*bp));
fflush(stdout);
*bp *= *bp;
printf("%g\t+%gI", creal(*bp), cimag(*bp));
fputc(’\n’, stdout);
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* typedef enum { false, true } bool; */
/* (C99) */
#include "euclid.h"
#include <stdbool.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
#ifndef RATIONALS_H
#define RATIONALS_H 1
/* from now on `struct rat` will be known as `rat` */
typedef struct rat rat;
/* this is the definition of a rational number */
struct rat {
bool sign;
size_t num;
size_t denom;
};
/* Functions that return a value of type rat. */
rat rat_get(long long num, unsigned long long denom);
rat rat_get_normal(rat x);
rat rat_get_extended(rat x, size_t f);
rat rat_get_prod(rat x, rat y);
rat rat_get_sum(rat x, rat y);
/* Functions that operate on pointers to rat. */
void rat_destroy(rat *rp);
rat *rat_init(rat *rp, long long num, unsigned long long denom);
rat *rat_normalize(rat *rp);
rat *rat_extend(rat *rp, size_t f);
rat *rat_sumup(rat *rp, rat y);
rat *rat_rma(rat *rp, rat x, rat y);
#endif
rat rat_get(long long num, unsigned long long denom) {
rat ret = {
.sign = (num < 0),
.num = (num < 0) ? -num : num,
.denom = denom,
};
return ret;
}
rat rat_get_normal(rat x) {
size_t c = gcd(x.num, x.denom);
x.num /= c;
x.denom /= c;
return x;
}
rat rat_get_extended(rat x, size_t f) {
x.num *= f;
x.denom *= f;
return x;
}
rat rat_get_prod(rat x, rat y) {
x = rat_get_normal(x);
y = rat_get_normal(y);
rat ret = {
.sign = (x.sign != y.sign),
.num = x.num * y.num,
.denom = x.denom * y.denom,
};
return rat_get_normal(ret);
}
rat rat_get_sum(rat x, rat y) {
size_t c = gcd(x.denom, y.denom);
size_t ax = y.denom / c;
size_t bx = x.denom / c;
x = rat_get_extended(x, ax);
y = rat_get_extended(y, bx);
assert(x.denom == y.denom);
if (x.sign == y.sign) {
x.num += y.num;
} else if (x.num > y.num) {
x.num -= y.num;
} else {
x.num = y.num - x.num;
x.sign = !x.sign;
}
return rat_get_normal(x);
}
/*
In practice, both cases will usually behave differently. The first might
access some random object in memory and modify it. Often this leads to bugs
that are difficult to trace. The second, null, will nicely crash your
program. Consider this to be a feature.
*/
void double_swap(double *p0, double *p1) {
double tmp = *p0;
*p0 = *p1;
*p1 = tmp;
}
void double_swap_arr(double p0[static 1], double p1[static 1]) {
double tmp = p0[0];
p0[0] = p1[0];
p1[0] = tmp;
}
double sum0(size_t len, double const *a) {
double ret = 0.0;
for (size_t i = 0; i < len; ++i) {
ret += *(a + i);
}
return ret;
}
double sum1(size_t len, double const *a) {
double ret = 0.0;
for (double const *p = a; p < a + len; ++p) {
ret += *p;
}
return ret;
}
double sum2(size_t len, double const *a) {
double ret = 0.0;
for (double const *const aStop = a + len; a < aStop; ++a) {
ret += *a;
}
return ret;
}
void try_sum() {
double A[7] = {
0, 1, 2, 3, 4, 5, 6,
};
double s0_7 = sum0(7, &A[0]); // for the whole
double s1_6 = sum0(6, &A[1]); // for last 6
double s2_3 = sum0(3, &A[2]); // for 3 in the middle
(void)s0_7;
(void)s1_6;
(void)s2_3;
}
void matrix_mult(size_t n, size_t k, size_t m, double C[n][m], double A[n][k],
double B[k][m]) {
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
C[i][j] = 0.0;
for (size_t l = 0; l < k; ++l) {
C[i][j] += A[i][l] * B[l][j];
}
}
}
}
typedef int compare_function(void const *, void const *);
void *bsearch(void const *key, void const *base, size_t n, size_t size,
compare_function *compar);
void qsort(void *base, size_t n, size_t size, compare_function *compar);
int compare_unsigned(void const *a, void const *b) {
unsigned const *A = a;
unsigned const *B = b;
if (*A < *B)
return -1;
else if (*A > *B)
return +1;
else
return 0;
}
/* A header that provides searching and sorting for unsigned. */
/* No use of inline here, we always use the function pointer. */
size_t nmeb;
extern int compare_unsigned(void const *, void const *);
inline unsigned const *bsearch_unsigned(unsigned const key[static 1], size_t n,
unsigned const base[nmeb]) {
return bsearch(key, base, nmeb, sizeof base[0], compare_unsigned);
}
inline void qsort_unsigned(size_t n, unsigned base[nmeb]) {
qsort(base, nmeb, sizeof base[0], compare_unsigned);
}
/*
double f(double a);
// equivalent calls to f
// decay to function pointer
f(3);
// address of function
(&f)(3);
// decay to function pointer , then dereference , then decay
(*f)(3);
// address of function , then dereference , then decay
(*&f)(3);
// decay , dereference , address of
(&*f)(3);
*/
// in a header
typedef int logger_function(char const *, ...);
extern logger_function *logger;
enum logs { log_pri, log_ign, log_ver, log_num };
// in a TU
/*
extern int logger_verbose(char const *, ...);
static int logger_ignore(char const *, ...) { return 0; }
logger_function *logger = logger_ignore;
static logger_function *loggers = {
[log_pri] = [log_ign] = [log_ver] = printf,
logger_ignore,
logger_verbose,
};
*/
/* if (LOGGER < log_num) logger = loggers[LOGGER]; */
/* logger("Do␣we␣ever␣see␣line␣\%lu␣of␣file␣\%s?", __LINE__+0UL, __FILE__); */
/* Exercises
- [Exs 10]: The function rat_get_prod can produce intermediate values
that may have it produce wrong results, even if the mathematical
result of the multiplication is representable in rat. How is that?
- [Exs 11] Reimplement the rat_get_prod function such that it
produces a correct result all times that the mathematical result value
is representable in a rat. This can be done with two calls to
rat_get_normal instead of one.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_rat_get_prod(void **state) {
(void)state;
// definition: struct my_structure {char name[20]; int number; int rank; };
// initialise: struct my_structure variable = {"StudyTonight", 35, 1};
// pointerdef: struct my_structure *ptr;
// pointerass: ptr = &variable;
// printdebug: printf("NAME: %s\n", ptr->name);
// printdebug: printf("NUMBER: %d\n", ptr->number);
// printdebug: printf("RANK: %d", ptr->rank);
rat *a;
rat *b;
rat *actl;
rat *xpct;
xpct = &((rat){.sign = 0, .num = 5, .denom = 1});
a = &((rat){.sign = 0, .num = 10, .denom = 2});
b = &((rat){.sign = 0, .num = 1, .denom = 1});
rat r0 = rat_get_prod(*a, *b);
actl = &r0;
assert_true(xpct->sign == actl->sign);
assert_true(xpct->num == actl->num);
assert_true(xpct->denom == actl->denom);
xpct = &((rat){.sign = 0, .num = 1, .denom = 1});
a = &((rat){.sign = 0, .num = 10, .denom = 2});
b = &((rat){.sign = 0, .num = 1, .denom = 5});
rat r1 = rat_get_prod(*a, *b);
actl = &r1;
assert_true(xpct->sign == actl->sign);
assert_true(xpct->num == actl->num);
assert_true(xpct->denom == actl->denom);
xpct = &((rat){.sign = 0, .num = 10, .denom = 3});
a = &((rat){.sign = 0, .num = 10, .denom = 1});
b = &((rat){.sign = 0, .num = 1, .denom = 3});
rat r2 = rat_get_prod(*a, *b);
actl = &r2;
assert_true(xpct->sign == actl->sign);
assert_true(xpct->num == actl->num);
assert_true(xpct->denom == actl->denom);
xpct = &((rat){.sign = 0, .num = 1, .denom = 3});
a = &((rat){.sign = 0, .num = 2, .denom = 4});
b = &((rat){.sign = 0, .num = 2, .denom = 3});
rat r3 = rat_get_prod(*a, *b);
actl = &r3;
assert_true(xpct->sign == actl->sign);
assert_true(xpct->num == actl->num);
assert_true(xpct->denom == actl->denom);
xpct = &((rat){.sign = 1, .num = 3, .denom = 7});
a = &((rat){.sign = 1, .num = 5, .denom = 7});
b = &((rat){.sign = 0, .num = 3, .denom = 5});
rat r4 = rat_get_prod(*a, *b);
actl = &r4;
assert_true(xpct->sign == actl->sign);
assert_true(xpct->num == actl->num);
assert_true(xpct->denom == actl->denom);
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_rat_get_prod),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#include "acronym.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char *abbreviate(const char *phrase) {
if (!phrase || !strlen(phrase)) {
return NULL;
}
const char *input = phrase;
/* "result" will contain the result */
char *result = malloc(strlen(phrase));
/* "r" will be used to iterate through the "result". */
char *r = result;
/* "cap" controls the capitalisation. */
bool cap = true;
while (*input) {
if (!isalnum(*input) && *input != '\'') {
cap = true;
} else if (cap) {
*r++ = toupper(*input);
cap = false;
}
input++;
}
/* here, "r" is the tail of "result". */
*r = '\0';
return result;
}
<file_sep>#ifndef BEER_SONG_H
#define BEER_SONG_H
void verse(char *buffer, int n);
void sing(char *buffer, int start, int stop);
#endif
<file_sep>#include <stdio.h>
#define BUFSIZE 9
void init_buf(char *buf, size_t size);
void print_buf(char *buf);
int main() {
char buf[BUFSIZE];
init_buf(buf, BUFSIZE);
print_buf(buf);
// AAAAAAAAAAAA == 12 characters, > BUFSIZE
init_buf(buf, BUFSIZE);
snprintf(buf, BUFSIZE, "AAAAAAAAAAAA");
print_buf(buf);
// BBBBBB == 6 charaters, < BUFSIZE
init_buf(buf, BUFSIZE);
snprintf(buf, BUFSIZE, "BBBBBB");
print_buf(buf);
// 1111110 == 7 charaters, > 5
init_buf(buf, BUFSIZE);
snprintf(buf, 5, "%d", 111111 * 10);
print_buf(buf);
return 0;
}
void init_buf(char *buf, size_t size) {
size_t i;
for (i = 0; i < size; i++) {
buf[i] = i + '0'; // int to char conversion
}
}
void print_buf(char *buf) {
int i;
char c;
for (i = 0; i < BUFSIZE; i++) {
c = buf[i];
if (c == '\0') {
printf("\\0");
} else {
printf("%c", buf[i]);
}
}
printf("\n");
}
<file_sep>#include <libdill.h>
#include <stdio.h>
#include <stdlib.h>
/*
* http://libdill.org/index.html
*
* gcc -Wall -O3 `pkg-config --cflags --libs libdill` -o pebbles libdill_hello_world.c
* -ldill
*/
coroutine void worker(const char *text) {
while (1) {
printf("%s\n", text);
msleep(now() + random() % 500);
}
}
int main() {
go(worker("Hello!"));
go(worker("World!"));
msleep(now() + 5000);
return 0;
}
<file_sep>/*
* https://github.com/rjmh/q/blob/master/q.c
*/
#include <stdlib.h>
typedef struct queue
{ int inp;
int outp;
int size;
int *buf;
} Queue;
Queue *new(int n)
{ int *buff = malloc(n*sizeof(int));
Queue q = {0,0,n,buff};
Queue *qptr = malloc(sizeof(Queue));
*qptr = q;
return qptr;
}
int put(Queue *q, int n)
{ q -> buf[q -> inp] = n;
q -> inp = (q -> inp + 1) % q -> size;
return n;
}
int get(Queue *q)
{ int ans = q -> buf[q -> outp];
q -> outp = (q -> outp + 1) % q -> size;
return ans;
}
int size(Queue *q)
{ return (q->inp - q->outp) % (q -> size);
}
<file_sep>#include "nearly.h"
#include <complex.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <tgmath.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
// clang-format off
#define ffabs(X) \
_Generic((X), \
float: fabsf, \
long double: fabsl, \
complex double: cabs, \
complex long double: cabsl, \
complex float: cabsf, \
default: fabs)(X)
// clang-format on
/*
* Macro rules
* and C preprocessor: https://en.wikipedia.org/wiki/C_preprocessor
*
* Rule 3.17.0.1
* Whenever possible, prefer an inline function to a functional macro.
*
* Rule 3.17.0.2
* A functional macro shall provide a simple interface to a complex task.
*
* #define MINSIZE(X, Y) (sizeof(X)<sizeof(Y)?sizeof(X):sizeof(Y))
* #define BYTECOPY(T, S) memcpy(&(T), &(S), MINSIZE(T, S))
*
* When the compiler encounters the name of a functional macro, followed
* by a closing pair of (), such as in BYTECOPY(A, B), it considers this
* as a macro call and replaces it textually according to the following
* rules:
*
* - (1) The definition of the macro is temporarily disabled to avoid
* infinite recursion.
* - (2) The text inside the (), the argument list, is scanned for
* parenthesis and commas.
* Each opening parenthesis ( must match a ).
* A comma that is not inside such additional () is used to
* separate the argument list into the arguments.
* For the case that we handle here, the number of arguments must
* match the number of parameters of the definition of the macro.
* - (3) Each argument is recursively expanded for macros that might
* appear in them. In our example, A could be yet-another macro
* and expand to some variable name such as redA.
* - (4) The resulting text fragments from the expansion of the arguments
* are assigned to the parameters.
* - (5) A copy of the replacement text is made and all occurrences of
* the parameters is replaced by their respective definitions.
* - (6) The resulting replacement text is subject to macro replacement,
* again.
* - (7) This final replacement text is inserted in the source instead
* of the macro call.
* - (8) The definition of the macro is re-enabled.
*
*/
int foo(int a);
int foo(int a) { return a; }
#define foo(A) (A == 0) ? 0 : foo(A);
double min(double a, double b);
long double minl(long double a, long double b);
float minf(float a, float b);
long int minli(long int a, long int b);
long long int minlli(long long int a, long long int b);
long long int *minllip(long long int *a, long long int *b);
inline double min(double a, double b) { return a < b ? a : b; }
inline long double minl(long double a, long double b) { return a < b ? a : b; }
inline float minf(float a, float b) { return a < b ? a : b; }
inline intmax_t minj(intmax_t a, intmax_t b) { return a < b ? a : b; }
inline long int minli(long int a, long int b) { return a < b ? a : b; }
inline long long int minlli(long long int a, long long int b) {
return a < b ? a : b;
}
inline long long int *minllip(long long int *a, long long int *b) {
return *a < *b ? a : b;
}
int minus_one(void *a, void *b);
inline int minus_one(void *a, void *b) {
(void)a;
(void)b;
return -1;
}
/*
* https://en.wikipedia.org/wiki/C_data_types
* https://en.wikipedia.org/wiki/C_syntax
* https://en.wikipedia.org/wiki/Printf_format_string
* https://en.wikibooks.org/wiki/C_Programming/wchar.h
*/
/*
* int
* signed
* signed int | Basic signed integer type. Capable of containing at least
* | the [−32,767, +32,767] range;[3][4] thus, it is at least
* | 16 bits in size. [%i or %d]
* |
* unsigned |
* unsigned int | Basic unsigned integer type. Contains at least
* | the [0, 65,535] range. [%u]
* |
* long |
* long int |
* signed long |
* signed long int | Long signed integer type. Capable of containing at least
* | the [−2,147,483,647, +2,147,483,647] range; thus, it is
* | at least 32 bits in size. [%li]
* |
* unsigned long |
* unsigned long int | Long unsigned integer type. Capable of containing at
* | least the [0, 4,294,967,295] range. [%lu]
* |
* long long |
* long long int |
* signed long long |
* signed long long int | Long long signed integer type. Capable of containing
* | at least the [−9,223,372,036,854,775,807,
* | +9,223,372,036,854,775,807] range; thus, it is at
* | least 64 bits in size. Specified since the C99 version
* | of the standard. [%lli]
* |
* unsigned long long |
* unsigned long long int | Long long unsigned integer type. Contains at least
* | the [0, +18,446,744,073,709,551,615] range;
* | Specified since the C99 version of the
* | standard. [%llu]
*/
/*
* @brief Type generic minimum for floating point values
*
* ... the _Generic expression must decide on a combination of the two types.
* This is done, by using the sum of the two arguments as controlling
* expression. As an effect, argument promotions and conversion are effected to
* the arguments of that sum, and so the _Generic expression chooses the
* function for the wider of the two types, or double if both arguments are
* integers.
*/
// clang-format off
#define min_generic(A, B) \
_Generic((A) + (B), \
float : minf, \
long double : minl, \
long int: minli, \
long long int: minlli, \
double : min)(A, B)
#define min_pp(A, B) \
_Generic((A), \
long long int*: _Generic((B), \
long long int*: minllip))(A, B)
#define min_p(A, B) \
_Generic((A), \
int*: _Generic((B), \
int*: minllip, \
default: min), \
long int*: _Generic((B), \
long int*: minllip, \
default: min), \
long long int*: _Generic((B), \
long long int*: minllip, \
default: min), \
default: _Generic((*A) + (*B), \
float : minf, \
long double : minl, \
long int: minli, \
long long int: minlli, \
double : min, \
default: min))(A, B)
// clang-format on
/*
* 17.5. Type generic programming
*
* Exercises
*
* - [Exs 11]: Find the two reasons why this occurence of fabs in the macro
* expansion is not itself expanded.
* (rule (1))
* - [Exs 12]: Extend the fabs macro to cover complex floating point types.
* - [Exs 13]: Extend the min macro to cover all wide integer types.
* - [Exs 14]: Extend min to cover pointer types, as well.
*
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_not_recursive(void **state) {
(void)state;
int r = foo(0);
assert_int_equal(0, r);
r = foo(1);
assert_int_equal(1, r);
assert_true(true);
}
#define printfc(c) \
printf("%f%c%fi\n", creal(c), (cimag(c) >= 0.0f) ? '+' : '\0', cimag(c))
/* specifies a format with 9 total characters: 2 digits before
* the dot, the dot itself, and six digits after the dot.
*/
static void test_generic_fabs(void **state) {
(void)state;
double prec = 0.0001;
double expected = 10.0;
double dx = -10.0;
double dresult = ffabs(dx);
printf("%+9.6f\n", dresult);
assert_true(nearly_equal(expected, dresult, prec));
float fx = -10.0;
float fresult = ffabs(fx);
printf("%+9.6f\n", dresult);
assert_true(nearly_equal(expected, fresult, prec));
long double ldx = -10.0;
long double ldresult = ffabs(ldx);
printf("%+9.6Lf\n", ldresult);
assert_true(nearly_equal(expected, dresult, prec));
complex double cdx = -10.0;
complex double cdresult = ffabs(cdx);
printfc(cdresult);
assert_true(nearly_equal(expected, cdresult, prec));
complex float cfx = -10.0;
complex float cfresult = ffabs(cfx);
printfc(cfresult);
assert_true(nearly_equal(expected, cfresult, prec));
}
static void test_generic_min(void **state) {
(void)state;
long long int a = 9223372036854775807;
long long int b = 9223372036854775806;
long long int m = min_generic(b, a);
assert_true(m == b);
}
static void test_generic_minp(void **state) {
(void)state;
long long int a = 9223372036854775807;
long long int b = 9223372036854775806;
long long int * ap = &a;
long long int * bp = &b;
printf("A: %lli, AP: %p, *AP: %lli\n", a, ap, *ap);
printf("B: %lli, BP: %p, *BP: %lli\n", b, bp, *bp);
long long int *m = minllip(bp, ap);
assert_true(m == bp);
printf("MP: %p, *M: %lli\n", m, *m);
m = min_pp(bp, ap);
printf("MP: %p, *M: %lli\n", m, *m);
m = min_p(bp, ap);
printf("MP: %p, *M: %lli\n", m, *m);
assert_true(m == bp);
}
int test(void) {
double complex z = 1 + 2 * I;
z = 1 / z;
printf("1/(1.0+2.0i) = %.1f%+.1fi\n", creal(z), cimag(z));
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1),
cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference),
cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product),
cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient),
cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate),
cimag(conjugate));
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_not_recursive),
cmocka_unit_test(test_generic_fabs),
cmocka_unit_test(test_generic_min),
cmocka_unit_test(test_generic_minp),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
/*
* _Generic: references
* https://en.cppreference.com/w/c/language/generic
* https://en.cppreference.com/w/c/language/generic
*
* https://stackoverflow.com/questions/24743520/incompatible-pointer-types-passing-in-generic-macro
* https://stackoverflow.com/questions/9804371/syntax-and-sample-usage-of-generic-in-c11#17290414
* http://www.robertgamble.net/2012/01/c11-generic-selections.html
*/
<file_sep>
#include <stdio.h>
#include <unistd.h>
int main() {
int a = 0;
if (fork() == 0) {
a = a + 5;
printf("%d, %p\n", a, &a);
} else {
a = a - 5;
printf("%d, %p\n", a, &a);
}
}
<file_sep>#include <stdio.h>
int main() {
int a;
for (a = 0; a < 10; a++) {
printf("%d (%d & 1) : (%s)\n", a, a, (a & 1) == 0 ? "even" : "odd");
printf("%d (%d & 1) : (%s)\n", a, a, (a & 1) ? "odd" : "even");
}
return 0;
}
<file_sep>#include "binary.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int is_binary_digit(char c) { return (c == '0' || c == '1'); }
int convert(char *s) {
int r = 0;
int i = 0;
int e = strlen(s) - 1;
char c;
while (e >= 0) {
c = s[e--];
if (!is_binary_digit(c)) {
return INVALID;
}
r += (c - '0') << (i++);
}
/* Paragraph 2.2.1 "In both the source and execution basic character sets,
* the value of each character after 0 in the above list of decimal digits
* shall be one greater than the value of the previous." */
/* while (s++) {
* r += (s[0] - '0') << i;
* }
*/
return r;
}
<file_sep>#include "leap.h"
/* is a leap year?
* on every year that is evenly divisible by 4
* except every year that is evenly divisible by 100
* unless the year is also evenly divisible by 400
*/
int is_leap_year(int year) {
/* clang-format off */
if (year%400 == 0) return 1;
if (year%100 == 0) return 0;
if (year%4 == 0) return 1;
/* clang-format on */
return 0;
}
<file_sep>#include "space_age.h"
/* 31557600 seconds */
#define EARTH_PERIOD 60 * 60 * 24 * 365.25
/* planet periods
* - Earth: orbital period 365.25 Earth days, or 31557600 seconds
* - Mercury: orbital period 0.2408467 Earth years
* - Venus: orbital period 0.61519726 Earth years
* - Mars: orbital period 1.8808158 Earth years
* - Jupiter: orbital period 11.862615 Earth years
* - Saturn: orbital period 29.447498 Earth years
* - Uranus: orbital period 84.016846 Earth years
* - Neptune: orbital period 164.79132 Earth years
*/
/* clang--format off */
static const float period[8] = {
[EARTH] = EARTH_PERIOD * 1,
[MERCURY] = EARTH_PERIOD * 0.2408467,
[VENUS] = EARTH_PERIOD * 0.61519726,
[MARS] = EARTH_PERIOD * 1.8808158,
[JUPITER] = EARTH_PERIOD * 11.862615,
[SATURN] = EARTH_PERIOD * 29.447498,
[URANUS] = EARTH_PERIOD * 84.016846,
[NEPTUNE] = EARTH_PERIOD * 164.79132,
};
/* clang-format on */
float convert_planet_age(planet_t PLANET, unsigned long seconds) {
return seconds / period[PLANET];
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
* Exercises
*
* - [Exs 00]:
*
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
/*
* This program has three declarations for variables named i, but only two
* definitions: the declaration and definition in Line 6 shadows the one in
* Line 3. In turn declaration Line 8 shadows Line 6, but it refers to the same
* object as the object defined in Line 3.
*/
unsigned i = 1; /* [3] */
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
unsigned i = 2; /* a new object */ /* [6] */
if (i) {
extern unsigned i; /* an existing object */ /* [8] */
printf("%u\n", i);
} else {
printf("%u\n", i);
}
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
return EXIT_SUCCESS;
}
<file_sep>#include <pthread.h>
pthread_mutex_t count_mutex;
long long count;
void increment_count() {
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
long long get_count() {
long long c;
pthread_mutex_lock(&count_mutex);
c = count;
pthread_mutex_unlock(&count_mutex);
return (c);
}
<file_sep>/*
This may look like nonsense , but really is
-*- mode : C -*-
*/
#include <stdio.h>
#include <stdlib.h>
/*
Exs 3.1
*/
void exs_1() {
double A[5] = {
[0] = 9.0, [1] = 2.9, [4] = 3.E+25, [3] = .00007,
};
for (size_t i = 0; i < 5; ++i) {
if (i) {
printf("element %zu is %g, \tits square is %g\n", i, A[i], A[i] * A[i]);
}
}
}
void something(size_t i) { printf("%zu\n", i); }
void something_else(size_t i) { printf("%zu\n", i); }
// https://en.wikipedia.org/wiki/C_data_types#stddef.h
size_t upper_bound() { return 10; }
/*
Exs 3.2
*/
void exs_2() {
for (size_t i = 10; i; --i) {
something(i);
}
printf("---\n");
for (size_t i = 0, stop = upper_bound(); i < stop; ++i) {
something_else(i);
}
printf("---\n");
size_t x = 0;
printf("%zu\n", x);
printf("%zu\n", --x);
printf("---\n");
for (size_t i = 9; i <= 9; --i) {
something_else(i);
}
}
int main(void) {
exs_1();
exs_2();
return EXIT_SUCCESS;
}
<file_sep>#include "all_your_base.h"
#include <math.h>
#include <stdio.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/* rem is the int reminder of the division. */
int8_t rem(int16_t a, int16_t b) { return a - (a / b) * b; }
size_t rebase(int8_t digits[], int16_t input_base, int16_t output_base,
size_t input_length) {
size_t steps = 0;
size_t decimal = 0;
size_t i = 0;
int8_t d = 0;
int16_t p = 0;
DEBUG_PRINT(("--- from base %d to base %d ---\n", input_base, output_base));
for (i = 0; i < input_length; ++i) {
DEBUG_PRINT(("%d", digits[i]));
}
if (digits[0] == 0) {
return 0;
}
if (input_base <= 0) {
return 0;
}
for (i = 0; i < input_length; ++i) {
d = digits[input_length - 1 - i];
if (d < 0 || d >= input_base || output_base <= 1) {
return 0;
}
p = pow(input_base, i);
decimal = decimal + (d * p);
DEBUG_PRINT(("\nstep: %lu, digit: %d, %d^%lu: %d, decimal: %lu\n", i, d, input_base,
i, p, decimal));
}
int16_t reminder = 0;
DEBUG_PRINT(("decimal value: %lu\n", decimal));
while (decimal) {
reminder = rem(decimal, output_base);
decimal /= output_base;
DEBUG_PRINT(("decimal: %lu, reminder: %d, steps: %lu\n", decimal, reminder,
steps));
digits[steps++] = reminder;
}
int8_t *left = &digits[0];
int8_t *right = &digits[steps - 1];
while (left < right) {
*left ^= *right;
*right ^= *left;
*left ^= *right;
left++;
right--;
}
return steps;
}
<file_sep>/* header file */
#import <stdio.h>
#import <stdlib.h>
#define string_literal(S) string_literal("" S "")
inline char const *(string_literal)(char const str[static 1]) { return str; }
// one translation unit
extern char const *(*func)(char const str[static 1]);
// another translation unit
char const *(string_literal)(char const str[static 1]);
char const *(*func)(char const str[static 1]) = string_literal;
/*
* That is, both the inline definition and the instantiating declaration of the
* function are protected by surrounding (), and don’t expand the functional
* macro. The last line shows another common usage of this feature. Here
* string_literal is not followed by () and so both rules are applied. First
* Rule 3.17.1.2 inhibits the expansion of the macro and then Rule 2.11.8.1
* evaluates the use of the function to a pointer to that function.
*/
/* Rule 3.17.1.2 If the name of functional macro is not followed by () it is not
* expanded.
*
* Rule 2.11.8.1 A function f without following opening ( decays to a pointer to
* its start.
*/
int main(void) {
const char *s = string_literal("SSS");
/* const char *t = string_literal(s); */
printf("%s\n", s);
exit(EXIT_SUCCESS);
}
/*
* An important such case are string literals.
* string literals are read-only but are not even const qualified. Also an
* interface with [static 1] as for the function string_literal above is not
* enforced by the language, because prototypes without [static 1] are
* equivalent. In C there is no way to prescribe for a parameter str of a
* function interface, that it should fulfill the following constraints:
* - is a character pointer,
* - must be non-null,
* - must be unmutable,
* - must be 0-terminated,
*
* All these properties could be particular useful to check at compile time,
* but we have simply no way to specify them in a function interface.
* The macro string_literal fills that gap in the language specification. The
* weird empty string literals in its expansion "" X "" ensure that
* string_literal can only be called with a string literal.
*
* string_literal("hello"); // "" "hello" ""
* char word[25] = "hello";
* ...
* // replacing rules cannot work in this case:
* string_literal(word); // "" word "" // error
*/
<file_sep>#include "hamming.h"
#include <string.h>
int compute(char *a, char *b) {
if (!a)
return -1;
if (!b)
return -1;
if (strcmp(a, b) == 0)
return 0;
if (strlen(a) != strlen(b))
return -1;
int diff = 0;
while (*a && *b) {
diff += (*a++ != *b++);
}
return diff;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/* Exercises
- [Exs 06]: Consider a macro sum(a, b) that is implemented as
a+b. What is the result of sum(5, 2)*7?
- [Exs 07]: Let max(a, b) be implemented as ((a) < (b) ? (b) : (a)).
What happens for max(i++, 5)?
*/
#ifndef sum
#define sum(a, b) a + b
#endif
#ifndef max
#define max(a, b) ((a) < (b) ? (b) : (a))
#endif
_Static_assert((sum(5, 2) * 7) == 19, "this is not what you were expecting!");
/* _Static_assert((max(i++, 5)) == 5, "this is not what you were expecting!"); */
/* https://stackoverflow.com/questions/41442317/macro-expression-is-not-assignable#41442360 */
/* https://stackoverflow.com/questions/923822/whats-the-use-of-do-while0-when-we-define-a-macro */
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#include "pangram.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
/* char_to_lower converts a character to its lowercase version. */
int char_to_lower(char c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
/* If the i object is not used outside the translation unit where it is defined,
* you should declare it with the static specifier.
*
* This enables the compiler to (potentially) perform further optimizations and
* informs the reader that the object is not used outside its translation unit.
* static inside a function means the variable will exist before and after the
* function has ended.
*
* static outside of a function means that the scope of the symbol marked static
* is limited to that .c file and cannot be seen outside of it.
*
* a:97 ... z:122 */
static const int LEN = 26;
bool is_pangram(const char *sentence) {
if (!sentence)
return false;
if (!strlen(sentence))
return false;
int i = 0;
char c = '\0';
int idx = 0;
int chars[LEN];
int score = LEN;
memset(chars, 0, LEN * sizeof(int));
while ((c = char_to_lower(sentence[i++]))) {
idx = c % 'a';
if (!isalpha(c) || chars[idx]) {
continue;
}
chars[idx] = 1;
if (!--score)
return true;
}
return false;
}
<file_sep>#ifndef NUCLEOTIDE_COUNT_H
#define NUCLEOTIDE_COUNT_H
char * count(const char * dna_strand);
#endif
<file_sep>#include <stdio.h>
int lgn(int val, int n) {
int log = 0;
if (!val)
return 1;
for (; val; (val /= n), log++)
;
return log;
}
int digits(int i) {
return lgn(i, 10);
}
int main() {
int test[11] = {0, 1, 10, 20, 50, 100, 200, 300, 1000, 1200, 1500};
for (int i = 0; i < 11; ++i) {
printf("- %d: %d digits\n", test[i], digits(test[i]));
printf("- %d: %d/%d ( 100)\n", test[i], test[i] / 100, test[i] % 100);
printf("- %d: %d/%d (1000)\n", test[i], test[i] / 1000, test[i] % 1000);
printf("\n");
}
}
<file_sep>#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
/*
Exs 5.12
Show that the expressions -1U, -1UL and -1ULL have the maximum values and type
of the three usable unsigned types, respectively.
*/
/*
http://www.cplusplus.com/reference/climits/
Macro constants
name expresses value*
CHAR_BIT | Number of bits in a char object (byte) | 8 or greater*
SCHAR_MIN | minVal for an object of type signed char | -127 (-27+1) or less*
SCHAR_MAX | maxVal for an object of type signed char | 127 (27-1) or greater*
UCHAR_MAX | maxVal for an object of type unsigned char | 255 (28-1) or greater*
CHAR_MIN | minVal for an object of type char | either SCHAR_MIN or 0
CHAR_MAX | maxVal for an object of type char | either SCHAR_MAX or UCHAR_MAX
MB_LEN_MAX | max number of bytes in a multibyte character, for any locale | 1 or
greater*
SHRT_MIN | minVal for an object of type short int | -32767 (-215+1) or less*
SHRT_MAX | maxVal for an object of type short int | 32767 (215-1) or greater*
USHRT_MAX | maxVal for an object of type unsigned short int | 65535 (216-1) or
greater*
INT_MIN | minVal for an object of type int | -32767 (-215+1) or less*
INT_MAX | maxVal for an object of type int | 32767 (215-1) or greater*
UINT_MAX | maxVal for an object of type unsigned int | 65535 (216-1) or greater*
LONG_MIN | minVal for an object of type long int | -2147483647 (-231+1) or less*
LONG_MAX | maxVal for an object of type long int | 2147483647 (231-1) or
greater*
ULONG_MAX | maxVal for an object of type unsigned long int | 4294967295 (232-1)
or greater*
LLONG_MIN | minVal for an object of type long long int | -9223372036854775807
(-263+1) or less*
LLONG_MAX | maxVal for an object of type long long int | 9223372036854775807
(263-1) or greater*
ULLONG_MAX | maxVal for an object of type unsigned long long int |
18446744073709551615 (264-1) or greater*
*/
unsigned int max_unsigned_int = UINT_MAX;
unsigned long max_unsigned_long = ULONG_MAX;
unsigned long long max_unsigned_long_long = ULLONG_MAX;
static void test_unsigned(void **state) {
(void)state; /* unused */
assert_int_equal(1U, 1);
assert_int_equal(1U - 1, 0);
assert_int_equal(1U - 2, max_unsigned_int);
}
static void test_unsigned_long(void **state) {
(void)state; /* unused */
assert_int_equal(1UL, 1);
assert_int_equal(1UL - 1, 0);
assert_int_equal(1UL - 2, max_unsigned_long);
}
static void test_unsigned_long_long(void **state) {
(void)state; /* unused */
assert_int_equal(1ULL, 1);
assert_int_equal(1ULL - 1, 0);
assert_int_equal(1ULL - 2, max_unsigned_long_long);
}
int test(void) {
// clang-format off
// http://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_unsigned),
cmocka_unit_test(test_unsigned_long),
cmocka_unit_test(test_unsigned_long_long),
};
// clang-format on
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(int argc, char *argv[argc + 1]) {
printf("running as %s\n", argv[0]);
printf("UINT_MAX \t= %u\n", UINT_MAX);
printf("ULONG_MAX \t= %lu\n", ULONG_MAX);
printf("ULLONG_MAX \t= %llu\n", ULLONG_MAX);
test();
return EXIT_SUCCESS;
}
<file_sep>#ifndef GRAINS_H
#define GRAINS_H
#define BOARD 64
#include <stdint.h>
uint64_t square(int board_size);
uint64_t total();
#endif
<file_sep>#include "roman_numerals.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void concat(char *res, char s[1]) { strncat(res, s, strlen(s)); }
/* roman numerals (wikipedia.org)
* https://en.wikipedia.org/wiki/Roman_numerals
*
* basic symbols
* Symbol: I V X L C D M
* Value: 1 5 10 50 100 500 1000
*
* extended symbols
* Symbol: I IV V IX X XL L XC C CD D CM M
* Value: 1 4 5 9 10 40 50 90 100 400 500 900 1000
*
* Arabic: 3888
*
* Roman: MMMDCCCLXXXVIII
*/
typedef struct symbols {
int arabic;
char roman[3];
} symbols_t;
const symbols_t lookup[] = {
[0] = (symbols_t){.arabic = 1000, .roman = "M"},
[1] = (symbols_t){.arabic = 900, .roman = "CM"},
[2] = (symbols_t){.arabic = 500, .roman = "D"},
[3] = (symbols_t){.arabic = 400, .roman = "CD"},
[4] = (symbols_t){.arabic = 100, .roman = "C"},
[5] = (symbols_t){.arabic = 90, .roman = "XC"},
[6] = (symbols_t){.arabic = 50, .roman = "L"},
[7] = (symbols_t){.arabic = 40, .roman = "XL"},
[8] = (symbols_t){.arabic = 10, .roman = "X"},
[9] = (symbols_t){.arabic = 9, .roman = "IX"},
[10] = (symbols_t){.arabic = 5, .roman = "V"},
[11] = (symbols_t){.arabic = 4, .roman = "IV"},
[12] = (symbols_t){.arabic = 1, .roman = "I"},
};
char *to_roman_numeral(int num) {
char *res = malloc(sizeof(char) * strlen("MMMDCCCLXXXVIII"));
if (!res) {
fprintf(stderr, "malloc failed!\n");
return res;
}
res[0] = '\0';
/* using macros and chars:
* char *out;
* #define RPUT(c) if (out) out[len] = c; len++
* RPUT('C'); RPUT('M');
* RPUT('\0');
* #undef RPUT
*/
int i = 0;
while (num) {
while (num / lookup[i].arabic) {
strncat(res, lookup[i].roman, strlen(lookup[i].roman));
num -= lookup[i].arabic;
}
i++;
}
return res;
}
<file_sep>/**
* section: Parsing
* synopsis: Parse an XML file to a tree and free it
* purpose: Demonstrate the use of xmlReadFile() to read an XML file
* into a tree and and xmlFreeDoc() to free the resulting tree
* usage: parse1 test1.xml
* test: parse1 test1.xml
* author: <NAME>
* copy: see Copyright for the status of this software.
*
* http://xmlsoft.org/examples/index.html
* http://xmlsoft.org/examples/parse1.c
* http://xmlsoft.org/examples/parse2.c
* http://xmlsoft.org/examples/parse3.c
* http://xmlsoft.org/examples/parse4.c
* gcc -Wall -o ~/Downloads/a.out ~/workspaces/pebbles/sample_libxml.c
* $(xml2-config --cflags --libs)
*
* For compilers to find libxml2 you may need to set:
* export LDFLAGS="-L/usr/local/opt/libxml2/lib"
* export CPPFLAGS="-I/usr/local/opt/libxml2/include"
*
* For pkg-config to find libxml2 you may need to set:
* export PKG_CONFIG_PATH="/usr/local/opt/libxml2/lib/pkgconfig"
*
* PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl tidy)
* -I/usr/local/Cellar/tidy-html5/5.6.0/include
* -L/usr/local/Cellar/tidy-html5/5.6.0/lib -lcurl -ltidy
*
* LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
* $ /usr/local/opt/libxml2/bin/xml2-config --cflags
* -I/usr/local/Cellar/libxml2/2.9.7/include/libxml2
* $ /usr/local/opt/libxml2/bin/xml2-config --libs
* -L/usr/local/Cellar/libxml2/2.9.7/lib -lxml2 -lz -lpthread -liconv -lm
*
*/
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
#include <string.h>
static const char *document = "<doc/>";
/**
* example1Func:
* @filename: a filename or an URL
*
* Parse the resource and free the resulting tree
*/
static void example1Func(const char *filename) {
xmlParserCtxtPtr ctxt; /* the parser context */
xmlDocPtr doc; /* the resulting document tree */
/* create a parser context */
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
fprintf(stderr, "Failed to allocate parser context\n");
return;
}
doc = xmlReadFile(filename, NULL, 0);
if (doc == NULL) {
fprintf(stderr, "Failed to parse %s\n", filename);
return;
}
xmlFreeDoc(doc);
}
/**
* exampleFunc:
* @filename: a filename or an URL
*
* Parse and validate the resource and free the resulting tree
*/
static void example2Func(const char *filename) {
xmlParserCtxtPtr ctxt; /* the parser context */
xmlDocPtr doc; /* the resulting document tree */
/* create a parser context */
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
fprintf(stderr, "Failed to allocate parser context\n");
return;
}
/* parse the file, activating the DTD validation option */
doc = xmlCtxtReadFile(ctxt, filename, NULL, XML_PARSE_DTDVALID);
/* check if parsing suceeded */
if (doc == NULL) {
fprintf(stderr, "Failed to parse %s\n", filename);
} else {
/* check if validation suceeded */
if (ctxt->valid == 0)
fprintf(stderr, "Failed to validate %s\n", filename);
/* free up the resulting document */
xmlFreeDoc(doc);
}
/* free up the parser context */
xmlFreeParserCtxt(ctxt);
}
/**
* example3Func:
* @content: the content of the document
* @length: the length in bytes
*
* Parse the in memory document and free the resulting tree
*/
static void example3Func(const char *content, int length) {
xmlDocPtr doc; /* the resulting document tree */
/*
* The document being in memory, it have no base per RFC 2396,
* and the "noname.xml" argument will serve as its base.
*/
doc = xmlReadMemory(content, length, "noname.xml", NULL, 0);
if (doc == NULL) {
fprintf(stderr, "Failed to parse document\n");
return;
}
xmlFreeDoc(doc);
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("filename missing\n");
return (1);
}
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
example1Func(argv[1]);
example2Func(argv[1]);
example3Func(document, strlen(document));
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
return (0);
}
<file_sep>#include <stdio.h>
#define SIZE 6
int main() {
int bubble[] = {95, 60, 6, 87, 50, 24};
int inner, outer, temp, x;
/* Display original array */
puts("Original Array:");
for (x = 0; x < SIZE; x++)
printf("%dt", bubble[x]);
putchar('n');
/* Bubble sort */
for (outer = 0; outer < SIZE - 1; outer++) {
for (inner = outer + 1; inner < SIZE; inner++) {
if (bubble[outer] > bubble[inner]) {
temp = bubble[outer];
bubble[outer] = bubble[inner];
bubble[inner] = temp;
}
}
}
/* Display sorted array */
puts("Sorted Array:");
for (x = 0; x < SIZE; x++)
printf("%dt", bubble[x]);
putchar('n');
return (0);
}
<file_sep>#ifndef PASCALS_TRIANGLE_H
#define PASCALS_TRIANGLE_H
#include <stdlib.h>
size_t **create_triangle(size_t);
void free_triangle(size_t **r, size_t n);
#endif
<file_sep>#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/* for fork and kill */
#include <signal.h>
#include <sys/types.h>
/* for having execclp */
#include <unistd.h>
/*
* SDL version 2.0.8 (stable)
* http://www.libsdl.org/index.php
* https://www.libsdl.org/download-2.0.php
*p http://wiki.libsdl.org/FrontPage
* http://wiki.libsdl.org/Tutorials
*
* API:
* http://wiki.libsdl.org/CategoryAPI
* http://wiki.libsdl.org/APIByCategory
* http://hg.libsdl.org/SDL/file/default/include/SDL_audio.h
* https://www.libsdl.org/projects/SDL_mixer/
*
* $ pkg-config --libs sdl2
* -L/usr/local/lib -lSDL2
*
* $ sdl2-config --cflags --libs
* -I/usr/local/include/SDL2 -D_THREAD_SAFE
* -L/usr/local/lib -lSDL2
*
* gcc -O3 -o loomp3 $(sdl2-config --cflags --libs) loomp3.c
* gcc -Wall -std=c11 -O3 -lSDL2 -lSDL2_mixer -o loomp3 loomp3.c
*
* TODO:
* - [ ] implement pause with spacebar
* 4.5.10 Mix_PauseMusic
* void Mix_PauseMusic()
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_62.html#SEC62
*/
#include "SDL2/SDL.h"
#include "SDL2/SDL_mixer.h"
#include <SDL2/SDL_ttf.h>
void loop_with_fork(char *file_name) {
pid_t x;
char kil[20] = "kill -s 9 ";
x = fork();
if (x < 0) {
puts("fork failure");
exit(-1);
} else if (x == 0) {
/* here we are in the forked child */
execlp("afplay", "afplay", file_name, (char *)NULL);
} else {
/* here in the parent process */
printf("from parent: afplay is pid %d\nENTER to quit\n", x);
sprintf(kil, "%s%d", kil, x);
getchar();
system(kil);
printf("All ");
}
printf("done.\n");
}
void debug_sdl_compiled_version() {
SDL_version compile_version;
const SDL_version *link_version = Mix_Linked_Version();
SDL_MIXER_VERSION(&compile_version);
printf("compiled with SDL_mixer version: %d.%d.%d\n", compile_version.major,
compile_version.minor, compile_version.patch);
printf("running with SDL_mixer version: %d.%d.%d\n", link_version->major,
link_version->minor, link_version->patch);
}
int debug_sdl_decoders() {
// print the number of music decoders available
printf("There are %d music decoders available\n", Mix_GetNumMusicDecoders());
// print music decoders available
int i, max = Mix_GetNumMusicDecoders();
for (i = 0; i < max; ++i)
printf("Music decoder %d is for %s\n", i, Mix_GetMusicDecoder(i));
return 0;
}
/*
* https://www.libsdl.org/projects/SDL_mixer/
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer.html#SEC9
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_52.html#SEC52
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_57.html#SEC57
* Mix_FreeMusic
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_56.html
* SDL_Event
* https://wiki.libsdl.org/SDL_Event
* SDL_CreateWindow
* https://wiki.libsdl.org/SDL_CreateWindow
* SDL_PollEvent
* https://wiki.libsdl.org/SDL_PollEvent
*
* Call Mix_OpenAudio _before_ Mix_Init:
* https://discourse.libsdl.org/t/bug-sdl2-mixer-init-error-format-support-not-available/23705/2
*/
int play_with_sdl(char *file_name) {
int error = 0;
debug_sdl_compiled_version();
/*
*create a window
*/
SDL_Window *window;
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;
const char *WINDOW_TITLE = "SDL Window - playing music";
window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH,
WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
{
/* open audio device
* open 44.1KHz, signed 16bit, system byte order,
* stereo audio, using 1024 byte chunks
*/
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
SDL_Log("Mix_OpenAudio: %s\n", Mix_GetError());
return 2;
}
error = debug_sdl_decoders();
if (error) {
SDL_Log("Could not debug decoders (result: %d).\n", error);
return 1;
}
}
{
/* start SDL with audio and video support
* if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) == -1)
*/
if (SDL_Init(SDL_INIT_AUDIO) == -1) {
SDL_Log("SDL_Init: %s", SDL_GetError());
return 1;
}
}
{
/* sdl2_mixer init
* load support for the OGG and MOD , MP3 sample/music formats
*/
int flags = MIX_INIT_OGG | MIX_INIT_MOD | MIX_INIT_MP3;
if (!Mix_Init(flags)) {
SDL_Log("Mix_Init: %s", Mix_GetError());
return 1;
}
}
/* Load music file
* Load the MP3 file to play as music
*/
Mix_Music *music;
music = Mix_LoadMUS(file_name);
if (!music) {
SDL_Log("Mix_LoadMUS(\"%s\"): %s", file_name, Mix_GetError());
return 1;
}
SDL_Renderer *renderer =
SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer) {
const char *error = SDL_GetError();
SDL_Log("Renderer: %s", error);
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", error);
/* handle error */
}
if (TTF_Init() == -1) {
/* https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_12.html */
const char *error = TTF_GetError();
SDL_Log("TTF_Font: %s", error);
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", error);
/* handle error */
}
TTF_Font *font = TTF_OpenFont("/Library/Fonts/Arial.ttf", 25);
if (!font) {
const char *error = TTF_GetError();
SDL_Log("TTF_Font: %s", error);
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", error);
/* handle error */
}
/* white color */
SDL_Color color = {255, 255, 255, 255};
SDL_Surface *surface = TTF_RenderText_Solid(font, "foo!", color);
if (!surface) {
const char *error = TTF_GetError();
SDL_Log("Surface: %s", error);
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", error);
/* handle error */
}
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
if (!texture) {
const char *error = TTF_GetError();
SDL_Log("Texture: %s", error);
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", error);
/* handle error */
}
int texW = 10;
int texH = 10;
SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);
SDL_Rect dstrect = {0, 0, texW, texH};
SDL_RenderCopy(renderer, texture, NULL, &dstrect);
SDL_RenderPresent(renderer);
SDL_Log("Load Music success. Press <SPACE> to start/stop music playing.");
unsigned char quit = 0;
while (!quit) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
/*
* SDL_PollEvent
* If event is not NULL, the next event is removed from the queue and
* stored in the SDL_Event structure pointed to by event.
*
* If event is NULL, it simply returns 1 if there is an event in the
* queue, but will not remove it.
*
* As this function implicitly calls SDL_PumpEvents(), you can only call
* this function in the thread that set the video mode.
*
* SDL_PollEvent() is the favored way of receiving system events since it
* can be done from the main loop and does not suspend the main loop while
* waiting on an event to be posted.
*
* https://wiki.libsdl.org/SDL_PollEvent
*/
SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "event received %d", event.type);
if (event.type == SDL_QUIT) {
quit = 1;
} else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_SPACE:
if (!Mix_PlayingMusic()) {
if (Mix_PlayMusic(music, -1) == -1) {
SDL_Log("Mix_PlayMusic: %s\n", Mix_GetError());
}
} else {
SDL_Log("toggling Mix_ResumeMusic and Mix_PauseMusic");
Mix_PausedMusic() ? Mix_ResumeMusic() : Mix_PauseMusic();
}
break;
case SDLK_q:
SDL_Log("quitting...");
quit = 1;
break;
default:
break;
}
}
}
}
/* closing the corresponding Mix_LoadMUS() */
SDL_Log("FreeMusic");
Mix_FreeMusic(music);
music = NULL;
/* closing the corresponding Mix_OpenAudio() */
Mix_CloseAudio();
SDL_DestroyTexture(texture);
SDL_FreeSurface(surface);
TTF_CloseFont(font);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
TTF_Quit();
/* destroying window */
SDL_DestroyWindow(window);
SDL_Log("SDLQuit\n");
SDL_Quit();
return 0;
}
void print_usage(char *program_name) {
printf("%s\n%s\n\nusage:\n\n%s <file.mp3>\n\n", program_name, "0.0.1",
program_name);
}
void kill_gracefully(pid_t pid) {
kill(pid, SIGTERM);
bool died = false;
for (int loop = 0; !died && loop < 5; ++loop) {
printf("... quitting ...\n");
int status;
sleep(1);
if (waitpid(pid, &status, WNOHANG) == pid)
died = true;
}
if (!died) {
printf("forcing quit of %d\n", pid);
kill(pid, SIGKILL);
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
print_usage(argv[0]);
return 0;
}
assert(argc > 1);
return play_with_sdl(argv[1]);
}
/*
* sample fork logic
*
* pid_t parent = getpid();
* pid_t pid;
* pid = fork();
* if (pid < 0) {
* printf("cannot fork!\n");
* } else if (pid > 0) {
* printf("parent pid: %d, SDL2 pid: %d\n", parent, pid);
* char ch = 0;
* while (1) {
* scanf("%c", &ch);
* printf("pressed %c\n", ch);
* if (ch == 'q') {
* break;
* }
* }
* kill_gracefully(pid);
* } else {
* printf("children process\n");
* play_with_sdl(argv[1]);
* }
*/
/*
* sample event loop
*
* while (running) {
* SDL_Log("entering the PollEvent loop");
* while (SDL_PollEvent(&event)) {
* SDL_Log("switching on event %d", event.type);
* switch (event.type) {
* case SDL_KEYDOWN:
* printf("Key pressed:\n");
* printf(" SDL sim: %i\n", event.key.keysym.sym);
* printf(" modifiers: %i\n", event.key.keysym.mod);
* break;
* switch (event.key.keysym.sym) {
* case SDLK_ESCAPE:
* SDL_Log("ESC pressed.\n");
* running = false;
* break;
* default:
* SDL_Log("ANY key pressed.\n");
* break;
* }
* break;
* case SDL_QUIT:
* running = false;
* break;
* }
* SDL_Delay(1000);
* }
* SDL_Log("no events");
* SDL_Delay(1000);
* }
*/
/* some APIs
* Mix_VolumeMusic(MIX_MAX_VOLUME / 2);
* Mix_VolumeMusic(-1);
*
* pause music playback
* Mix_PauseMusic();
*
* fade out music to finish 3 seconds from now
* while (!Mix_FadeOutMusic(3000) && Mix_PlayingMusic()) {
* // wait for any fades to complete
* SDL_Delay(100);
* }
*
* // check if music is playing
* printf("music is%s playing.\n", Mix_PlayingMusic() ? "" : " not");
* // check the music pause status
* printf("music is%s paused\n", Mix_PausedMusic() ? "" : " not");
* // halt music playback
* Mix_HaltMusic();
*/
<file_sep>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/*
* Write a function to run a simulation like this, with a variable number of
* random points to select.
* Also, show the results of a few different sample sizes.
* For software where the number π is not built-in, we give π
* as a number of digits:
* 3.141592653589793238462643383280
*/
double pi(double tolerance) {
double x, y, val, error;
unsigned long sampled = 0, hit = 0, i;
do {
/* don't check error every turn, make loop tight */
for (i = 1000000; i; i--, sampled++) {
x = rand() / (RAND_MAX + 1.0);
y = rand() / (RAND_MAX + 1.0);
if (x * x + y * y < 1)
hit++;
}
val = (double)hit / sampled;
error = sqrt(val * (1 - val) / sampled) * 4;
val *= 4;
/* some feedback, or user gets bored */
fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r", val, error,
sampled / 1000000);
} while (!hit || error > tolerance);
/* !hit is for completeness's sake; if no hit after 1M samples,
your rand() is BROKEN */
return val;
}
int main() {
printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */
return 0;
}
<file_sep>#ifndef PALINDROME_PRODUCTS_H
#define PALINDROME_PRODUCTS_H
#define ERROR_MSG_LENGTH 100
typedef struct factor_t {
int factor_a;
int factor_b;
struct factor_t *next;
} factor_t;
typedef struct product_t {
int smallest;
int largest;
factor_t *factors_sm;
factor_t *factors_lg;
char *error;
} product_t;
product_t *get_palindrome_product(int a, int b);
void free_product(product_t *p);
#endif
<file_sep>#include <assert.h>
#include <errno.h>
#include <libdill.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/*
* Communication among coroutines
*
* Suppose we want the greetserver to keep statistics: The overall number of
* connections made, the number of those that are active at the moment and the
* number of those that have failed.
*
* In a classic, thread-based application, we would keep the statistics in
* global variables and synchronize access to them using mutexes.
*
* With libdill, however, we aim at "concurrency by message passing", and so we
* are going to implement the feature in a different way.
*
* We will create a new coroutine that will keep track of the statistics and a
* channel that will be used by the dialogue() coroutines to communicate with
* it:
*
* http://libdill.org/tutorial1.png
*
* First, we define the values that will be passed through the channel:
*/
#define CONN_ESTABLISHED 1
#define CONN_SUCCEEDED 2
#define CONN_FAILED 3
/*
* Making it parallel
*
* At this point, the client cannot crash the server, but it can block it. Do
* the following experiment:
*
* Start the server.
* At a different terminal, start a telnet session and, without entering your
* name, let it hang. At yet another terminal, open a new telnet session.
* Observe that the second session hangs without even asking you for your name.
* The reason for this behavior is that the program doesn't even start accepting
* new connections until the entire dialog with the client has finished. What we
* want instead is to run any number of dialogues with clients in parallel. And
* that is where coroutines kick in.
*
* Coroutines are defined using the coroutine keyword and launched with the go()
* construct.
*
* In our case, we can move the code performing the dialogue with the client
* into a separate function and launch it as a coroutine:
*/
coroutine void dialogue(int s, int ch) {
/*
* The chrecv() function will retrieve one message from the channel or block
* if there is none available. At the moment we are not sending anything to
* it, so the coroutine will simply block forever.
*
* To fix that, let's modify the dialogue() coroutine to send some messages to
* the channel. The chsend() function will be used to do that:
*/
int op = CONN_ESTABLISHED;
int rc = chsend(ch, &op, sizeof(op), -1);
assert(rc == 0);
/*
* Note that hclose() works recursively. Given that our SUFFIX socket wraps
* an underlying TCP socket, a single call to hclose() will close both of
* them.
*
* Once finished with the setup, we can send the "What's your name?"
* question to the client:
*/
/*
* File descriptors can be a scarce resource. If a client connects to the
* greetserver and lets the dialogue hang without entering a name, one file
* descriptor on the server side is, for all intents and purposes, wasted.
*
* To deal with the problem, we are going to timeout the whole client/server
* dialogue. If it takes more than 10 seconds, the server will kill the
* connection at once.
*
* One thing to note is that libdill uses deadlines rather than the more
* conventional timeouts. In other words, you specify the time instant by
* which you want the operation to finish rather than the maximum time it
* should take to run it. To construct deadlines easily, libdill provides the
* now() function. The deadline is expressed in milliseconds, which means you
* can create a deadline one minure in the future as follows:
*/
int64_t deadline = now() + 60000;
int src = msend(s, "What's your name?", 17, deadline);
if (src != 0)
goto cleanup;
/*
* Note that msend() works with messages, not bytes (the name stands for
* "message send"). Consequently, the data will act as a single unit: either
* all of it is received or none of it is. Also, we don't have to care about
* message delimiters. That's done for us by the SUFFIX protocol.
*/
/*
* To handle possible errors from msend() (such as when the client has
* closed the connection), add a cleanup label before the hclose line and
* jump to it whenever you want to close the connection and proceed without
* crashing the server.
*/
char inbuf[256];
ssize_t sz = mrecv(s, inbuf, sizeof(inbuf), -1);
if (sz < 0)
goto cleanup;
/*
* The above piece of code simply reads the reply from the client. The reply
* is a single message, which in our case translates to a single line of
* text. The mrecv function returns the number of bytes in the message.
*
* Having received a reply, we can now construct the greeting and send it to
* the client.
*/
inbuf[sz] = 0;
char outbuf[256];
rc = snprintf(outbuf, sizeof(outbuf), "Hello, %s!", inbuf);
rc = msend(s, outbuf, rc, -1);
if (rc != 0)
goto cleanup;
cleanup:
op = errno == 0 ? CONN_SUCCEEDED : CONN_FAILED;
rc = chsend(ch, &op, sizeof(op), -1);
assert(rc == 0 || errno == ECANCELED);
rc = hclose(s);
assert(rc == 0);
}
/*
*
* Libdill channels are "unbuffered". In other words, the sending coroutine will
* block each time until the receiving coroutine can process the message.
*
* This kind of behavior could, in theory, become a bottleneck, however, in our
* case we assume that the statistics() coroutine will be extremely fast and not
* turn into one.
*
* At this point we can implement the statistics() coroutine, which will run
* forever in a busy loop and collect statistics from all the dialogue()
* coroutines. Each time the statistics change, it will print them to stdout:
*
* Create a telnet session and let it time out. The output on the server side
* will look like this:
*
* $ ./greetserver
* active: 1 succeeded: 0 failed: 0
* active: 0 succeeded: 0 failed: 1
* The first line is displayed when the connection is established: There is one
* active connection and no connection has succeeded or failed yet.
*
* The second line shows up when the connection times out: There are no active
* connection anymore and one connection has failed so far.
*
*/
coroutine void statistics(int ch) {
int active = 0;
int succeeded = 0;
int failed = 0;
while (1) {
int op;
int rc = chrecv(ch, &op, sizeof(op), -1);
if (rc < 0 && errno == ECANCELED)
return;
switch (op) {
case CONN_ESTABLISHED:
++active;
break;
case CONN_SUCCEEDED:
--active;
++succeeded;
break;
case CONN_FAILED:
--active;
++failed;
break;
}
printf("active: %-5d succeeded: %-5d failed: %-5d\n", active, succeeded,
failed);
}
}
int main(int argc, char *argv[]) {
/*
* We'll assume that the first argument, if present, will be the port
* number to be used by the server. If not specified, the port number will
* default to 5555:
*/
int port = 5555;
if (argc > 1)
port = atoi(argv[1]);
/*
* The tcp_listen() function creates a listening TCP socket. The socket can be
* used to accept new TCP connections from clients:
*
* The ipaddr_local() function converts the textual representation of a local
* IP address to the actual address. Its second argument can be used to
* specify a local network interface to bind to. This is an advanced feature
* and you likely won't need it. For now, you can simply ignore it by setting
* it to NULL. This will cause the server to bind to all local network
* interfaces available.
*
* The third argument is, unsurprisingly, the port that clients will connect
* to. When testing the program, keep in mind that valid port numbers range
* from 1 to 65535 and that binding to ports 1 through 1023 will typically
* require superuser privileges.
*
* If tcp_listen() fails, it will return -1 and set errno to the appropriate
* error code. The libdill API is in this respect very similar to standard
* POSIX APIs. Consequently, we can use standard POSIX error-handling
* mechanisms such as perror() in this case.
*
*/
struct ipaddr addr;
int rc = ipaddr_local(&addr, NULL, port, 0);
assert(rc == 0);
int ls = tcp_listen(&addr, 10);
if (ls < 0) {
perror("Can't open listening socket");
return 1;
}
assert(ls >= 0);
/*
* If you run the program at this stage, you'll find out that it terminates
* immediately without pausing or waiting for a client to connect. That is
* what the tcp_accept() function is for:
*/
int ch[2];
rc = chmake(ch);
assert(rc == 0);
int cr = go(statistics(ch[0]));
assert(cr >= 0);
/*
* Once we get out of the loop we have to deallocate all the allocated
* resources. For example, we have to close the listening socket.
*
* More importantly though, we are creating coroutines and never closing the
* coroutine handles. In fact, the previous step of this tutorial contains a
* memory leak: While individual dialogue coroutines finish and their stacks
* are automatically deallocated, the handles to those coroutines remain open
* and consume a little bit of memory. If the server was run for a very long
* time those handles would eventually accumulate and cause memory usage to go
* up.
*
* Closing them is not an easy feat though. The main function would have to
* keep a list of all open coroutine handles. The coroutines, before they
* exit, would have to notify the main function about the fact so that it can
* close the handle... The more you think about it the more complex it gets.
*
* Luckily though, libdill has a concept of coroutine bundles. Bundle is a set
* of zero or more coroutines referred to by a single handle. In fact, there's
* no such a thing as direct coroutine handle. Even go which seems to return a
* coroutine handle really returns a handle to a bundle containing a single
* coroutine.
*
* We can use bundles to solve our cleanup problem. First, we will create an
* empty bundle. Then we will launch individual dialogue coroutines within the
* bundle. As the execution of any particular coroutine finishes its stack
* will be automatically deallocated and it will be removed from the bundle.
* There will be no memory leaks.
*
* Moreover, when shutting down the server we have only a single handle the
* close which will, in turn, cancel all the coroutines that are still
* running.
*
*/
int b = bundle();
assert(b >= 0);
/*
* The function returns the newly established connection.
*
* Its third argument is a deadline. the constant -1 can be used to mean 'no
* deadline' — if there is no incoming connection, the call will block
* forever.
*
* Finally, we want to handle any number of client connections instead of just
* one so we put the tcp_accept() call into an infinite loop. For now we'll
* just print a message when a new connection is established. We will close it
* immediately:
*/
int i;
for (i = 0; i != 3; i++) {
int s = tcp_accept(ls, NULL, -1);
assert(s >= 0);
printf("New connection!\n");
/*
* On top of the TCP connection that we've just created, we'll have a simple
* protocol that will split the TCP bytestream into discrete messages, using
* line breaks (CR+LF) as delimiters:
*/
s = suffix_attach(s, "\r\n", 2);
assert(s >= 0);
rc = bundle_go(b, dialogue(s, ch[1]));
assert(rc == 0);
}
/*
* Note that errno is set to ETIMEDOUT if the deadline is reached. Since we're
* treating all errors the same (by closing the connection), we don't make any
* specific provisions for deadline expiries.
*
* Now note that the third connection to the greetserver is closed immediately
* without even given user a chance to enter their name. This is a common use
* case for network servers. When the server is being shut down we want it to
* stop accepting new connections, but we also want to give it some time to
* finish handling those connections that are still open.
*
* This can be achieved by calling bundle_wait() on the dialogue() coroutine
* bundle. bundle_wait() waits for all the coroutines in the bundle to finish.
* Also, it allows to specify a deadline. We can do so immediately after
* exiting the loop:
*/
rc = bundle_wait(b, now() + 10000);
assert(rc == 0 || (rc < 0 && errno == ETIMEDOUT));
rc = hclose(b);
assert(rc == 0);
rc = hclose(ls);
assert(rc == 0);
return 0;
}
<file_sep>#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
size_t gcd2(size_t a, size_t b) {
assert(a <= b);
if (!a)
return b;
size_t rem = b % a;
return gcd2(rem, a);
}
size_t gcd(size_t a, size_t b) {
assert(a);
assert(b);
if (a < b)
return gcd2(a, b);
else
return gcd2(b, a);
}
<file_sep>#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tgmath.h>
/*
_Generic macro is part of C11 standard; compile with -std=c11 option
*/
#define type_name(T) \
_Generic((T), char : "char", int : "int", float : "float" default : "other")
const char *supported_rules[] = {"first", "second", NULL};
bool supports_rule(const char *const rulename) {
for (const char **r = supported_rules; *r; ++r) {
if (!strcmp(rulename, *r)) {
return true;
}
}
return false;
}
int main(int argc, const char *const argv[argc + 1]) {
if (argc == 1) {
printf("there are no rules\n");
return EXIT_SUCCESS;
}
const char *const rulename = argv[1];
printf("rule %s:\n", rulename);
fputs(supports_rule(rulename) ? "true" : "false", stdout);
printf("\n\n");
}
<file_sep>#include <stdio.h>
/*
https://en.wikipedia.org/wiki/Bitwise_operations_in_C
LeftShift
bit pattern equivalent is binary 100
int i = 4;
makes it binary 10000, which multiplies the original number by 4 i.e. 16
int j = i << 2;
Right shift can be used to divide a bit pattern by 2 as shown:
i = 14; // Bit pattern 00001110
// here we have the bit pattern shifted by 1 thus we get 00000111 = 7 which is 14/2
j = i >> 1;
*/
void showbits(unsigned int x) {
int i;
for (i = (sizeof(int) * 8) - 1; i >= 0; i--)
(x & (1u << i)) ? putchar('1') : putchar('0');
printf("\n");
}
int simple_addition() {
unsigned int x = 3, y = 1, sum, carry;
sum = x ^ y; // x XOR y
carry = x & y; // x AND y
while (carry != 0) {
carry = carry << 1; // left shift the carry
x = sum; // initialize x as sum
y = carry; // initialize y as carry
sum = x ^ y; // sum is calculated
carry = x & y; /* carry is calculated, the loop condition is
evaluated and the process is repeated until
carry is equal to 0.
*/
}
printf("%u\n", sum); // the program will print 4
return 0;
}
int main() {
int j = 5225, m, n;
printf("%d in binary \t\t ", j);
/* assume we have a function that prints a binary string when given
a decimal integer
*/
showbits(j);
/* the loop for right shift operation */
for (m = 0; m <= 5; m++) {
n = j >> m;
printf("%d right shift %d gives ", j, m);
showbits(n);
}
return 0;
}
<file_sep>#include "collatz_conjecture.h"
int odd(int n) { return (n & 1); }
int steps(int start) {
if (start <= 0) {
return ERROR_VALUE;
}
int steps = 0;
while (start != 1) {
steps += 1;
if (odd(start)) {
start = (start * 3) + 1;
} else {
start /= 2;
}
}
return steps;
}
<file_sep>#include "nucleotide_count.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct nucleotide_counter {
size_t adenine;
size_t cytosine;
size_t guanine;
size_t thymine;
} nucleotide_counter_t;
void initialise(nucleotide_counter_t *counter) {
counter->adenine = 0;
counter->cytosine = 0;
counter->guanine = 0;
counter->thymine = 0;
}
nucleotide_counter_t *new_counter() {
nucleotide_counter_t *counter = malloc(sizeof(nucleotide_counter_t));
if (counter == NULL) {
return NULL;
}
initialise(counter);
return counter;
}
/* count the digits. */
int lg10(int val) {
int log = 0;
if (!val)
return 1;
for (; val; (val /= 10), log++)
;
return log;
}
char *print(nucleotide_counter_t *counter) {
char *fmt = "A:%d C:%d G:%d T:%d";
int a = counter->adenine;
int c = counter->cytosine;
int g = counter->guanine;
int t = counter->thymine;
int len = lg10(a) + lg10(g) + lg10(t) + lg10(c) + 12;
char *result = malloc(len);
int n = sprintf(result, fmt, a, c, g, t);
if (n + 1 < len) {
printf("error allocating the result\n");
return NULL;
}
return result;
}
char *count(const char *dna_strand) {
nucleotide_counter_t *counter = new_counter();
char c;
while((c = *dna_strand++)) {
switch (c) {
case 'A':
counter->adenine++;
break;
case 'G':
counter->guanine++;
break;
case 'T':
counter->thymine++;
break;
case 'C':
counter->cytosine++;
break;
default:
return calloc(1, sizeof(char));
}
}
return print(counter);
}
<file_sep>#include "palindrome_products.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
int lgn(int val, int n) {
int log = 0;
if (!val)
return 1;
for (; val; (val /= n), log++)
;
return log;
}
int digits(int i) { return lgn(i, 10); }
int is_odd(int n) { return n & 1; }
char *to_array(int n, int l) {
char *arr = (char *)malloc((l + 1) * sizeof(char));
char *curr = arr;
do {
*curr++ = n % 10;
n /= 10;
} while (n != 0);
return arr;
}
int is_palindrome(int n) {
int l = digits(n);
if (l == 1) {
return 1;
}
char *arr = to_array(n, l);
char *i = arr;
char *j = arr + (l - 1);
while (i < j) {
if (*i != *j) {
return 0;
}
i++;
j--;
}
free(arr);
return 1;
}
factor_t *new_factor() {
/* TODO: check malloc error */
factor_t *f = malloc(sizeof(factor_t));
f->factor_a = 0;
f->factor_b = 0;
f->next = NULL;
return f;
}
product_t *new_product() {
product_t *p = malloc(sizeof(product_t));
char *error = malloc(sizeof(char) * ERROR_MSG_LENGTH + 1);
strcpy(error, "");
p->smallest = INT_MAX;
p->largest = INT_MIN;
p->error = error;
p->factors_sm = NULL;
p->factors_lg = NULL;
return p;
}
product_t *get_palindrome_product(int a, int b) {
product_t *p = new_product();
factor_t *f;
int res;
DEBUG_PRINT(("palindrome product in range [%02d, %02d]\n", a, b));
if (a > b) {
snprintf(p->error, ERROR_MSG_LENGTH,
"invalid input: min is %d and max is %d", a, b);
return p;
}
snprintf(p->error, ERROR_MSG_LENGTH,
"no palindrome with factors in the range %d to %d", a, b);
if (a == b) {
return p;
}
for (int i = a; i <= b; ++i) {
for (int j = i; j <= b; ++j) {
res = i * j;
if (is_palindrome(res)) {
strcpy(p->error, "");
DEBUG_PRINT(("palindrome: <%d>, sm-lg: [%d - %d]\n", res, p->smallest,
p->largest));
f = new_factor();
f->factor_a = i;
f->factor_b = j;
f->next = NULL;
if (res < p->smallest) {
p->smallest = res;
p->factors_sm = f;
DEBUG_PRINT(("found: new small: %d (%02d * %02d)\n", res, i, j));
} else if (res == p->smallest) {
f->next = p->factors_sm;
p->factors_sm = f;
DEBUG_PRINT(("appending: new small: %d (%02d * %02d)\n", res, i, j));
}
if (res > p->largest) {
p->largest = res;
p->factors_lg = f;
DEBUG_PRINT(("appending: new large: %d (%02d * %02d)\n", res, i, j));
} else if (res == p->largest) {
f->next = p->factors_lg;
p->factors_lg = f;
DEBUG_PRINT(("appending: new large: %d (%02d * %02d)\n", res, i, j));
}
}
}
}
return p;
}
void free_product(product_t *p) {
for (factor_t *f = p->factors_sm; f != NULL; f = f->next) {
free(f);
}
for (factor_t *f = p->factors_lg; f != NULL; f = f->next) {
free(f);
}
free(p);
}
<file_sep>#define FOR(i, n) for(int i = 0, _n = n; i < _n; ++i)
<file_sep>#include "beer_song.h"
#include <stdio.h>
#include <string.h>
char fmt_beers[] =
"%d bottles of beer on the wall, %d bottles of beer.\n"
"Take one down and pass it around, %d bottle%s of beer on the wall.\n";
char fmt_beer[] =
"1 bottle of beer on the wall, 1 bottle of beer.\n"
"Take it down and pass it around, no more bottles of beer on the wall.\n";
char fmt_end[] =
"No more bottles of beer on the wall, no more bottles of beer.\n"
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
void put(char *buf, int n) {
if (n == 0)
strcpy(buf, fmt_end);
else if (n == 1)
strcpy(buf, fmt_beer);
else
sprintf(buf, fmt_beers, n, n, n - 1, (n - 1 > 1) ? "s" : "");
}
void verse(char *buf, int n) { put(buf, n); }
void sing(char *buf, int start, int end) {
char *ptr = buf;
int len = 0;
for (int i = start; i >= end; i--) {
put(ptr, i);
len = strlen(ptr);
ptr += len;
strcpy(ptr++, "\n");
}
/* "closing" the string */
*--ptr = '\0';
}
<file_sep>/*
* https://github.com/hnes/libaco
* https://github.com/hnes/libaco/blob/master/aco.h
* https://github.com/hnes/libaco/blob/master/aco.c
*/
// Copyright 2018 <NAME> <EMAIL>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ACO_H
#define ACO_H
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/mman.h>
#ifdef ACO_USE_VALGRIND
#include <valgrind/valgrind.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ACO_VERSION_MAJOR 1
#define ACO_VERSION_MINOR 2
#define ACO_VERSION_PATCH 2
#ifdef __i386__
#define ACO_REG_IDX_RETADDR 0
#define ACO_REG_IDX_SP 1
#define ACO_REG_IDX_FPU 6
#elif __x86_64__
#define ACO_REG_IDX_RETADDR 4
#define ACO_REG_IDX_SP 5
#define ACO_REG_IDX_FPU 8
#else
#error "platform no support yet"
#endif
typedef struct {
void* ptr;
size_t sz;
size_t valid_sz;
// max copy size in bytes
size_t max_cpsz;
// copy from share stack to this save stack
size_t ct_save;
// copy from this save stack to share stack
size_t ct_restore;
} aco_save_stack_t;
struct aco_s;
typedef struct aco_s aco_t;
typedef struct {
void* ptr;
size_t sz;
void* align_highptr;
void* align_retptr;
size_t align_validsz;
size_t align_limit;
aco_t* owner;
char guard_page_enabled;
void* real_ptr;
size_t real_sz;
#ifdef ACO_USE_VALGRIND
unsigned long valgrind_stk_id;
#endif
} aco_share_stack_t;
typedef void (*aco_cofuncp_t)(void);
struct aco_s{
// cpu registers' state
#ifdef __i386__
#ifdef ACO_CONFIG_SHARE_FPU_MXCSR_ENV
void* reg[6];
#else
void* reg[8];
#endif
#elif __x86_64__
#ifdef ACO_CONFIG_SHARE_FPU_MXCSR_ENV
void* reg[8];
#else
void* reg[9];
#endif
#else
#error "platform no support yet"
#endif
aco_t* main_co;
void* arg;
char is_end;
aco_cofuncp_t fp;
aco_save_stack_t save_stack;
aco_share_stack_t* share_stack;
};
#define aco_likely(x) (__builtin_expect(!!(x), 1))
#define aco_unlikely(x) (__builtin_expect(!!(x), 0))
#define aco_assert(EX) ((aco_likely(EX))?((void)0):(abort()))
#define aco_assertptr(ptr) ((aco_likely((ptr) != NULL))?((void)0):(abort()))
#define aco_assertalloc_bool(b) do { \
if(aco_unlikely(!(b))){ \
fprintf(stderr, "Aborting: failed to allocate memory: %s:%d:%s\n", \
__FILE__, __LINE__, __PRETTY_FUNCTION__); \
abort(); \
} \
} while(0)
#define aco_assertalloc_ptr(ptr) do { \
if(aco_unlikely((ptr) == NULL)){ \
fprintf(stderr, "Aborting: failed to allocate memory: %s:%d:%s\n", \
__FILE__, __LINE__, __PRETTY_FUNCTION__); \
abort(); \
} \
} while(0)
extern void aco_runtime_test();
extern void aco_thread_init(aco_cofuncp_t last_word_co_fp);
// TODO: plan to use regparm(0) (fastcall) in Sys V ABI intel386
// to accelerate acosw and copystack(-8bytes), and PR is welcome :)
extern void* acosw(aco_t* from_co, aco_t* to_co); // asm
extern void aco_save_fpucw_mxcsr(void* p); // asm
extern void aco_funcp_protector_asm(); // asm
extern void aco_funcp_protector();
extern aco_share_stack_t* aco_share_stack_new(size_t sz);
aco_share_stack_t* aco_share_stack_new2(size_t sz, char guard_page_enabled);
extern void aco_share_stack_destroy(aco_share_stack_t* sstk);
extern aco_t* aco_create(
aco_t* main_co,
aco_share_stack_t* share_stack,
size_t save_stack_sz,
aco_cofuncp_t fp, void* arg
);
// aco's Global Thread Local Storage variable `co`
extern __thread aco_t* aco_gtls_co;
extern void aco_resume(aco_t* resume_co);
//extern void aco_yield1(aco_t* yield_co);
#define aco_yield1(yield_co) do { \
aco_assertptr((yield_co)); \
aco_assertptr((yield_co)->main_co); \
acosw((yield_co), (yield_co)->main_co); \
} while(0)
#define aco_yield() do { \
aco_yield1(aco_gtls_co); \
} while(0)
#define aco_get_arg() (aco_gtls_co->arg)
#define aco_get_co() ({(void)0; aco_gtls_co;})
#define aco_co() ({(void)0; aco_gtls_co;})
extern void aco_destroy(aco_t* co);
#define aco_is_main_co(co) ({((co)->main_co) == NULL;})
#define aco_exit1(co) do { \
(co)->is_end = 1; \
aco_assert((co)->share_stack->owner == (co)); \
(co)->share_stack->owner = NULL; \
(co)->share_stack->align_validsz = 0; \
aco_yield1((co)); \
aco_assert(0); \
} while(0)
#define aco_exit() do { \
aco_exit1(aco_gtls_co); \
} while(0)
#ifdef __cplusplus
}
#endif
#endif
/* https://raw.githubusercontent.com/hnes/libaco/master/aco.c */
// Copyright 2018 <NAME> <EMAIL>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "aco.h"
#include <stdio.h>
#include <stdint.h>
// this header including should be at the last of the `include` directives list
#include "aco_assert_override.h"
void aco_runtime_test(){
#ifdef __i386__
_Static_assert(sizeof(void*) == 4, "require 'sizeof(void*) == 4'");
#elif __x86_64__
_Static_assert(sizeof(void*) == 8, "require 'sizeof(void*) == 8'");
_Static_assert(sizeof(__uint128_t) == 16, "require 'sizeof(__uint128_t) == 16'");
#else
#error "platform no support yet"
#endif
_Static_assert(sizeof(int) >= 4, "require 'sizeof(int) >= 4'");
assert(sizeof(int) >= 4);
_Static_assert(sizeof(int) <= sizeof(size_t),
"require 'sizeof(int) <= sizeof(size_t)'");
assert(sizeof(int) <= sizeof(size_t));
}
// assertptr(dst); assertptr(src);
// assert((((uintptr_t)(src) & 0x0f) == 0) && (((uintptr_t)(dst) & 0x0f) == 0));
// assert((((sz) & 0x0f) == 0x08) && (((sz) >> 4) >= 0) && (((sz) >> 4) <= 8));
// sz = 16*n + 8 ( 0 <= n <= 8)
// Note: dst and src must be valid address already
#define aco_amd64_inline_short_aligned_memcpy_test_ok(dst, src, sz) \
( \
(((uintptr_t)(src) & 0x0f) == 0) && (((uintptr_t)(dst) & 0x0f) == 0) \
&& \
(((sz) & 0x0f) == 0x08) && (((sz) >> 4) >= 0) && (((sz) >> 4) <= 8) \
)
#define aco_amd64_inline_short_aligned_memcpy(dst, src, sz) do {\
__uint128_t xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7; \
switch((sz) >> 4){ \
case 0: \
break; \
case 1: \
xmm0 = *((__uint128_t*)(src) + 0); \
*((__uint128_t*)(dst) + 0) = xmm0; \
break; \
case 2: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
break; \
case 3: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
break; \
case 4: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
xmm3 = *((__uint128_t*)(src) + 3); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
*((__uint128_t*)(dst) + 3) = xmm3; \
break; \
case 5: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
xmm3 = *((__uint128_t*)(src) + 3); \
xmm4 = *((__uint128_t*)(src) + 4); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
*((__uint128_t*)(dst) + 3) = xmm3; \
*((__uint128_t*)(dst) + 4) = xmm4; \
break; \
case 6: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
xmm3 = *((__uint128_t*)(src) + 3); \
xmm4 = *((__uint128_t*)(src) + 4); \
xmm5 = *((__uint128_t*)(src) + 5); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
*((__uint128_t*)(dst) + 3) = xmm3; \
*((__uint128_t*)(dst) + 4) = xmm4; \
*((__uint128_t*)(dst) + 5) = xmm5; \
break; \
case 7: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
xmm3 = *((__uint128_t*)(src) + 3); \
xmm4 = *((__uint128_t*)(src) + 4); \
xmm5 = *((__uint128_t*)(src) + 5); \
xmm6 = *((__uint128_t*)(src) + 6); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
*((__uint128_t*)(dst) + 3) = xmm3; \
*((__uint128_t*)(dst) + 4) = xmm4; \
*((__uint128_t*)(dst) + 5) = xmm5; \
*((__uint128_t*)(dst) + 6) = xmm6; \
break; \
case 8: \
xmm0 = *((__uint128_t*)(src) + 0); \
xmm1 = *((__uint128_t*)(src) + 1); \
xmm2 = *((__uint128_t*)(src) + 2); \
xmm3 = *((__uint128_t*)(src) + 3); \
xmm4 = *((__uint128_t*)(src) + 4); \
xmm5 = *((__uint128_t*)(src) + 5); \
xmm6 = *((__uint128_t*)(src) + 6); \
xmm7 = *((__uint128_t*)(src) + 7); \
*((__uint128_t*)(dst) + 0) = xmm0; \
*((__uint128_t*)(dst) + 1) = xmm1; \
*((__uint128_t*)(dst) + 2) = xmm2; \
*((__uint128_t*)(dst) + 3) = xmm3; \
*((__uint128_t*)(dst) + 4) = xmm4; \
*((__uint128_t*)(dst) + 5) = xmm5; \
*((__uint128_t*)(dst) + 6) = xmm6; \
*((__uint128_t*)(dst) + 7) = xmm7; \
break; \
}\
*((uint64_t*)((uintptr_t)(dst) + (sz) - 8)) = *((uint64_t*)((uintptr_t)(src) + (sz) - 8)); \
} while(0)
// Note: dst and src must be valid address already
#define aco_amd64_optimized_memcpy_drop_in(dst, src, sz) do {\
if(aco_amd64_inline_short_aligned_memcpy_test_ok((dst), (src), (sz))){ \
aco_amd64_inline_short_aligned_memcpy((dst), (src), (sz)); \
}else{ \
memcpy((dst), (src), (sz)); \
} \
} while(0)
static void aco_default_protector_last_word(){
aco_t* co = aco_get_co();
// do some log about the offending `co`
fprintf(stderr,"error: aco_default_protector_last_word triggered\n");
fprintf(stderr, "error: co:%p should call `aco_exit()` instead of direct "
"`return` in co_fp:%p to finish its execution\n", co, (void*)co->fp);
assert(0);
}
// aco's Global Thread Local Storage variable `co`
__thread aco_t* aco_gtls_co;
static __thread aco_cofuncp_t aco_gtls_last_word_fp = aco_default_protector_last_word;
#ifdef __i386__
static __thread void* aco_gtls_fpucw_mxcsr[2];
#elif __x86_64__
static __thread void* aco_gtls_fpucw_mxcsr[1];
#else
#error "platform no support yet"
#endif
void aco_thread_init(aco_cofuncp_t last_word_co_fp){
aco_save_fpucw_mxcsr(aco_gtls_fpucw_mxcsr);
if((void*)last_word_co_fp != NULL)
aco_gtls_last_word_fp = last_word_co_fp;
}
// This function `aco_funcp_protector` should never be
// called. If it's been called, that means the offending
// `co` didn't call aco_exit(co) instead of `return` to
// finish its execution.
void aco_funcp_protector(){
if((void*)(aco_gtls_last_word_fp) != NULL){
aco_gtls_last_word_fp();
}else{
aco_default_protector_last_word();
}
assert(0);
}
aco_share_stack_t* aco_share_stack_new(size_t sz){
return aco_share_stack_new2(sz, 1);
}
#define aco_size_t_safe_add_assert(a,b) do { \
assert((a)+(b) >= (a)); \
}while(0)
aco_share_stack_t* aco_share_stack_new2(size_t sz, char guard_page_enabled){
if(sz == 0){
sz = 1024 * 1024 * 2;
}
if(sz < 4096){
sz = 4096;
}
assert(sz > 0);
size_t u_pgsz = 0;
if(guard_page_enabled != 0){
// although gcc's Built-in Functions to Perform Arithmetic with
// Overflow Checking is better, but it would require gcc >= 5.0
long pgsz = sysconf(_SC_PAGESIZE);
// pgsz must be > 0 && a power of two
assert(pgsz > 0 && (((pgsz - 1) & pgsz) == 0));
u_pgsz = (size_t)((unsigned long)pgsz);
// it should be always true in real life
assert(u_pgsz == (unsigned long)pgsz && ((u_pgsz << 1) >> 1) == u_pgsz);
if(sz <= u_pgsz){
sz = u_pgsz << 1;
} else {
size_t new_sz;
if((sz & (u_pgsz - 1)) != 0){
new_sz = (sz & (~(u_pgsz - 1)));
assert(new_sz >= u_pgsz);
aco_size_t_safe_add_assert(new_sz, (u_pgsz << 1));
new_sz = new_sz + (u_pgsz << 1);
assert(sz / u_pgsz + 2 == new_sz / u_pgsz);
} else {
aco_size_t_safe_add_assert(sz, u_pgsz);
new_sz = sz + u_pgsz;
assert(sz / u_pgsz + 1 == new_sz / u_pgsz);
}
sz = new_sz;
assert((sz / u_pgsz > 1) && ((sz & (u_pgsz - 1)) == 0));
}
}
aco_share_stack_t* p = malloc(sizeof(aco_share_stack_t));
assertalloc_ptr(p);
memset(p, 0, sizeof(aco_share_stack_t));
if(guard_page_enabled != 0){
p->real_ptr = mmap(
NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0
);
assertalloc_bool(p->real_ptr != MAP_FAILED);
p->guard_page_enabled = 1;
assert(0 == mprotect(p->real_ptr, u_pgsz, PROT_READ));
p->ptr = (void*)(((uintptr_t)p->real_ptr) + u_pgsz);
p->real_sz = sz;
assert(sz >= (u_pgsz << 1));
p->sz = sz - u_pgsz;
} else {
//p->guard_page_enabled = 0;
p->sz = sz;
p->ptr = malloc(sz);
assertalloc_ptr(p->ptr);
}
p->owner = NULL;
#ifdef ACO_USE_VALGRIND
p->valgrind_stk_id = VALGRIND_STACK_REGISTER(
p->ptr, (void*)((uintptr_t)p->ptr + p->sz)
);
#endif
#if defined(__i386__) || defined(__x86_64__)
uintptr_t u_p = (uintptr_t)(p->sz - (sizeof(void*) << 1) + (uintptr_t)p->ptr);
u_p = (u_p >> 4) << 4;
p->align_highptr = (void*)u_p;
p->align_retptr = (void*)(u_p - sizeof(void*));
*((void**)(p->align_retptr)) = (void*)(aco_funcp_protector_asm);
assert(p->sz > (16 + (sizeof(void*) << 1) + sizeof(void*)));
p->align_limit = p->sz - 16 - (sizeof(void*) << 1);
#else
#error "platform no support yet"
#endif
return p;
}
void aco_share_stack_destroy(aco_share_stack_t* sstk){
assert(sstk != NULL && sstk->ptr != NULL);
#ifdef ACO_USE_VALGRIND
VALGRIND_STACK_DEREGISTER(sstk->valgrind_stk_id);
#endif
if(sstk->guard_page_enabled){
assert(0 == munmap(sstk->real_ptr, sstk->real_sz));
sstk->real_ptr = NULL;
sstk->ptr = NULL;
} else {
free(sstk->ptr);
sstk->ptr = NULL;
}
free(sstk);
}
aco_t* aco_create(
aco_t* main_co, aco_share_stack_t* share_stack,
size_t save_stack_sz, aco_cofuncp_t fp, void* arg
){
aco_t* p = malloc(sizeof(aco_t));
assertalloc_ptr(p);
memset(p, 0, sizeof(aco_t));
if(main_co != NULL){ // non-main co
assertptr(share_stack);
p->share_stack = share_stack;
#ifdef __i386__
// POSIX.1-2008 (IEEE Std 1003.1-2008) - General Information - Data Types - Pointer Types
// http://pubs.opengroup.org/onlinepubs/9699919799.2008edition/functions/V2_chap02.html#tag_15_12_03
p->reg[ACO_REG_IDX_RETADDR] = (void*)fp;
// push retaddr
p->reg[ACO_REG_IDX_SP] = p->share_stack->align_retptr;
#ifndef ACO_CONFIG_SHARE_FPU_MXCSR_ENV
p->reg[ACO_REG_IDX_FPU] = aco_gtls_fpucw_mxcsr[0];
p->reg[ACO_REG_IDX_FPU + 1] = aco_gtls_fpucw_mxcsr[1];
#endif
#elif __x86_64__
p->reg[ACO_REG_IDX_RETADDR] = (void*)fp;
p->reg[ACO_REG_IDX_SP] = p->share_stack->align_retptr;
#ifndef ACO_CONFIG_SHARE_FPU_MXCSR_ENV
p->reg[ACO_REG_IDX_FPU] = aco_gtls_fpucw_mxcsr[0];
#endif
#else
#error "platform no support yet"
#endif
p->main_co = main_co;
p->arg = arg;
p->fp = fp;
if(save_stack_sz == 0){
save_stack_sz = 64;
}
p->save_stack.ptr = malloc(save_stack_sz);
assertalloc_ptr(p->save_stack.ptr);
p->save_stack.sz = save_stack_sz;
#if defined(__i386__) || defined(__x86_64__)
p->save_stack.valid_sz = 0;
#else
#error "platform no support yet"
#endif
return p;
} else { // main co
p->main_co = NULL;
p->arg = arg;
p->fp = fp;
p->share_stack = NULL;
p->save_stack.ptr = NULL;
return p;
}
assert(0);
}
void aco_resume(aco_t* resume_co){
assert(resume_co != NULL && resume_co->main_co != NULL
&& resume_co->is_end == 0
);
if(resume_co->share_stack->owner != resume_co){
if(resume_co->share_stack->owner != NULL){
aco_t* owner_co = resume_co->share_stack->owner;
assert(owner_co->share_stack == resume_co->share_stack);
#if defined(__i386__) || defined(__x86_64__)
assert(
(
(uintptr_t)(owner_co->share_stack->align_retptr)
>=
(uintptr_t)(owner_co->reg[ACO_REG_IDX_SP])
)
&&
(
(uintptr_t)(owner_co->share_stack->align_highptr)
-
(uintptr_t)(owner_co->share_stack->align_limit)
<=
(uintptr_t)(owner_co->reg[ACO_REG_IDX_SP])
)
);
owner_co->save_stack.valid_sz =
(uintptr_t)(owner_co->share_stack->align_retptr)
-
(uintptr_t)(owner_co->reg[ACO_REG_IDX_SP]);
if(owner_co->save_stack.sz < owner_co->save_stack.valid_sz){
free(owner_co->save_stack.ptr);
owner_co->save_stack.ptr = NULL;
while(1){
owner_co->save_stack.sz = owner_co->save_stack.sz << 1;
assert(owner_co->save_stack.sz > 0);
if(owner_co->save_stack.sz >= owner_co->save_stack.valid_sz){
break;
}
}
owner_co->save_stack.ptr = malloc(owner_co->save_stack.sz);
assertalloc_ptr(owner_co->save_stack.ptr);
}
// TODO: optimize the performance penalty of memcpy function call
// for very short memory span
if(owner_co->save_stack.valid_sz > 0) {
#ifdef __x86_64__
aco_amd64_optimized_memcpy_drop_in(
owner_co->save_stack.ptr,
owner_co->reg[ACO_REG_IDX_SP],
owner_co->save_stack.valid_sz
);
#else
memcpy(
owner_co->save_stack.ptr,
owner_co->reg[ACO_REG_IDX_SP],
owner_co->save_stack.valid_sz
);
#endif
owner_co->save_stack.ct_save++;
}
if(owner_co->save_stack.valid_sz > owner_co->save_stack.max_cpsz){
owner_co->save_stack.max_cpsz = owner_co->save_stack.valid_sz;
}
owner_co->share_stack->owner = NULL;
owner_co->share_stack->align_validsz = 0;
#else
#error "platform no support yet"
#endif
}
assert(resume_co->share_stack->owner == NULL);
#if defined(__i386__) || defined(__x86_64__)
assert(
resume_co->save_stack.valid_sz
<=
resume_co->share_stack->align_limit - sizeof(void*)
);
// TODO: optimize the performance penalty of memcpy function call
// for very short memory span
if(resume_co->save_stack.valid_sz > 0) {
#ifdef __x86_64__
aco_amd64_optimized_memcpy_drop_in(
(void*)(
(uintptr_t)(resume_co->share_stack->align_retptr)
-
resume_co->save_stack.valid_sz
),
resume_co->save_stack.ptr,
resume_co->save_stack.valid_sz
);
#else
memcpy(
(void*)(
(uintptr_t)(resume_co->share_stack->align_retptr)
-
resume_co->save_stack.valid_sz
),
resume_co->save_stack.ptr,
resume_co->save_stack.valid_sz
);
#endif
resume_co->save_stack.ct_restore++;
}
if(resume_co->save_stack.valid_sz > resume_co->save_stack.max_cpsz){
resume_co->save_stack.max_cpsz = resume_co->save_stack.valid_sz;
}
resume_co->share_stack->align_validsz = resume_co->save_stack.valid_sz + sizeof(void*);
resume_co->share_stack->owner = resume_co;
#else
#error "platform no support yet"
#endif
}
aco_gtls_co = resume_co;
acosw(resume_co->main_co, resume_co);
aco_gtls_co = resume_co->main_co;
}
void aco_destroy(aco_t* co){
assertptr(co);
if(aco_is_main_co(co)){
free(co);
} else {
if(co->share_stack->owner == co){
co->share_stack->owner = NULL;
co->share_stack->align_validsz = 0;
}
free(co->save_stack.ptr);
co->save_stack.ptr = NULL;
free(co);
}
}
/* https://raw.githubusercontent.com/hnes/libaco/master/test_aco_tutorial_0.c */
// Copyright 2018 <NAME> <EMAIL>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Hello aco demo.
#include "aco.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "aco_assert_override.h"
void co_fp0() {
// Get co->arg. The caller of `aco_get_arg()` must be a non-main co.
int *iretp = (int *)aco_get_arg();
// Get current co. The caller of `aco_get_co()` must be a non-main co.
aco_t* this_co = aco_get_co();
int ct = 0;
while(ct < 6){
printf(
"co:%p save_stack:%p share_stack:%p yield_ct:%d\n",
this_co, this_co->save_stack.ptr,
this_co->share_stack->ptr, ct
);
// Yield the execution of current co and resume the execution of
// `co->main_co`. The caller of `aco_yield()` must be a non-main co.
aco_yield();
(*iretp)++;
ct++;
}
printf(
"co:%p save_stack:%p share_stack:%p co_exit()\n",
this_co, this_co->save_stack.ptr,
this_co->share_stack->ptr
);
// In addition do the same as `aco_yield()`, `aco_exit()` also set
// `co->is_end` to `1` thus to mark the `co` at the status of "END".
aco_exit();
}
int main() {
#ifdef ACO_USE_VALGRIND
if(0){
printf("%s doesn't have valgrind test yet, "
"so bypass this test right now.\n",__FILE__
);
exit(0);
}
#endif
// Initialize the aco environment in the current thread.
aco_thread_init(NULL);
// Create a main coroutine whose "share stack" is the default stack
// of the current thread. And it doesn't need any private save stack
// since it is definitely a standalone coroutine (which coroutine
// monopolizes it's share stack).
aco_t* main_co = aco_create(NULL, NULL, 0, NULL, NULL);
// Create a share stack with the default size of 2MB and also with a
// read-only guard page for the detection of stack overflow.
aco_share_stack_t* sstk = aco_share_stack_new(0);
int co_ct_arg_point_to_me = 0;
// Create a non-main coroutine whose share stack is `sstk` and has a
// default 64 bytes size private save stack. The entry function of the
// coroutine is `co_fp0`. Set `co->arg` to the address of the int
// variable `co_ct_arg_point_to_me`.
aco_t* co = aco_create(main_co, sstk, 0, co_fp0, &co_ct_arg_point_to_me);
int ct = 0;
while(ct < 6){
assert(co->is_end == 0);
// Start or continue the execution of `co`. The caller of this function
// must be main_co.
aco_resume(co);
// Check whether the co has completed the job it promised.
assert(co_ct_arg_point_to_me == ct);
printf("main_co:%p\n", main_co);
ct++;
}
aco_resume(co);
assert(co_ct_arg_point_to_me == ct);
// The value of `co->is_end` must be `1` now since it just suspended
// itself by calling `aco_exit()`.
assert(co->is_end);
printf("main_co:%p\n", main_co);
// Destroy co and its private save stack.
aco_destroy(co);
co = NULL;
// Destroy the share stack sstk.
aco_share_stack_destroy(sstk);
sstk = NULL;
// Destroy the main_co.
aco_destroy(main_co);
main_co = NULL;
return 0;
}
/* end */
<file_sep>#include <stdio.h>
#include <string.h>
// http://en.cppreference.com/w/c/string/byte/strcat
// https://stackoverflow.com/a/1496328
//
// http://en.cppreference.com/w/c/string/byte/strncpy
// char *strncpy( char *dest, const char *src, size_t count );
void concat_these(char *dest, char *a, char *b, char *c, int buffersize) {
int x = 0;
// failure when space allocated to str is insufficient.
if (!dest || buffersize < 1) {
printf("no dest or not enough buffersize");
return; // bad input. Let junk deal with junk data.
}
printf("sizeof a: %lu\n", sizeof(a));
printf("strlen a: %lu\n", strlen(a));
printf("strlen b: %lu\n", strlen(b));
printf("strlen c: %lu\n", strlen(c));
if (sizeof(a) > strlen(a) + strlen(b) + strlen(c)) {
/* 1st method*/
strcat(a, b);
/*2nd method*/
x = strlen(a);
sprintf(&a[x], "%s", c);
strncpy(dest, a, buffersize - 1);
} else {
printf("conditions are not met\n");
*dest = '\0';
}
dest[buffersize - 1] = '\0';
return;
}
int main(void) {
char some[10];
char a[8];
char *b = "bbb";
char *c = "ccc";
printf("A: %s (%lu)(%lu)\n", a, strlen(a), sizeof(a));
printf("B: %s (%lu)(%lu)\n", b, strlen(b), sizeof(b));
printf("C: %s (%lu)(%lu)\n", c, strlen(c), sizeof(c));
concat_these(some, a, b, c, sizeof(some));
printf("Content concatt'd: %s (%lu)(%lu)\n", some, strlen(some),
sizeof(some));
return 0;
}
<file_sep>/*
* Suppose two integer values a and b
* Perform, x = a ^ b
* Now x ^ b will evaluate to a
* and x ^ a will evaluate to b.
*/
#include <stdio.h>
int main() {
int num1, num2;
/* Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
printf("Original value of num1 = %d\n", num1);
printf("Original value of num2 = %d\n", num2);
/* Swap two numbers */
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
printf("Num1 after swapping = %d\n", num1);
printf("Num2 after swapping = %d\n", num2);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
* Exercises
*
* - [Exs 00]:
*
*/
/*
* Now we see the use of the second parameter of strtoull. Here, it is the
* address of the variable next, and next is used to keep track of the position
* in the string that ends the number. Since next is a pointer to char, the
* argument to strtoull is a pointer to a pointer to char. Suppose strtoull is
* called as strtoull("0789a", &next, base). According to the value of the
* parameter base that string is interpreted differently. If for example base
* has value 10, the first non-digit is the character 'a' at the end.
*/
static size_t numberline_inner(char const *restrict act, size_t numb[restrict],
int base) {
size_t n = 0;
for (char *next = 0; act[0]; act = next) {
numb[n] = strtoull(act, &next, base);
if (act == next)
break;
++n;
}
return n;
}
/*
* Now, the function numberline itself provides the glue around
* numberline_inner:
*
* - If np is null, it is set to point to an auxiliary.
* - The input string is a checked for validity.
* - An array with enough elements to store the values is allocated and tailored
* to the appropriate size, once the correct length is known.
*/
size_t *numberline(size_t size, char const lbuf[restrict size],
size_t *restrict np, int base) {
size_t *ret = 0;
size_t n = 0;
/*
* Check for validity of the string, first.
*
* memchr
* void * memchr(const void *s, int c, size_t n);
* Description
* The memchr() function locates the first occurrence of c (converted to an
* unsigned char) in string s.
* Return Values
* The memchr() function returns a pointer to the byte located, or
* NULL if no such byte exists within n bytes.
* The call to memchr returns the address of the first byte that has
* value 0, if there is any, or (void*)0 if there is none. Here, this
* is just used to check that within the first size bytes there
* effectively is a 0-character. By that it guarantees that all the
* string functions that are used underneath (in particular strtoull)
* operate on a 0-terminated string.
*/
if (memchr(lbuf, 0, size)) {
/* The maximum number of integers encoded. To see that this
may be as much look at the sequence 08 08 08 08 ... */
ret = malloc(sizeof(size_t[1 + (2 * size) / 3]));
n = numberline_inner(lbuf, ret, base);
/* Supposes that shrinking realloc will always succeed . */
size_t len = n ? n : 1;
ret = realloc(ret, sizeof(size_t[len]));
}
if (np)
*np = n;
return ret;
}
char *fgetline(size_t size, char s[restrict size], FILE *restrict stream) {
s[0] = 0;
char *ret = fgets(s, size, stream);
if (ret) {
/* s is writable so can be pos. */
char *pos = strchr(s, '\n');
if (pos)
*pos = 0;
else
ret = 0;
}
return ret;
}
int sprintnumbers(size_t tot, char buf[restrict tot],
char const form[restrict static 1],
char const sep[restrict static 1], size_t len,
size_t nums[restrict len]) {
char *p = buf;
size_t const seplen = strlen(sep);
if (len) {
size_t i = 0;
for (;;) {
p += sprintf(p, form, nums[i]);
++i;
if (i >= len)
break;
memcpy(p, sep, seplen);
p += seplen;
}
}
memcpy(p, "\n", 2);
return (p - buf) + 1;
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do\n\n");
return EXIT_SUCCESS;
}
<file_sep>#include <ncurses.h>
WINDOW *create_newwin(int height, int width, int starty, int startx);
void destroy_win(WINDOW *local_win);
/*
* This program creates a rectangular window that can be moved with left, right,
* up, down arrow keys. It repeatedly creates and destroys windows as user press
* a key. Don't go beyond the screen limits. Checking for those limits is left
* as an exercise for the reader.
*/
int main(void) {
WINDOW *my_win;
int startx, starty, width, height;
int ch;
initscr(); /* Start curses mode */
cbreak(); /* Line buffering disabled, Pass on
* every thing to me */
keypad(stdscr, TRUE); /* I need that nifty F1 */
height = 3;
width = 10;
starty = (LINES - height) / 2; /* Calculating for a center placement */
startx = (COLS - width) / 2; /* of the window */
printw("Press Q to exit");
/*
* The curs_set routine sets the cursor state is set to invisible, normal,
* or very visible for visibility equal to 0, 1, or 2 respectively. If the
* terminal supports the visibility requested, the previous cursor state is
* re- turned; otherwise, ERR is returned.
*/
curs_set(0);
refresh();
/*
* The create_newwin() function creates a window with newwin() and displays a
* border around it with box. The function destroy_win() first erases the
* window from screen by painting a border with ' ' character and then calling
* delwin() to deallocate memory related to it. Depending on the key the user
* presses, starty or startx is changed and a new window is created.
*/
my_win = create_newwin(height, width, starty, startx);
while ((ch = getch()) != 'Q') { /* KEY_F(1) */
switch (ch) {
case KEY_LEFT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty, --startx);
break;
case KEY_RIGHT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty, ++startx);
break;
case KEY_UP:
destroy_win(my_win);
my_win = create_newwin(height, width, --starty, startx);
break;
case KEY_DOWN:
destroy_win(my_win);
my_win = create_newwin(height, width, ++starty, startx);
break;
}
}
endwin(); /* End curses mode */
return 0;
}
WINDOW *create_newwin(int height, int width, int starty, int startx) {
WINDOW *local_win;
local_win = newwin(height, width, starty, startx);
box(local_win, 0, 0); /* 0, 0 gives default characters
* for the vertical and horizontal
* lines */
wrefresh(local_win); /* Show that box */
return local_win;
}
void destroy_win(WINDOW *local_win) {
/* box(local_win, ' ', ' '); : This won't produce the desired
* result of erasing the window. It will leave it's four corners
* and so an ugly remnant of window.
*/
wborder(local_win, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
/* The parameters taken are
* 1. win: the window on which to operate
* 2. ls: character to be used for the left side of the window
* 3. rs: character to be used for the right side of the window
* 4. ts: character to be used for the top side of the window
* 5. bs: character to be used for the bottom side of the window
* 6. tl: character to be used for the top left corner of the window
* 7. tr: character to be used for the top right corner of the window
* 8. bl: character to be used for the bottom left corner of the window
* 9. br: character to be used for the bottom right corner of the window
*/
wrefresh(local_win);
delwin(local_win);
}
<file_sep>#ifndef SAY_H
#define SAY_H
int say(long number, char **buffer);
#endif
<file_sep>/*
* indenter: a recursive descent parser to indent text.
*
* The function descend implements a simple recursive descent parser that
* recognizes {} constructs in a text given on stdin and indents this text on
* output, according to the nesting of the {}. More formally this function
* detects text as of the following recursive definition:
* program := some-text* ['{' program '}' some-text*]*
* and prints such a program conveniently by changing the line structure
* and indentation.⋆
*
* Graphic representation:
*
* HEAD (11) is now: --[ ........... ]--
* {{{{a}{b}{c}}}}
* ......
* .......
* ........
* .........
* ..........a
* .........
* ..........b
* .........
* ..........c
* .........
* ........
* .......
* ......
*
* or
*
* emacs:~/workspaces/pebbles$ ./pebbles
* HEAD (10) is now: --[ 0123456789 ]--
* {{{{a}{b}{c}}}}
* 56789
* 456789
* 3456789
* 23456789
* 123456789a
* 23456789
* 123456789b
* 23456789
* 123456789c
* 23456789
* 3456789
* 456789
* 56789
*
*/
#import <errno.h>
#import <signal.h>
#import <stdio.h>
#import <stdlib.h>
#import <string.h>
/* setjmp.h
* https://en.cppreference.com/w/c/program/setjmp
* https://en.wikipedia.org/wiki/Setjmp.h
* https://web.eecs.utk.edu/~huangj/cs360/360/notes/Setjmp/lecture.html
*/
#import <setjmp.h>
/* https://en.cppreference.com/w/c/io/fwprintf */
#import <wchar.h>
#ifdef DEBUG
#define DEBUG_PRINTF(x) printf x
#else
#define DEBUG_PRINTF(x) \
do { \
} while (0)
#endif
#define LEFT '{'
#define RIGHT '}'
char *head;
static int interrupt = 0;
/**
** @brief exceptional states of the parse algorithm
**/
enum state {
execution = 0, //*< normal execution
plusL, //*< too many left parenthesis
plusR, //*< too many right parenthesis
tooDeep, //*< nesting too deep to handle
eofOut, //*< end of output
interrupted, //*< interrupted by signal
};
/*
* 18. Variations In Control Flow, page 213
* 18.4. Longjumps. Our function `descend` may also encounter
* exceptional conditions that can not be repaired. We use an
* enumeration type to name them. Here, eofOut is reached if stdout
* can’t be written, and interrupted refers to an asynchronous signal
* that our running program received. We will discuss this concept
* later.
*/
/*
* @brief prototype of signal handlers
*/
typedef void sh_handler(int);
/* Signal handlers are established by a call to signal, as we can already see in
* our function signal_handler. Here, it is just used to reset the signal
* disposition to the default. signal is one of the two function interfaces that
* are provided by signal.h; the return value of signal is the handler that had
* previously been active for the signal
*
* sh_handler* signal(int, sh_handler*);
* int raise(int);
*
* The return value of signal is the handler that had previously been active for
* the signal, or the special value SIG_ERR if an error occurred. Inside a
* signal handler, signal should only be used to change the disposition of the
* same signal number that was received by the call. The following function has
* the same interface as signal but provides a bit more information about the
* success of the call.
* The second function raise can be used to deliver the specified signal to
* the current execution.
*/
/*
Since even the list of signals that the C standard specifies is minimal, dealing
with the different possible conditions becomes complicated. The following shows
how we can handle a collection of signal numbers that goes beyond those that are
specified in the C standard
*/
/**
** @brief A pair of strings to hold signal information
**/
typedef struct sh_pair sh_pair;
struct sh_pair {
char const *name;
char const *desc;
};
#define SH_PAIR(X, D) \
[X] = { \
.name = #X, \
.desc = "" D "", \
}
/**
** @brief Array that holds names and descriptions of the
** standard C signals. **
** Conditionally, we also add some commonly used signals. **/
sh_pair const sh_pairs[] = {
/* Execution errors */
SH_PAIR(SIGFPE, "erroneous␣arithmetic␣operation"),
SH_PAIR(SIGILL, "invalid␣instruction"),
SH_PAIR(SIGSEGV, "invalid␣access␣to␣storage"),
#ifdef SIGBUS
SH_PAIR(SIGBUS, "bad␣address"),
#endif
/* Job control */
SH_PAIR(SIGABRT, "abnormal␣termination"),
SH_PAIR(SIGINT, "interactive␣attention␣signal"),
SH_PAIR(SIGTERM, "termination␣request"),
#ifdef SIGKILL
SH_PAIR(SIGKILL, "kill␣signal"),
#endif
#ifdef SIGQUIT
SH_PAIR(SIGQUIT, "keyboard␣quit"),
#endif
#ifdef SIGSTOP
SH_PAIR(SIGSTOP, "stop␣process"),
#endif
#ifdef SIGCONT
SH_PAIR(SIGCONT, "continue␣if␣stopped"),
#endif
#ifdef SIGINFO
SH_PAIR(SIGINFO, "status␣information␣request"),
#endif
};
size_t const sh_known = (sizeof sh_pairs / sizeof sh_pairs[0]);
#if ATOMIC_LONG_LOCK_FREE > 1
/* @brief Keep track of the number of calls into a
* signal handler for each possible signal.
Don’t use this array directly.
@see sh_count to update this information.
@see SH_PRINT to use that information.
*/
extern unsigned long _Atomic sh_counts[];
/*
* @brief Use this in your signal handler to keep track of the
* number of calls to the signal @a sig.
*
* @see sh_counted to use that information.
*/
inline void sh_count(int sig) {
if (sig < sh_known)
++sh_counts[sig];
}
inline unsigned long sh_counted(int sig) {
return (sig < sh_known) ? sh_counts[sig] : 0;
}
#else
inline void sh_count(int sig) {
(void)sig;
// empty
}
inline unsigned long sh_counted(int sig) {
(void)sig;
return 0;
}
#endif
/*
* @ brief Enable a signal handler and catch the errors.
*/
sh_handler *sh_enable(int sig, sh_handler *hnd) {
sh_handler *ret = signal(sig, hnd);
if (ret == SIG_ERR) {
SH_PRINT(stderr, sig, "failed");
errno = 0;
} else if (ret == SIG_IGN) {
SH_PRINT(stderr, sig, "previously␣ignored");
} else if (ret && ret != SIG_DFL) {
SH_PRINT(stderr, sig, "previously␣set␣otherwise");
} else {
SH_PRINT(stderr, sig, "ok");
}
return ret;
}
/*
* @brief a minimal signal handler
*
* After updating the signal count, for most signals this simply stores the
* signal value in "interrupt" and returns.
*/
static void signal_handler(int sig) {
sh_count(sig);
switch (sig) {
case SIGTERM:
quick_exit(EXIT_FAILURE);
case SIGABRT:
_Exit(EXIT_FAILURE);
#ifdef SIGCONT
// continue normal operation
case SIGCONT:
return;
#endif default:
/* reset the handling to its default */
signal(sig, SIG_DFL);
interrupt = sig;
return;
}
}
char const *skipspace(char const *str) {
while (str[0] == ' ')
str++;
return str;
}
/* end_line prints a new line in the stdout and consumes the heading
* spaces of the input string.
*/
char const *end_line(char const *s, jmp_buf jmpTarget) {
if (putchar('\n') == EOF) {
longjmp(jmpTarget, eofOut);
}
return skipspace(s);
}
/*
* Rule 3.18.4.2 When reached through normal control flow, a call to setjmp
* marks the call location as a jump target and returns 0.
*
* Rule 3.18.4.3 Leaving the scope of a call to setjmp invalidates the jump
* target.
*
* Rule 3.18.4.4 A call to longjmp transfers control directly to the position
* that was set by setjmp as if that had returned the condition argument.
*
* Rule 3.18.4.5 A 0 as condition parameter to longjmp is replaced by 1.
*
* Rule 3.18.4.6 setjmp may only be used in simple comparisons inside
* controlling expression of conditionals.
*
* Rule 3.18.4.7 Optimization interacts badly with calls to setjmp.
*
* Rule 3.18.4.8 Objects that are modified across longjmp must be volatile.
*
* Rule 3.18.4.9 volatile objects are reloaded from memory each time they are
* accessed.
*
* Rule 3.18.4.10 volatile objects are stored to memory each time they are
* modified.
*
* (So volatile objects are protected from optimization, or, if we look at it
* negatively, they inhibit optimization).
*
* Rule 3.18.4.11 The typedef for jmp_buf hides an array type.
*/
/* In descend we use just one jump target of type jmp_buf, that we declare as a
* local variable. This jump target is setup in the base function basic_blocks
* that serves as interface to descend
*/
int empty(char const *act) { return (!act || !act[0]); }
/* blocking optimisation of `dp` with `volatile dp` instead of
* unsigned dp[restrict static 1]
*/
static char const *descend(char const *act,
unsigned volatile dp[restrict static 1], size_t len,
char buffer[len], jmp_buf jmpTarget) {
if (empty(act)) {
printf("ready to start\n");
} else {
printf("ACT: %s\n", act);
DEBUG_PRINTF(("descending into %s\n", act));
}
/* if the depth is greater than the head, we don't have enough space to
* print the content and we jump out with a tooDeep condition.
*/
if (dp[0] + 3 > sizeof head) {
DEBUG_PRINTF("jumping out (tooDeep)");
longjmp(jmpTarget, tooDeep);
}
/* we increase the depth by one */
++dp[0];
/* NEW_LINE is jump target when a new line is to be printed */
NEW_LINE:
DEBUG_PRINTF("loop on output\n");
while (empty(act)) {
DEBUG_PRINTF("loop for input\n");
if (interrupt) {
longjmp(jmpTarget, interrupted);
}
act = skipspace(fgets(buffer, len, stdin));
if (!act) {
DEBUG_PRINTF("end of stream\n");
if (dp[0] != 1) {
longjmp(jmpTarget, plusL);
} else
goto ASCEND;
}
}
DEBUG_PRINTF("writing the header\n");
fputs(&head[sizeof head - (dp[0] + 2)], stdout);
DEBUG_PRINTF("remainder of the line\n");
for (; act && act[0]; ++act) {
DEBUG_PRINTF(("act[0]: %c\n", act[0]));
switch (act[0]) {
case LEFT:
DEBUG_PRINTF(("CURRENT char (%c) NEXT char (%c)\n", act[0], act[1]));
/* descend on left brace
* consume the open parenthesis (LEFT) with the `act + 1`, then
* add a new line and remove the heading spaces
*/
act = end_line(act + 1, jmpTarget);
/*
* descend, recursively, will return a processed input
*/
act = descend(act, dp, len, buffer, jmpTarget);
/* we return here, from the RIGHT case, consuming the closing brace,
* (RIGHT: }) that is now at act[0], add a new line and remove the
* heading spaces.
*/
printf("RETURNING in LEFT with ACT: %s\n", act);
act = end_line(act + 1, jmpTarget);
goto NEW_LINE;
case RIGHT:
/* return on right brace */
if (dp[0] == 1)
longjmp(jmpTarget, plusR);
else
goto ASCEND;
default:
/* print char and continue process the input */
puts(" ==> ");
putchar(act[0]);
}
}
goto NEW_LINE;
ASCEND:
/* ASCEND is used if a } is encountered or if the stream ended. */
/* decreasing the depth */
--dp[0];
return act;
}
void basic_blocks(void) {
int maxline = 80;
char buffer[maxline];
unsigned volatile depth = 0;
char const *format = "All %0.0d%c %c blocks have been closed correctly\n";
jmp_buf jmpTarget;
switch (setjmp(jmpTarget)) {
case 0:
descend(0, &depth, maxline, buffer, jmpTarget);
break;
case plusL:
format = "Warning: %d %c %c blocks have not been closed properly\n ";
break;
case plusR:
format = "Error: closing too many (%d) %c %c blocks\n";
break;
case tooDeep:
format = "Error: nesting (%d) of %c %c blocks is too deep\n";
break;
case eofOut:
format = "Error: EOF for stdout at nesting (%d) of %c %c blocks\n";
break;
case interrupted:
format = "Interrupted at level %d of %c %c block nesting\n";
break;
default:;
format = "Error: unknown error within (%d) %c %c blocks\n";
}
fflush(stdout);
fprintf(stderr, format, depth, LEFT, RIGHT);
if (interrupt) {
fprintf(stderr, "is somebody trying to kill us?");
raise(interrupt);
}
}
/*
* [Exs 24]: Change descend such that it receives an unsigned depth instead of a
* pointer.
* [Exs 25]: Compare the assembler output of the initial version against
* your version without dp pointer.
* [Exs 27]: Your version of descend that passes depth as value, might not
* propagate the depth correctly if it encounters the plusL condition. Ensure
* that it copies that value to an object that can be used in by the fprintf
* call in basic_blocks.
*/
int main(void) {
/* establish signal handlers */
for (unsigned i = 1; i < sh_known; ++i)
sh_enable(i, signal_handler);
size_t size = 11;
head = malloc(sizeof(char) * size);
/*
* memset -- fill a byte string with a byte value
* void *memset(void *b, int c, size_t len);
* The memset() function writes len bytes of value c (converted to an unsigned
* char) to the string b.
*/
memset(head, '.', size);
head[size] = '\0';
head = "0123456789";
printf("HEAD (%lu) is now: --[ %s ]--\n", strlen(head), head);
basic_blocks();
free(head);
return 0;
}
<file_sep>#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
struct p {
unsigned char *s;
struct p *p;
};
int c_count(char *s, char c) {
int count = 0;
while (*s)
if (*(s++) == c)
count++;
return count;
}
int part_01(void) {
FILE *input;
input = fopen("./input.txt", "r");
size_t len = 32;
char *line = malloc(len);
ssize_t read;
char c;
int have2, n2 = 0;
int have3, n3 = 0;
int cm;
while ((read = getline(&line, &len, input)) != -1) {
have2 = 0;
have3 = 0;
for (c = 'a'; c <= 'z'; c++) {
cm = c_count(line, c);
if (cm >= 3)
have3 = 1;
else if (cm == 2)
have2 = 1;
}
if (have2)
n2++;
if (have3)
n3++;
}
if (ferror(stdin))
err(1, "fgets");
return n2 * n3;
}
int main() { printf("part 01: %02d\n", part_01()); }
<file_sep>#include <stdio.h>
#include <string.h>
#include <time.h>
// http://en.cppreference.com/w/c
// http://en.cppreference.com/w/c/chrono/strftime
// http://en.cppreference.com/w/c/chrono/gmtime
// size_t strftime( char * str, size_t count, const char * format, const struct
// tm * time );
void date_tag(char *buffer, int buffersize) {
time_t timer;
struct tm *tm_info;
time(&timer);
tm_info = gmtime(&timer);
strftime(buffer, buffersize, "%Y%m%d%H%M%S", tm_info);
buffer[buffersize - 1] = '\0';
}
int main(void) {
char other[15];
date_tag(other, sizeof(other));
printf("datetag: %s (%lu)(%lu)\n", other, strlen(other), sizeof(other));
return 0;
}
<file_sep>/* difftime example */
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h> /* printf */
#include <stdlib.h>
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
#define TYPE_SIGNED(type) ((type)-1 < 0)
/*
Original difftime:
http://sourceware.org/git/?p=glibc.git;a=summary
http://sourceware.org/git/?p=glibc.git;a=tree;f=time;hb=HEAD
http://sourceware.org/git/?p=glibc.git;a=blob;f=time/difftime.c;h=7c5dd9898b8b52adca956cbd0b7e4e4b46e41413;hb=HEAD
Usage:
http://www.cplusplus.com/reference/ctime/difftime/
difftime
double difftime (time_t end, time_t beginning);
Return difference between two times
Calculates the difference in seconds between beginning and end.
*/
/*
struct timespec {
time_t tv_sec; // whole seconds
long tv_nsec; // nanoseconds
};
*/
/*
- Exs 33: Write a function timespec_diff that computes the difference
between two timespec values.
*/
static double simple_subtract(time_t time1, time_t time0) {
if (!TYPE_SIGNED(time_t))
return time1 - time0;
else
exit(EXIT_FAILURE);
}
/* Return the difference between TIME1 and TIME0. */
double simple_difftime(time_t time1, time_t time0) {
/* Subtract the smaller integer from the larger, convert the difference to
double, and then negate if needed. */
return time1 < time0 ? -simple_subtract(time0, time1)
: simple_subtract(time1, time0);
}
// int main(int argc, char *argv[]) {
int main(void) {
time_t now;
struct tm newyear;
double seconds;
time(&now); /* get current time; same as: now = time(NULL) */
newyear = *localtime(&now);
newyear.tm_hour = 0;
newyear.tm_min = 0;
newyear.tm_sec = 0;
newyear.tm_mon = 0;
newyear.tm_mday = 1;
seconds = difftime(now, mktime(&newyear));
printf("%.f seconds since new year in the current timezone.\n", seconds);
seconds = simple_difftime(now, mktime(&newyear));
printf("%.f seconds since new year in the current timezone.\n", seconds);
return 0;
}
<file_sep>#include "grains.h"
/* https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem
*
* #include <math.h>
* uint64_t square(uint64_t n) { return pow(2, n - 1); }
*
* using the math library
* uint64_t total(void) { return (uint64_t)(pow(2, BOARD) - 1); }
*
* bruteforcing the total
* T_{64}=2^{0}+2^{1}+2^{2}+\cdots +2^{63}
* T_{64} = 2^{64} - 1
* uint64_t total() {
* int sum = 0;
* for (int i = 0; i < 64; i++) {
* sum += square(i);
* }
* return sum;
* }
*
*/
uint64_t square(int n) {
/* clang-format off */
if (!n) return 0;
if (n > 64) return 0;
return 1ul << (n - 1);
/* clang-format on */
}
uint64_t total() { return -1; }
<file_sep>/* This may look like nonsense , but really is
-*- mode : C -*-
*/
/*
Exs 1.3
*/
/*
Exs 1.4
*/
/*
Exs 1.5
*/
#include <stdio.h>
/* The main thing that this program does . */
int main() {
// Declarations
int i;
double A[5] = {
9.0, 2.9, 3.E+25, .00007,
};
// Doing some work
for (i = 0; i < 5; ++i) {
printf("element %d is %g, \t its square is %g\n", i, A[i], A[i] * A[i]);
}
return 0;
}
<file_sep>SHELL := /bin/bash
COMPILER = gcc
TARGET = aoc
SOURCE = empty
BASE_FLAGS = -Wall -std=c11 -g
OPTM_FLAGS = -O3
# CURL_FLAGS = $(shell pkg-config --cflags --libs libcurl)
# PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl tidy gumbo)
# LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
# SDL2_FLAGS = -lSDL2 -lSDL2_mixer -lSDL2_ttf
# NCUR_FLAGS = -lncurses
# MATH_FLAGS = -lm
BULD_FLAGS = ${BASE_FLAGS} ${OPTM_FLAGS}
# TEST_FLAGS = ${BASE_FLAGS} -Og -lcmocka -DTEST=1 -DDEBUG=1
# Obtains the OS type, either 'Darwin' (OS X) or 'Linux'
UNAME_S:=$(shell uname -s)
.PHONY: build
build:
@echo "Building ${SOURCE}.c into ${TARGET}"
${COMPILER} ${BULD_FLAGS} -o ${TARGET} ${SOURCE}.c
<file_sep>#ifndef TRIANGLE_H
#define TRIANGLE_H
typedef struct {
double a;
double b;
double c;
} triangle_t;
int is_equilateral(triangle_t sides);
int is_isosceles(triangle_t sides);
int is_scalene(triangle_t sides);
#endif
<file_sep>##
# GNU GCC Option Summary
#
# https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html
# https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
#
# -std= Determine the language standard. See Language Standards
# Supported by GCC, for details of these standard versions. This option
# is currently only supported when compiling C or C++.
# c11, c1x, iso9899:2011, ISO C11, the 2011 revision of the ISO C
# standard. This standard is substantially completely supported,
# modulo bugs, floating-point issues (mainly but not entirely
# relating to optional C11 features from Annexes F and G) and the
# optional Annexes K (Bounds-checking interfaces) and L
# (Analyzability). The name ‘c1x’ is deprecated.
#
# https://gcc.gnu.org/onlinedocs/gcc/Standards.html#Standards
#
#
# https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#Debugging-Options
#
# -g : Produce debugging information in the operating system’s native
# format (stabs, COFF, XCOFF, or DWARF). GDB can work with this
# debugging information.
#
# https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Optimize-Options
#
# -O0
# Reduce compilation time and make debugging produce the expected
# results. This is the default.
# -O3
# Optimize yet more. -O3 turns on all optimizations
# -Og
# Optimize debugging experience. -Og enables optimizations that do not
# interfere with debugging. It should be the optimization level of
# choice for the standard edit-compile-debug cycle, offering a
# reasonable level of optimization while maintaining fast compilation
# and a good debugging experience.
# Most optimizations are only enabled if an -O level is set on the command
# line. Otherwise they are disabled, even if individual optimization flags
# are specified.
#
# Depending on the target and how GCC was configured, a slightly different
# set of optimizations may be enabled at each -O level than those listed
# here. You can invoke GCC with -Q --help=optimizers to find out the exact
# set of optimizations that are enabled at each level. See Overall
# Options, for examples.
#
# -O
# -O1
# Optimize. Optimizing compilation takes somewhat more time, and a lot
# more memory for a large function.
#
# With -O, the compiler tries to reduce code size and execution time,
# without performing any optimizations that take a great deal of
# compilation time.
#
# -O turns on the following optimization flags:
#
# -fauto-inc-dec
# -fbranch-count-reg
# -fcombine-stack-adjustments
# -fcompare-elim
# -fcprop-registers
# -fdce
# -fdefer-pop
# -fdelayed-branch
# -fdse
# -fforward-propagate
# -fguess-branch-probability
# -fif-conversion2
# -fif-conversion
# -finline-functions-called-once
# -fipa-pure-const
# -fipa-profile
# -fipa-reference
# -fmerge-constants
# -fmove-loop-invariants
# -fomit-frame-pointer
# -freorder-blocks
# -fshrink-wrap
# -fshrink-wrap-separate
# -fsplit-wide-types
# -fssa-backprop
# -fssa-phiopt
# -ftree-bit-ccp
# -ftree-ccp
# -ftree-ch
# -ftree-coalesce-vars
# -ftree-copy-prop
# -ftree-dce
# -ftree-dominator-opts
# -ftree-dse
# -ftree-forwprop
# -ftree-fre
# -ftree-phiprop
# -ftree-sink
# -ftree-slsr
# -ftree-sra
# -ftree-pta
# -ftree-ter
# -funit-at-a-time
#
# -O2
# Optimize even more. GCC performs nearly all supported optimizations that
# do not involve a space-speed tradeoff. As compared to -O, this option
# increases both compilation time and the performance of the generated
# code.
#
# -O2 turns on all optimization flags specified by -O. It also turns on
# the following optimization flags:
#
# -fthread-jumps
# -falign-functions -falign-jumps
# -falign-loops -falign-labels
# -fcaller-saves
# -fcrossjumping
# -fcse-follow-jumps -fcse-skip-blocks
# -fdelete-null-pointer-checks
# -fdevirtualize -fdevirtualize-speculatively
# -fexpensive-optimizations
# -fgcse -fgcse-lm
# -fhoist-adjacent-loads
# -finline-small-functions
# -findirect-inlining
# -fipa-cp
# -fipa-bit-cp
# -fipa-vrp
# -fipa-sra
# -fipa-icf
# -fisolate-erroneous-paths-dereference
# -flra-remat
# -foptimize-sibling-calls
# -foptimize-strlen
# -fpartial-inlining
# -fpeephole2
# -freorder-blocks-algorithm=stc
# -freorder-blocks-and-partition -freorder-functions
# -frerun-cse-after-loop
# -fsched-interblock -fsched-spec
# -fschedule-insns -fschedule-insns2
# -fstore-merging
# -fstrict-aliasing
# -ftree-builtin-call-dce
# -ftree-switch-conversion -ftree-tail-merge
# -fcode-hoisting
# -ftree-pre
# -ftree-vrp
# -fipa-ra
#
# Please note the warning under -fgcse about invoking -O2 on programs that
# use computed gotos.
#
# -O3
# Optimize yet more. -O3 turns on all optimizations specified by -O2 and
# also turns on the following optimization flags:
#
# -finline-functions
# -funswitch-loops
# -fpredictive-commoning
# -fgcse-after-reload
# -ftree-loop-vectorize
# -ftree-loop-distribution
# -ftree-loop-distribute-patterns
# -floop-interchange
# -floop-unroll-and-jam
# -fsplit-paths
# -ftree-slp-vectorize
# -fvect-cost-model
# -ftree-partial-pre
# -fpeel-loops
# -fipa-cp-clone
#
# -O0
# Reduce compilation time and make debugging produce the expected
# results. This is the default.
#
# -Os
# Optimize for size. -Os enables all -O2 optimizations that do not
# typically increase code size. It also performs further optimizations
# designed to reduce code size.
#
# -Os disables the following optimization flags:
#
# -falign-functions -falign-jumps -falign-loops
# -falign-labels -freorder-blocks -freorder-blocks-algorithm=stc
# -freorder-blocks-and-partition -fprefetch-loop-arrays
# -Ofast
# Disregard strict standards compliance. -Ofast enables all -O3
# optimizations. It also enables optimizations that are not valid for all
# standard-compliant programs. It turns on -ffast-math and the
# Fortran-specific -fstack-arrays, unless -fmax-stack-var-size is
# specified, and -fno-protect-parens.
#
# -Og
# Optimize debugging experience. -Og enables optimizations that do not
# interfere with debugging. It should be the optimization level of choice
# for the standard edit-compile-debug cycle, offering a reasonable level
# of optimization while maintaining fast compilation and a good debugging
# experience.
#
# If you use multiple -O options, with or without level numbers, the last
# such option is the one that is effective.
# I do have to link to <math.h>, using -lm with gcc
# The functions in stdlib.h and stdio.h have implementations in libc.so
# (or libc.a for static linking), which is linked into your executable
# by default (as if -lc were specified). GCC can be instructed to avoid
# this automatic link with the -nostdlib or -nodefaultlibs options.
#
# The math functions in math.h have implementations in libm.so (or
# libm.a for static linking), and libm is not linked in by
# default. There are historical reasons for this libm/libc split, none
# of them very convincing.
SHELL := /bin/bash
COMPILER = gcc
TARGET = pebbles
SOURCE = empty
# Using The shell Function:
# http://www.gnu.org/software/make/manual/html_node/Shell-Function.html
# and the lib helpers, we have
#
# -I/usr/local/Cellar/tidy-html5/5.6.0/include
# -I/usr/local/Cellar/gumbo-parser/0.10.1/include
# -L/usr/local/Cellar/tidy-html5/5.6.0/lib
# -L/usr/local/Cellar/gumbo-parser/0.10.1/lib
# -lcurl -ltidy -lgumbo
BASE_FLAGS = -Wall -std=c11 -g
OPTM_FLAGS = -O3
CURL_FLAGS = $(shell pkg-config --cflags --libs libcurl)
PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl tidy gumbo)
LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
SDL2_FLAGS = -lSDL2 -lSDL2_mixer -lSDL2_ttf
NCUR_FLAGS = -lncurses
MATH_FLAGS = -lm
BULD_FLAGS = ${BASE_FLAGS} ${OPTM_FLAGS} ${MATH_FLAGS} ${NCUR_FLAGS} ${PKGC_FLAGS} ${LXML_FLAGS}
TEST_FLAGS = ${BASE_FLAGS} -Og -lcmocka -DTEST=1 -DDEBUG=1
# Obtains the OS type, either 'Darwin' (OS X) or 'Linux'
UNAME_S:=$(shell uname -s)
.PHONY: help
help:
@echo "** Pebbles **"
@echo "Options are:"
@echo "- help (this message)"
@echo "- build (just compile)"
@echo "- buildtest (compile with test feature)"
@echo "- builddebug (compile with test and debug)"
@echo "- test (build and run with the test feature)"
@echo "- debug (build and run with the test and debug feature)"
@echo "- run (run the executable)"
@echo "- clean (remove the executable)"
.PHONY: build
build:
@echo "Building ${SOURCE}.c into ${TARGET}"
${COMPILER} ${BULD_FLAGS} -o ${TARGET} ${SOURCE}.c
.PHONY: builddebug
builddebug:
@echo "Building ${SOURCE}.c with feature TEST=1 DEBUG=1 into ${TARGET}"
${COMPILER} ${TEST_FLAGS} -o ${TARGET} ${SOURCE}.c
.PHONY: buildtest
buildtest:
@echo "Building ${SOURCE}.c with feature TEST=1 into ${TARGET}"
${COMPILER} ${TEST_FLAGS} -o ${TARGET} ${SOURCE}.c
.PHONY: debug
debug: buildebug run
.PHONY: test
test: buildtest run clean
.PHONY: addressbok
addressbook:
@echo "Building addressbook.c into ${TARGET}"
${COMPILER} ${BULD_FLAGS} -o ${TARGET} addressbook.c
./${TARGET}
# make bolder ARGS=empty.c
.PHONY: bolder
bolder:
@echo "Building bolder.c into ${TARGET}"
${COMPILER} ${BULD_FLAGS} -o ${TARGET} bolder.c
./${TARGET} ${ARGS}
.PHONY: snail
snail:
@echo "Building snail.c into ${TARGET}"
${COMPILER} ${BASE_FLAGS} ${OPTM_FLAGS} ${NCUR_FLAGS} ${CURL_FLAGS} ${LXML_FLAGS} -o snail snail.c
.PHONY: loomp3
loomp3:
@echo "building loomp3.c into loomp3"
${COMPILER} ${BASE_FLAGS} ${OPTM_FLAGS} ${SDL2_FLAGS} -o loomp3 loomp3.c
.PHONY: run
run:
@echo "Running ${TARGET} build from ${SOURCE}.c"
./${TARGET} ${ARGS}
.PHONY: build_and_run
build_and_run: build run
.PHONY: clean
clean:
@echo "Cleaning up ${TARGET}"
rm ./${TARGET}
rm -rf ./${TARGET}.*
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#define CORVID_NAME /* */ \
(char const *const[corvid_num]) { \
[chough] = " chough ", [raven] = " raven ", [magpie] = " magpie ", \
[jay] = " jay ", \
}
int main(void) {
enum corvid {
magpie,
raven,
jay,
corvid_num,
};
char const *const animal[corvid_num] = {
[raven] = " raven ", [magpie] = " magpie ", [jay] = " jay ",
};
for (unsigned i = 0; i < corvid_num; ++i)
printf(" Corvid %u is the %s\n", i, animal[i]);
signed const o42 = 42;
enum {
b42 = 42,
// ok , 42 is a literal
c52 = o42 + 10, // error , o42 is an object
b52 = b42 + 10, // ok , b42 is not an object
};
return EXIT_SUCCESS;
}
<file_sep>#include "difference_of_squares.h"
int square_of_sum(int n) {
int x = n * (n + 1) >> 1;
return x * x;
}
int sum_of_squares(int n) {
return n * (n + 1) * (2 * n + 1) / 6;
}
int difference_of_squares(int n) {
return square_of_sum(n) - sum_of_squares(n);
}
<file_sep>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
* https://stackoverflow.com/a/822368
*
* srand(time(NULL)); // should only be called once
* int r = rand(); // returns a pseudo-random integer between 0 and RAND_MAX
*
* +1 for simplicity, but it is probably a good idea to emphasize that srand()
* should only be called once. Also, in a threaded application, you might want
* to make sure that the generator's state is stored per thread, and seed the
* generator once for each thread.
* its complicated. Here's a reason: time() only changes once per
* second. If you seed from time(), for each call to rand(), then you
* will get the same value for every call during a single second. But
* the bigger reason is that the properties of rand() and functions like
* it are known best for the use case where they are seeded exactly once
* per run, and not on every single call. Depending on "randomness" with
* untested or unproven properties leads to trouble.
*
* https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626
* https://stackoverflow.com/a/39475626
*/
/* config */
typedef struct t_config config;
struct t_config {
double min_x;
double min_y;
double max_x;
double max_y;
};
/* point */
typedef struct t_point point;
struct t_point {
double x;
double y;
};
/* list_element */
typedef struct t_list_element list_element;
struct t_list_element {
point p;
list_element *next;
};
int rand_int() {
int r = rand(); // returns a pseudo-random integer between 0 and RAND_MAX
return r;
}
double randomDouble(double min, double max) {
return min + (double)rand_int() / ((double)RAND_MAX / (max - min));
}
point random_point(config c) {
double px = randomDouble(c.min_x, c.max_x);
double py = randomDouble(c.min_y, c.max_y);
point p = {.x = px, .y = py};
return p;
}
point randomDirection() {
double angle = randomDouble(0, 2 * 3.14159);
point p = {.x = sin(angle), .y = cos(angle)};
return p;
}
void pretty_print_point(point *p) {
/* safe printing */
char *buf;
size_t sz;
sz = snprintf(NULL, 0, "point [%f, %f]", p->x, p->y);
buf = (char *)malloc(sz + 1);
if (buf == NULL) {
printf("cannot allocate memory for output\n");
exit(EXIT_FAILURE);
}
snprintf(buf, sz + 1, "point [%f, %f]", p->x, p->y);
printf("%s\n", buf);
}
int main(void) {
srand((unsigned int)time(NULL));
/*
* list_element el = {.p = {.x = 3, .y = 7}};
* list_element le = {.p = {.x = 4, .y = 5}, .next = &el};
*/
config c = { .max_x = 1.0, .min_x = 0.0, .max_y = 1.0, .min_y = 0.0 };
point p = random_point(c);
pretty_print_point(&p);
}
<file_sep>#ifndef DIFFERENCE_OF_SQUARES_H
#define DIFFERENCE_OF_SQUARES_H
int square_of_sum(int);
int sum_of_squares(int);
int difference_of_squares(int);
#endif
<file_sep>/*
* noahhaasis/elementary_automaton
*
* https://github.com/noahhaasis/elementary_automaton
* https://github.com/noahhaasis/elementary_automaton/blob/master/automaton.c
* https://raw.githubusercontent.com/noahhaasis/elementary_automaton/master/automaton.c
*/
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DEFAULT_WIDTH 80
typedef unsigned char byte;
void display(bool generation[], int size);
void evolve(bool generation[], int size, int rule);
/* Convert an array of booleans or bits into a decimal number,
* where the rightmost bit is the least significant (big-endian)
*/
int bool_to_num(bool bits[], int size);
bool new_state(bool *neighbours, byte rule);
void sleep(int ms);
int main(int argc, char **argv) {
int rule;
int width = DEFAULT_WIDTH;
if (argc != 2 && argc != 3) {
fprintf(stderr, "Usage: ./automaton rule [width]\n");
return -1;
}
rule = atoi(argv[1]);
assert(rule <= 0 && rule <= 255);
if (argc == 3)
width = atoi(argv[2]);
bool current_generation[width];
memset(current_generation, 0, width);
current_generation[width / 2] = true;
for (;;) {
display(current_generation, width);
evolve(current_generation, width, rule);
sleep(500);
}
return 0;
}
int bool_to_num(bool bits[], int size) {
int res = 0;
for (int i = 0; i < size; i++) {
res |= bits[i] << (size - (i + 1));
}
return res;
}
bool new_state(bool *neighbours, byte rule) {
return rule & 1 << bool_to_num(neighbours, 3);
}
void display(bool generation[], int size) {
for (int i = 0; i < size; i++) {
putchar(generation[i] ? '#' : ' ');
}
putchar('\n');
}
void evolve(bool generation[], int size, int rule) {
bool new_generation[size];
bool *neighbours;
for (int i = 0; i < size; i++) {
if (i == 0)
neighbours = (bool[]){false, generation[i], generation[i + 1]};
else if (i == size - 1)
neighbours = (bool[]){generation[i - 1], generation[i], false};
else
neighbours = &generation[i - 1];
new_generation[i] = new_state(neighbours, rule);
}
memcpy(generation, new_generation,
size); // TODO: Make this a bit more efficient later
}
void sleep(int ms) {
clock_t delta = 0, delta_in_ms = 0;
clock_t start_time = clock();
assert(start_time != -1);
while (delta_in_ms < ms) {
delta = clock() - start_time;
delta_in_ms = (delta / CLOCKS_PER_SEC) * 1000;
}
}
<file_sep>#include "gigasecond.h"
time_t gigasecond_after(time_t t) {
/* #include <time.h>
* struct tm *gmtime(const time_t *clock);
*
* The functions ctime(), gmtime(), and localtime() all take as an
* argument a time value represent- ing the time in seconds since the
* Epoch (00:00:00 UTC, January 1, 1970; see time(3)). When
* encountering an error, these functions return NULL and set errno
* to an appropriate value.
*
* The function gmtime() also converts the time value, but makes no
* time zone adjustment. It returns a pointer to a tm structure
* (described below).
*
* The tm structure includes at least the following fields:
*
* int tm_sec; // seconds (0 - 60)
* int tm_min; // minutes (0 - 59)
* int tm_hour; // hours (0 - 23)
* int tm_mday; // day of month (1 - 31)
* int tm_mon; // month of year (0 - 11)
* int tm_year; // year - 1900
* int tm_wday; // day of week (Sunday = 0)
* int tm_yday; // day of year (0 - 365)
* int tm_isdst; // is summer time in effect?
* char *tm_zone; // abbreviation of timezone name
* long tm_gmtoff; // offset from UTC in seconds
*/
struct tm *date = gmtime(&t);
date->tm_sec += 40;
if (date->tm_sec > 59) {
date->tm_sec = date->tm_sec % 60;
date->tm_min++;
}
date->tm_min += 46;
if (date->tm_min > 59) {
date->tm_min = date->tm_min % 60;
date->tm_hour++;
}
date->tm_hour += 1;
if (date->tm_hour > 59) {
date->tm_hour = date->tm_hour % 60;
date->tm_mday++;
}
/* 1,000,000,000 seconds = 11574.07 days
* 0.074 days = 1.776 hours
* 0.776 hours = 46.56 Minutes
*/
date->tm_mday += 11574;
return timegm(date);
}
<file_sep>#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int part_01(void) {
int frequency = 0;
FILE *input;
input = fopen("./input.txt", "r");
char line[100];
while (fgets(line, 100, input)) {
int num = atoi(line);
frequency += num;
}
fclose(input);
return frequency;
}
int part_02() {
int frequency = 0;
unsigned byte, bit;
char *bitfield;
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("input.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
if (!(bitfield = calloc(UINT_MAX / 8, 1)))
err(1, "calloc");
bitfield[0] = 1;
while (1) {
read = getline(&line, &len, fp);
if (read == -1) {
rewind(fp);
read = getline(&line, &len, fp);
}
int n = atoi(line);
frequency += n;
byte = (unsigned)frequency / 8;
bit = 1 << ((unsigned)frequency % 8);
if (bitfield[byte] & bit) {
free(bitfield);
fclose(fp);
return frequency;
}
bitfield[byte] = bitfield[byte] | bit;
}
free(bitfield);
fclose(fp);
return 0;
}
int main(void) {
/* for inspection
* FILE *fp;
* char *line = NULL;
* size_t len = 0;
* ssize_t read;
* fp = fopen("input.txt", "r");
* if (fp == NULL)
* exit(EXIT_FAILURE);
*
* while ((read = getline(&line, &len, fp)) != -1) {
* printf("Retrieved line of length %zu:\n", read);
* printf("%s", line);
* }
*
* fclose(fp);
* if (line)
* free(line);
*/
printf("part 01: %d\n", part_01());
printf("part 02: %d\n", part_02());
exit(EXIT_SUCCESS);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include "nearly.h"
#include <cmocka.h>
#import <stdarg.h>
/*
* void va_start(va_list ap, parmN);
* void va_end(va_list ap);
* type va_arg(va_list ap, type);
* void va_copy(va_list dest, va_list src);
*/
/*
* Rule 3.17.3.3
* Stringification with operator # does not expand macros in its argument.
*
* has a special macro __LINE__ that always expands to a decimal integer
* constant for the number of the actual line in the source.
*
* Rule 3.17.3.1
* The line number in __LINE__ may not fit into an int.
*
* Rule 3.17.3.2
* Using __LINE__ is inherently dangerous.
*
* In our macros we avoid the problem by either fixing the type to unsigned
* long (Hoping that no source will have more than 4 billion lines) or by
* transforming the number to a string during compilation.
* If such a # appears before a macro parameter in the expansion, the actual
* argument to this parameter is stringified that is all its textual content
* is placed into a string literal.
*
* TRACE_PRINT5("my␣favorite␣variable:␣%g", sum);
* #define TPRINT(F, X) do { \
* fprintf(stderr, "%s:" STRGY(__LINE__) ":(" #X "):" F "\n",__func__ , X); \
* } while (false)
* Output: main:25:(sum): my favorite variable: 889
*
* Rule 3.17.3.3
* Stringification with operator # does not expand macros in its argument.
*
* In view of the potential problems with __LINE__ mentioned above, we
* also would like to convert the line number directly into a string.
* This has a double advantage: it avoids the type problem and
* stringification is done entirely at compile time.
* As said, the # operator only applies to macro arguments, so a simple
* use as `#__LINE__` does not have the desired effect. Now consider the
* following macro definition:
*
* #define STRINGIFY(X) #X
*
* Stringification kicks in before argument replacement, and the
* result of STRINGIFY( __LINE__) is "__LINE__", the macro __LINE__ is
* not expanded. So this macro still is not sufficient for our need.
*
* #define STRGY(X) STRINGIFY(X)
*
* Now, STRGY(__LINE__) first expands to STRINGIFY(25) (if we are
* on line 25), this then expands to "25", the stringified line number.
*/
#define STRINGIFY(X) #X
#define STRGY(X) STRINGIFY(X)
/** @brief Trace with or without values.
**
** This implementation has the particularity of adding a format
** @c "%.0d" to skip the last element of the list which was
** artificially added.
**/
#define TRACE_PRINT8(...) \
\ TRACE_PRINT6(TRACE_FIRST(__VA_ARGS__) "%.0d", TRACE_LAST(__VA_ARGS__))
/**
** @brief Extract the first argument from a list of arguments.
**/
#define TRACE_FIRST(...) TRACE_FIRST0(__VA_ARGS__, 0)
#define TRACE_FIRST0(_0, ...) _0
/** @brief Remove the first argument from a list of arguments.
**
** @remark This is only suitable in our context,
** since this adds an artificial last argument.
**/
#define TRACE_LAST(...) TRACE_LAST0(__VA_ARGS__, 0)
#define TRACE_LAST0(_0, ...) __VA_ARGS__
/**
** @brief Return the number of arguments in the ... list.
** This version works for lists with up to 31 elements.
** @remark An empty argument list is taken as one (empty) argument.
**/
#define ALEN(...) \
ALEN0(__VA_ARGS__, 0x1E, 0x1F, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18, 0x17, \
0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x0E, 0x0F, 0x0D, 0x0C, \
0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, \
0x00)
#define ALEN0(_00, _01, _02, _03, _04, _05, _06, _07, _08, _09, _0A, _0B, _0C, \
_0D, _0F, _0E, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, \
_1A, _1B, _1C, _1D, _1F, _1E, ...) \
_1E
/**
** @brief Print to the debug stream @c iodebug
**/
FILE *iodebug = 0;
#ifdef __GNUC__
/* https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html */
__attribute__((format(printf, 1, 2)))
#endif
int printf_debug(const char *format, ...) {
int ret = 0;
if (iodebug) {
va_list va;
va_start(va, format);
ret = vfprintf(iodebug, format, va);
va_end(va);
}
return ret;
}
/**
** @brief A small, useless function to show how variadic functions
** work.
**/
double sum_it(size_t n, ...) {
double ret = 0.0;
va_list va;
va_start(va, n);
for (size_t i = 0; i < n; ++i) {
/*
* double d = va_arg(va, double);
* printf("double %f\n", d);
*/
ret += va_arg(va, double);
}
va_end(va);
return ret;
}
/*
* Exercises
*
* - [Exs 00]: Variadic functions that only receive arguments of all the same
* type, can be replaced by a variadic macro and an inline function that takes
* an array.
*
*/
#define VARIADIC_MACRO_SUM_A(N, ...) \
inline_variadic_sum(N, __VA_ARGS__); \
do { \
fprintf(stdout, "inline variadic sum (%s) injected at %s\n", __func__, \
STRGY(__LINE__)); \
} while (false);
/* https://en.cppreference.com/w/c/language/inline */
double inline_variadic_sum(size_t n, ...);
inline double inline_variadic_sum(size_t n, ...) {
double ret = 0.0;
va_list va;
va_start(va, n);
for (size_t i = 0; i < n; ++i)
ret += va_arg(va, double);
va_end(va);
return ret;
}
#define VARIADIC_MACRO_SUM_B(N, ...) inline_variadic_sum(N, __VA_ARGS__)
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void sum_it_test(void **state) {
(void)state;
/* https://api.cmocka.org/group__cmocka__asserts.html */
double prec = 0.0001;
int n = 3;
double expected = 10.0;
double result = sum_it(n, 5.0, 3.0, 2.0);
assert_true(nearly_equal(expected, result, prec));
}
static void sum_it_inline_test(void **state) {
(void)state;
double prec = 0.0001;
int n = 3;
double expected = 10.0;
double result = inline_variadic_sum(n, 5.0, 3.0, 2.0);
assert_true(nearly_equal(expected, result, prec));
}
static void inline_variadic_macro_sum_it_test(void **state) {
(void)state;
double prec = 0.0001;
int n = 3;
double expected = 10.0;
double result = VARIADIC_MACRO_SUM_A(n, 5.0, 3.0, 2.0);
assert_true(nearly_equal(expected, result, prec));
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(sum_it_test),
cmocka_unit_test(sum_it_inline_test),
cmocka_unit_test(inline_variadic_macro_sum_it_test),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) { return test(); }
<file_sep>#include "series.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
series_results_t series(char *input_text, unsigned int substring_length) {
series_results_t res = {
.substring_count = 0,
.substring = (char **)malloc(sizeof(char *) * MAX_SERIES_RESULTS),
};
for (int i = 0; i < MAX_SERIES_RESULTS; i++) {
res.substring[i] = (char *)malloc(MAX_INPUT_TEXT_LENGTH * sizeof(char));
res.substring[i][0] = '\0';
}
if (!substring_length)
return res;
char *cursor = input_text;
while (cursor && strlen(cursor) >= substring_length) {
char subbuff[substring_length + 1];
/* The memcpy() function copies n bytes from memory area src to memory area
* dest.
*/
memcpy(&subbuff, cursor, substring_length);
/* The strcpy() function copies the string pointed to by src, including the
* terminating null byte ('\0'), to the buffer pointed to by dest. The
* strncpy() function is similar, except that at most n bytes of src are
* copied. Warning: If there is no null byte among the first n bytes of src,
* the string placed in dest will not be null-terminated.
*
* If the length of src is less than n, strncpy() writes additional null
* bytes to dest to ensure that a total of n bytes are written.
*
* strncpy(subbuff, input_text, substring_length);
*/
subbuff[substring_length] = '\0';
strncpy(res.substring[res.substring_count], subbuff, strlen(subbuff));
res.substring_count++;
cursor++;
}
return res;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
typedef union unsignedInspect unsignedInspect;
union unsignedInspect {
unsigned val;
unsigned char bytes[sizeof(unsigned)];
};
/* Exercises
- [Exs 19]: Design a similar union type to investigate the bytes of a pointer
type, double* say.
- [Exs 20]: With such a union, investigate the addresses of to consecutive
elements of an array.
- [Exs 21]: Compare addresses of the same variable between different
executions.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
unsignedInspect twofold = {
.val = 0xAABBCCDD,
};
printf("TwoFold (custom)\n");
printf("value is 0x%.08X\n", twofold.val);
for (size_t i = 0; i < sizeof twofold.bytes; ++i) {
printf("byte[%zu]: 0x%.02hhX\n", i, twofold.bytes[i]);
}
if (twofold.bytes[sizeof(twofold.bytes) - 1] == 0xAA) {
printf("storage order Little Endian\n");
} else {
printf("storage order Big Endian\n");
}
unsigned cval = 0xAABBCCDD;
unsigned char *valp = (unsigned char *)&cval;
for (size_t i = 0; i < sizeof cval; ++i) {
printf("byte[%zu]: 0x%.02hhX\n", i, valp[i]);
}
/*
* In that direction (from "pointer to object" to a "pointer to character
* type") a cast is mostly harmless.
*/
printf("TwoFold (pointer to float)\n");
const double d_number = 11.2233;
const double *const p_number = &d_number;
unsignedInspect twofold_pointer = {
.val = (unsigned)p_number,
};
printf("value is 0x%.08X\n", twofold_pointer.val);
for (size_t i = 0; i < sizeof twofold_pointer.bytes; ++i) {
printf("byte[%zu]: 0x%.02hhX\n", i, twofold_pointer.bytes[i]);
}
printf("TwoFold (pointer to int[])\n");
// int* arr[8]; // An array of int pointers.
// int *(arr3[8]); // An array of int pointers.
// int (*arr)[8]; // A pointer to an array of integers.
const int i_arr[] = {0, 1, 2};
const int *p_arr = &i_arr[0];
unsignedInspect twofold_array = {
.val = (unsigned)p_arr,
};
printf("value is 0x%.08X\n", twofold_array.val);
for (size_t i = 0; i < sizeof twofold_array.bytes; ++i) {
printf("byte[%zu]: 0x%.02hhX\n", i, twofold_array.bytes[i]);
}
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
/*
The difference here is that such a union doesn’t collect objects of different
type into one bigger object, but it overlays an object with different type
interpretation. By that it is the perfect tool to inspect the individual
bytes of an object of another type.
*/
/*
The complete unsigned value can be computed by the following expression, where
CHAR_BIT is the number of bits in a character type.
((0xAA << (CHAR_BIT*3))
|(0xBB << (CHAR_BIT*2))
|(0xCC << CHAR_BIT)
|0xDD)
*/
/*
~/build/modernC% ./code/endianess
value is 0xAABBCCDD
byte[0]: 0xDD
byte[1]: 0xCC
byte[2]: 0xBB
byte[3]: 0xAA
For my machine, we see that the output above had the low-order representation
digits of the integer first, then the next-lower order digits and so on. At the
end the highest order digits are printed. So the in-memory representation of
such an integer on my machine is to have the low-order representation digits
before the high-order ones.
*/
<file_sep>#ifndef SPACE_AGE_H
#define SPACE_AGE_H
typedef enum {
EARTH = 0,
MERCURY = 1,
VENUS = 2,
MARS = 3,
JUPITER = 4,
SATURN = 5,
URANUS = 6,
NEPTUNE = 7
} planet_t;
float convert_planet_age(planet_t planet, unsigned long seconds);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
listing 3.1.1
*/
/* a replacement for the fabs macro in <tgmath.h> */
/*
lower and upper iteration limits
centered around 1.0
*/
/*
Exs 3.4
Exs 3.5
Exs 3.6
*/
static double const eps1m01 = 1.0 - 0x1P-01;
static double const eps1p01 = 1.0 + 0x1P-01;
static double const eps1m24 = 1.0 - 0x1P-24;
static double const eps1p24 = 1.0 + 0x1P-24;
/*
The task of the program is to compute the inverse of all numbers that
are provided to it on the command line
*/
int main(int argc, char *argv[argc + 1]) {
printf("running as %s\n", argv[0]);
for (int i = 1; i < argc; ++i) {
/*
The task of the program is to compute the inverse of all numbers that
are provided to it on the command line.
http://www.cplusplus.com/reference/cstdlib/strtod/
*/
double const a = strtod(argv[i], 0);
printf("processing a: %.12f and eps1p01: %.12f\n", a, eps1p01);
double x = 1.0;
for (;;) {
// by powers of 2
double prod = a * x;
if (prod < eps1m01) {
x *= 2.0;
printf("x: %f\n", x);
} else if (eps1p01 < prod) {
x *= 0.5;
printf("x: %f\n", x);
} else
break;
}
for (;;) {
// Heron approximation
double prod = a * x;
if ((prod < eps1m24) || (eps1p24 < prod))
x *= (2.0 - prod);
else
break;
}
printf("heron : a = %.5e, \t x = %.5e, \t a * x = %.12f\n", a, x, a * x);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
unsigned i = 1;
/* prints 1 */
int main(void) {
unsigned i = 2; /* a new object */
if (i) {
extern unsigned i; /* an existing object */
printf("%u\n", i);
} else {
printf("%u\n", i);
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
Exercises
- [Exs 00]:
*/
int maybe_write() {
FILE *logfile = fopen("mylog.txt", "a");
if (!logfile) {
perror("fopen failed");
return EXIT_FAILURE;
}
fputs("feeling fine today\n", logfile);
return EXIT_SUCCESS;
}
int maybe_freopen() {
if (!freopen("mylog.txt", "a", stdout)) {
perror("freopen failed");
return EXIT_FAILURE;
}
puts("feeling fine today");
return EXIT_SUCCESS;
}
/*
delay execution with some crude code, should use thrd_sleep, once we have that
*/
void delay(double secs) {
double const magic = 4E8; // works just on my machine
unsigned long long const nano = secs * magic;
for (unsigned long volatile count = 0; count < nano; ++count) {
/* nothing here */
}
}
int dots(int argc, char *argv[argc + 1]) {
(void)argv;
fputs("waiting 10 seconds for you to stop me", stdout);
if (argc < 3) {
fflush(stdout);
}
for (unsigned i = 0; i < 10; ++i) {
fputc('.', stdout);
if (argc < 2) {
fflush(stdout);
}
delay(1.0);
}
fputs("\n", stdout);
return fputs("You did ignore me, so bye bye\n", stdout);
}
/*
Rule 1.8.2.10
fgetc returns int to be capable to encode a special error status, EOF, in
addition to all valid characters.
*/
char *fgets_manually(char s[restrict], int n, FILE *restrict stream) {
if (!stream) {
return 0;
}
if (!n) {
return s;
}
/* Read at most n-1 characters */
for (size_t i = 0; i < (size_t)n - 1; ++i) {
int val = fgetc(stream);
switch (val) {
/* EOF signals end-of-file or error */
case EOF:
if (feof(stream)) {
s[i] = 0; /* has been a valid call */
return s;
} else {
/* we are on error */
return 0;
}
/* stop at end-of-line */
case '\n':
s[i] = val;
s[i + 1] = 0;
return s;
/* otherwise just assign and continue */
default:
s[i] = val;
}
}
s[n - 1] = 0;
return s;
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(int argc, char *argv[argc + 1]) {
#if defined(TEST)
printf("\nrunning the test suite\n");
dots(argc, argv);
return test();
#endif
(void)argv;
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>/*
* https://en.wikipedia.org/wiki/Merge_sort
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
bool is_sorted(int *a, int n) {
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
bool is_odd(int i) { return (i & 1); }
bool is_even(int i) { return (i & 1) == 0; }
bool is_really_sorted(int *a, int n) {
/* i is the index of the last element */
int i = n - 1;
/* if i is less or equal to zero the array is one element or empty */
if (i <= 0) {
return true;
}
/* if i is odd (so the list has an odd number of elements */
if (is_odd(i)) {
/* we compare the last 2 elements */
if (a[i] < a[i - 1]) {
return false;
}
/* now the list has an even number of elements */
i--;
}
int last_element;
int previous_element;
/* we compare elements 2 at a time */
for (last_element = a[i]; i > 0; i -= 2) {
previous_element = a[i - 1];
if (last_element < previous_element) {
return false;
}
last_element = previous_element;
previous_element = a[i - 2];
if (last_element < previous_element) {
return false;
}
}
return a[0] <= a[1];
}
/* note about the pre/post increment of the variable:
*
* ++i will increment the value of i, and then return the incremented value.
* i = 1;
* j = ++i;
* (i is 2, j is 2)
*
* i++ will increment the value of i, but return the original value that i held
* before being incremented.
* i = 1;
* j = i++;
* (i is 2, j is 1)
*
* https://stackoverflow.com/a/24858
* https://stackoverflow.com/a/24887
*/
void merge(int *a, int n, int m) {
int i, j, k;
bool stop;
int *x = malloc(n * sizeof(int));
i = 0; /* the start point: the beginning of the left list */
j = m; /* the middle point: the beginning of the right list */
k = 0; /* the cursor */
stop = k < n; /* the stop condition */
/* in a compact way, the decision of which element put in the k position:
* x[k] = j == n ? a[i++] : i == m ? a[j++] : a[j] < a[i] ? a[j++] : a[i++];
*/
for (i = 0, j = m, k = 0; k < n; k++) {
if (j == n) {
/* if the middle index (j) is at the end it means
* that the right list is empty.
* so we keep consuming the left list.
*
* put a[i] at the position k in x and increment i.
*/
x[k] = a[i++];
} else if (i == m) {
/* if the start index (i) is the middle point it means
* that the left list is empty.
* we consume the right list.
*
* put a[j] at the position k in x and increment j.
*/
x[k] = a[j++];
} else if (a[j] < a[i]) {
/* both the left list (pointed by i) and the right list (pointed by j)
* are there, so we compare the element at i and the element at j and
* we pick the j if less than the element at i and the move j forward.
*/
x[k] = a[j++];
} else {
/* both the left list (pointed by i) and the right list (pointed by j)
* are there, so we compare the element at i and the element at j and
* we pick the i if less than the element at j and the move i forward.
*/
x[k] = a[i++];
}
}
/* we copy the sorted elements into a */
for (i = 0; i < n; i++) {
a[i] = x[i];
}
/* and we finally free x that is not needed anymore */
free(x);
}
void merge_sort(int *a, int n) {
if (n < 2) {
return;
}
int m = n / 2;
merge_sort(a, m);
merge_sort(a + m, n - m);
merge(a, n, m);
}
void copy_array(int source[], int iBegin, int iEnd, int destination[]) {
for (int k = iBegin; k < iEnd; k++) {
destination[k] = source[k];
}
}
void copy_array_n(int source[], int destination[], int n) {
for (int i = 0; i < n; i++)
destination[i] = source[i];
}
int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
/* ************************************************************************** */
/*
* Top-down implementation
*
* Implementation using indices for top down merge sort algorithm that
* recursively splits the list (called runs in this example) into sublists
* until sublist size is 1, then merges those sublists to produce a sorted
* list. The copy back step is avoided with alternating the direction of
* the merge with each level of recursion.
*/
/*
* TopDownMerge
*
* considering "a" as source, and "b" as destination.
* Left source half is a[ iBegin:iMiddle-1].
* Right source half is a[iMiddle:iEnd-1 ].
* Result is b[ iBegin:iEnd-1 ].
*/
void TopDownMerge(int a[], int iBegin, int iMiddle, int iEnd, int b[]) {
/* the beginning of the left list */
int i = iBegin;
/* the beginning of the right list */
int j = iMiddle;
/* the cursor */
int k;
/* while there are elements in the left or right runs... */
for (k = iBegin; k < iEnd; k++) {
/* if left run head exists and is <= existing right run head
* we pick a[i] to be the element at the position k (the cursor).
*/
if (i < iMiddle && (j >= iEnd || a[i] <= a[j])) {
/* we consume the left list */
b[k] = a[i];
i = i + 1;
} else {
/* or the index of the left list array reached the middle point (so
* the beginning of the right list) or the head of the right
*/
b[k] = a[j];
j = j + 1;
}
}
}
/*
* TopDownSplitMerge
* Sort the given run of array a[] using array b[] as a source.
* iBegin is inclusive; iEnd is exclusive (a[iEnd] is not in the set).
*/
void TopDownSplitMerge(int b[], int iBegin, int iEnd, int a[]) {
/* if run size == 1 consider it sorted */
if (iEnd - iBegin < 2) {
return;
}
/* split the run longer than 1 item into halves
* iMiddle is the mid point.
*/
int iMiddle = (iEnd + iBegin) / 2;
/* recursively sort both runs from array a[] into b[] */
/* sort the left run */
TopDownSplitMerge(a, iBegin, iMiddle, b);
/* sort the right run */
TopDownSplitMerge(a, iMiddle, iEnd, b);
/* merge the resulting runs from array b[] into a[] */
TopDownMerge(b, iBegin, iMiddle, iEnd, a);
}
/*
* TopDownMergeSort
* Array A[] has the items to sort; array B[] is a work array.
*/
void TopDownMergeSort(int a[], int b[], int n) {
/* duplicate array A[] into B[] */
copy_array(a, 0, n, b);
/* sort data from B[] into A[] */
TopDownSplitMerge(b, 0, n, a);
}
/* ************************************************************************** */
/*
* Bottom-up implementation
*
* merge sort using indices for bottom up merge sort algorithm which treats the
* list as an array of n sublists (called runs in this example) of size 1, and
* iteratively merges sub-lists back and forth between two buffers:
*/
/* Left run is A[iLeft :iRight-1].
* Right run is A[iRight:iEnd-1 ].
*/
void BottomUpMerge(int a[], int iLeft, int iRight, int iEnd, int b[]) {
int i = iLeft;
int j = iRight;
int k;
/* while there are elements in the left or right runs... */
for (k = iLeft; k < iEnd; k++) {
/* if left run head exists and is <= existing right run head. */
if (i < iRight && (j >= iEnd || a[i] <= a[j])) {
b[k] = a[i];
i = i + 1;
} else {
b[k] = a[j];
j = j + 1;
}
}
}
/*
* array a[] has the items to sort; array b[] is a work array
*/
void BottomUpMergeSort(int a[], int b[], int n) {
int width;
int i;
/* Each 1-element run in "a" is already "sorted".
* Make successively longer sorted runs of length 2, 4, 8, 16... until whole
* array is sorted.
*/
for (width = 1; width < n; width = 2 * width) {
/* array "a" is full of runs of length width. */
for (i = 0; i < n; i = i + 2 * width) {
/* merge two runs: a[i:i+width-1] and A[i+width:i+2*width-1] to b[]
* or copy a[i:n-1] to b[] ( if(i+width >= n) )
*/
BottomUpMerge(a, i, min(i + width, n), min(i + 2 * width, n), b);
}
/* now work array B is full of runs of length 2*width.
* copy array B to array A for next iteration.
* a more efficient implementation would swap the roles of A and B.
*/
copy_array_n(b, a, n);
/* Now array A is full of runs of length 2*width. */
}
}
/* ************************************************************************** */
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void is_sorted_test(void **state) {
(void)state;
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
assert_false(is_sorted(a, n));
int b[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
n = sizeof b / sizeof b[0];
assert_true(is_sorted(b, n));
int c[] = {1};
n = sizeof c / sizeof c[0];
assert_true(is_sorted(c, n));
int d[] = {};
n = 0;
assert_true(is_sorted(d, n));
}
static void is_really_sorted_test(void **state) {
(void)state;
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
assert_false(is_really_sorted(a, n));
int b[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
n = sizeof b / sizeof b[0];
assert_true(is_really_sorted(b, n));
int c[] = {1};
n = sizeof c / sizeof c[0];
assert_true(is_really_sorted(c, n));
int d[] = {};
n = 0;
assert_true(is_really_sorted(d, n));
}
static void merge_sort_test(void **state) {
(void)state;
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
merge_sort(a, n);
assert_true(is_sorted(a, n));
assert_true(is_really_sorted(a, n));
}
static void top_down_merge_sort_test(void **state) {
(void)state;
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int b[10] = {0};
TopDownMergeSort(a, b, n);
assert_true(is_sorted(a, n));
assert_true(is_really_sorted(a, n));
}
static void bottom_up_merge_sort_test(void **state) {
(void)state;
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int b[10] = {0};
BottomUpMergeSort(a, b, n);
assert_true(is_sorted(a, n));
assert_true(is_really_sorted(a, n));
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(is_sorted_test),
cmocka_unit_test(is_really_sorted_test),
cmocka_unit_test(merge_sort_test),
cmocka_unit_test(top_down_merge_sort_test),
cmocka_unit_test(bottom_up_merge_sort_test),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main() {
test();
return EXIT_SUCCESS;
}
<file_sep>#include "isogram.h"
#include <ctype.h>
#include <string.h>
bool is_isogram(const char phrase[]) {
if (!phrase) return false;
int alphabet[26] = {0};
const char *input = phrase;
while (*input) {
if (isalpha(*input)) {
const int key = tolower(*input) - 'a';
if (alphabet[key]) {
return false;
}
alphabet[key]++;
}
input++;
}
return true;
}
<file_sep>#ifndef HAMMING_H
#define HAMMING_H
int compute(char *a, char *b);
#endif
<file_sep>#ifndef ROMAN_NUMERALS_H
#define ROMAN_NUMERALS_H
char * to_roman_numeral(int);
#endif
<file_sep>#include "rna_transcription.h"
#include <stdlib.h>
#include <string.h>
/* char_to_upper converts a character to its uppercase version.
* 'a':97 ... 'z':122;
* 'A':65 ... 'Z':90
*/
int char_to_upper(char c) { return (c >= 'a' && c <= 'z') ? c - 32 : c; }
/* clang-format off */
static const char dna_to_rna[26] = {
['G' % 65] = 'C',
['C' % 65] = 'G',
['T' % 65] = 'A',
['A' % 65] = 'U',
[1] = '\0',
};
/* clang-format on */
char *to_rna(const char *dna) {
char *rna = malloc(sizeof(char) * (strlen(dna) + 1));
char *res = rna;
while (*dna) {
int idx = (*dna++) % 65;
if (!dna_to_rna[idx])
return NULL;
*rna = dna_to_rna[char_to_upper(idx)];
rna++;
}
return res;
}
<file_sep>#include <stdbool.h>
#include <stdio.h>
#include <time.h>
int leapyear(unsigned year) {
/* All years that are divisible by 4 are leap years, unless they start
a new century, provided they don't start a new millennium. */
return !(year % 4) && ((year % 100) || !(year % 1000));
}
#define DAYS_BEFORE \
(int const[12]) { \
[0] = 0, [1] = 31, [2] = 59, [3] = 90, [4] = 120, [5] = 151, [6] = 181, \
[7] = 212, [8] = 243, [9] = 273, [10] = 304, [11] = 334, \
}
struct tm time_set_yday(struct tm t) {
// tm_mdays starts at 1
t.tm_yday += DAYS_BEFORE[t.tm_mon] + t.tm_mday - 1;
// take care of leap years
if ((t.tm_mon > 1) && leapyear(t.tm_year))
++t.tm_yday;
return t;
}
int main(void) {
struct tm today = {
.tm_year = 2014,
.tm_mon = 2,
.tm_mday = 29,
.tm_hour = 16,
.tm_min = 7,
.tm_sec = 5,
};
printf("this year is %d, next year will be %d\n", today.tm_year,
today.tm_year + 1);
today = time_set_yday(today);
printf("day of the year is %d\n", today.tm_yday);
}
<file_sep>#include "complex_numbers.h"
#include <math.h>
/* https://en.wikipedia.org/wiki/Complex_number */
complex_t c_add(complex_t a, complex_t b) {
complex_t c = {
.real = a.real + b.real,
.imag = a.imag + b.imag,
};
return c;
}
complex_t c_sub(complex_t a, complex_t b) {
complex_t c = {
.real = a.real - b.real,
.imag = a.imag - b.imag,
};
return c;
}
complex_t c_mul(complex_t a, complex_t b) {
complex_t c = {
.real = a.real * b.real - a.imag * b.imag,
.imag = a.real * b.imag + a.imag * b.real,
};
return c;
}
complex_t c_div(complex_t a, complex_t b) {
double div = b.real * b.real + b.imag * b.imag;
return (complex_t){(a.real * b.real + a.imag * b.imag) / div,
(a.imag * b.real - a.real * b.imag) / div};
}
/* https://en.wikipedia.org/wiki/Newton's_method
* http://www.nr.com/
*/
double c_abs(complex_t x) { return sqrt((x.real * x.real) + x.imag * x.imag); }
complex_t c_conjugate(complex_t x) {
complex_t c = {
.real = x.real,
.imag = -x.imag,
};
return c;
}
double c_real(complex_t x) { return x.real; }
double c_imag(complex_t x) { return x.imag; }
complex_t c_exp(complex_t x) {
complex_t c = {
.real = exp(x.real) * cos(x.imag),
.imag = exp(x.real) * sin(x.imag),
};
return c;
}
<file_sep>#include <iso646.h>
#include <math.h>
/* http://www.cplusplus.com/reference/climits/ */
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
/*
** Bit operations and values
| bit op | value | hex | b 15 ... b 0 | set op |
|-----------+-------+--------+------------------+--------|
| V | 65535 | 0xFFFF | 1111111111111111 | |
| A | 240 | 0x00F0 | 0000000011110000 | |
| ~A | 65295 | 0xFF0f | 1111111100001111 | V \ A |
| -A | 65296 | 0xFF10 | 1111111100010000 | |
| B | 287 | 0x011F | 0000000100011111 | |
| A \vert B | 511 | 0x01FF | 0000000111111111 | A ∪ B |
| A & B | 16 | 0x0010 | 0000000000010000 | A ∩ B |
| A ^ B | 495 | 0x01EF | 0000000111101111 | A ∆ B |
| bit op | set |
|-----------+-----------------------------------------|
| V | {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} |
| A | {4,5,6,7} |
| ~A | {0,1,2,3,8,9,10,11,12,13,14,15} |
| -A | {4,8,9,10,11,12,13,14,15} |
| B | {0, 1, 2, 3, 4, 8} |
| A \vert B | {0, 1, 2, 3, 4, 5, 6, 7, 8} |
| A & B | {4} |
| A ^ B | {0, 1, 2, 3, 5, 6, 7, 8} |
| | |
** Conversion table
| binary | hexadecimal | decimal |
| -------|-------------|------------------|
| 0000 | 0 | 0 (zero) |
| 0001 | 0x1 | 1 (one) |
| 0010 | 0x2 | 2 (two) |
| 0011 | 0x3 | 3 (three) |
| 0100 | 0x4 | 4 (four) |
| 0101 | 0x5 | 5 (five) |
| 0110 | 0x6 | 6 (six) |
| 0111 | 0x7 | 7 (seven) |
| 1000 | 0x8 | 8 (eight) |
| 1001 | 0x9 | 9 (nine) |
| 1010 | 0xA | 10 (ten) |
| 1011 | 0xB | 11 (eleven) |
| 1100 | 0xC | 12 (twelve) |
| 1101 | 0xD | 13 (thirteen) |
| 1110 | 0xE | 14 (fourteen) |
| 1111 | 0xF | 15 (fifteen) |
| 10000 | 0x10 | 16 (sixteen) |
| 10001 | 0x11 | 17 (seventeen) |
** Exercises
- [Exs 16]: Show that A \ B can be computed by A - (A&B)
- [Exs 17]: Show that V + 1 is 0.
- [Exs 18]: Show that A^B is equivalent to (A - (A&B))+ (B - (A&B)) and
A + B -2*(A&B)
- [Exs 19]: Show that A|B is equivalent to A + B - (A&B)
- [Exs 20]: Show that ~B can be computed by V - B
- [Exs 21]: Show that -B = ~B + 1
- [Exs 22]: Show that the bits that are "lost" in an operation x >> n
correspond to the remainder x % (1ULL << n).
- [Exs 23]: Show that INT_MIN+INT_MAX is −1.
- [Exs 24]: INT8_MIN, INT8_MAX, ..., INT64_MIN and INT64_MAX. If they
exist, the value of all these macros is precribed by the properties
of the types. Think of a closed formulas in N for these values.
- [Exs 25]: Show that all representable floating point values with e > p are
multiples of 2e−p.
- [Exs 26]: Print the results of the following expressions: 1.0E-13 + 1.0E-13
and (1.0E-13 + (1.0E-13 + 1.0))- 1.0.
*/
#define B0(x) S_to_binary_(#x)
/*
https://en.wikipedia.org/wiki/Bitwise_operations_in_C
*/
static inline unsigned long long S_to_binary_(const char *s) {
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
/* Function to convert a decinal number to binary number. */
long decimal_to_binary(long n) {
int remainder;
long binary = 0, i = 1;
while (n != 0) {
remainder = n % 2;
n = n / 2;
binary = binary + (remainder * i);
i = i * 10;
}
return binary;
}
/* Function to convert a binary number to decimal number. */
long binary_to_decimal(long n) {
int remainder;
long decimal = 0, i = 0;
while (n != 0) {
remainder = n % 10;
n = n / 10;
decimal = decimal + (remainder * pow(2, i));
++i;
}
return decimal;
}
void int_to_bin(int num, char *str, int buffersize) {
if (!str || buffersize < 1)
return;
/* cleaning up the buffer */
memset(str, 0, buffersize);
int i;
/*
Fill the buffer from the MSB to the LSB.
For instance, if the buffersize is 9, we expect to have an 8 digit binay
number. The indexes of the string goes from 0 (MSB) to 7 (LSB) and ends
with 8 that will be reserved for the string termination.
The loop will start filling the binary digits from the MSB.
*/
const int MSB = buffersize - 2;
const int LSB = 0;
for (i = MSB; i >= LSB; i--) {
str[i] = (num & 1) ? '1' : '0';
num >>= 1;
}
/* Ensure the string is NULL-terminated. */
str[buffersize - 1] = '\0';
}
void int_print_bin(int n) {
/* PRECISION: how many "digits" will be used to represent this number. */
const int PRECISION = 12;
/* reserve space for 13 characters (12 + 1) */
char str[PRECISION + 1];
int num = n;
memset(str, 0, (PRECISION + 1) * sizeof(char));
int i;
/* binary number length: 12 digits (0..11) */
for (i = PRECISION - 1; i >= 0; i--) {
str[i] = (num & 1) ? '1' : '0';
num >>= 1;
}
printf("num: %d: [%s]\n", n, str);
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_int_print_bin(void **state) { (void)state; /* ununsed */ }
static void test_eql(void **state) {
(void)state; /* unused */
int const a_d = 240;
int const b_d = 287;
int const a_x = 0x00F0;
int const b_x = 0x011F;
int const a_b = B0(11110000);
int const b_b = B0(100011111);
assert_int_equal(1, B0(1));
assert_int_equal(a_d, a_x);
assert_int_equal(b_d, b_x);
assert_int_equal(a_x, a_b);
assert_int_equal(b_x, b_b);
assert_int_equal(a_d, a_b);
assert_int_equal(b_d, b_b);
}
static void test_conversions(void **state) {
(void)state; /* unused */
int const a_x = 0x00F0;
int const b_x = 0x011F;
char const a_s[] = "11110000";
char const b_s[] = "100011111";
char str_a[sizeof(a_s)] = {0};
int_to_bin(a_x, str_a, sizeof(a_s));
assert_string_equal(a_s, str_a);
/*
Empty a string:
buffer[0] = '\0';
If you want to zero the entire contents of the string, you can do it this way:
memset(buffer, 0, strlen(buffer));
but this will only work for zeroing up to the first NULL character.
If the string is a static array, you can use:
memset(buffer, 0, sizeof(buffer));
*/
char str_b[sizeof(b_s)] = {0};
int_to_bin(b_x, str_b, sizeof(b_s));
assert_string_equal(b_s, str_b);
}
/*
[Exs 16]: Show that A \ B can be computed by A - (A&B)
011110000
& 100011111
---------
000010000 (16)
011110000
\ 100011111
---------
011100000 (224)
*/
static void test_exs_16(void **state) {
(void)state; /* unused */
int const a_x = 0x00F0;
int const b_x = 0x011F;
assert_int_equal(0x10, a_x & b_x); /* 16 */
assert_int_equal(0xE0, (a_x - (a_x & b_x))); /* 224 */
}
/*
[Exs 17]: Show that V + 1 is 0.
https://en.wikipedia.org/wiki/C_data_types#stdint.h
http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html
*/
static void test_exs_17(void **state) {
(void)state; /* unused */
int16_t const v_x = 0xFFFF; /* 65535 */
assert_int_equal(0x0, (v_x + 0x1));
}
/*
[Exs 18]: Show that A^B is equivalent to (A - (A&B)) + (B - (A&B)) and
A + B -2*(A&B)
011110000
^ 100011111
---------
111101111 (495)
*/
static void test_exs_18(void **state) {
(void)state; /* unused */
int const res = 0x01EF;
int const a_x = 0x00F0;
int const b_x = 0x011F;
assert_int_equal(res, (a_x - (a_x & b_x)) + (b_x - (a_x & b_x)));
assert_int_equal(res, (a_x + b_x - 2 * (a_x & b_x)));
}
/*
[Exs 19]: Show that A|B is equivalent to A + B - (A&B)
011110000
| 100011111
---------
111111111 (511)
*/
static void test_exs_19(void **state) {
(void)state; /* unused */
int const res = 0x01FF;
int const a_x = 0x00F0;
int const b_x = 0x011F;
assert_int_equal(res, (a_x + b_x - (a_x & b_x)));
}
/*
[Exs 20]: Show that ~B can be computed by V - B.
1111111111111111
- 0000000100011111
---------
1111111011100000 (65248)
http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html
*/
static void test_exs_20(void **state) {
(void)state; /* unused */
uint16_t const res = 0xFEE0; /* 65248 */
uint16_t const v_x = 0xFFFF; /* 65535 */
uint16_t const b_x = 0x011F; /* 287 */
assert_int_equal(res, (uint16_t)~b_x);
assert_int_equal(res, v_x - b_x);
}
/*
[Exs 21]: Show that -B = ~B + 1
*/
static void test_exs_21(void **state) {
(void)state; /* unused */
uint16_t const res = 0xFEE1; /* 65249 */
uint16_t const b_x = 0x011F; /* 287 */
assert_int_equal(res, (uint16_t)~b_x + (uint16_t)1);
assert_int_equal(res, (uint16_t)(b_x * (-1)));
}
/*
[Exs 22]: Show that the bits that are "lost" in an operation x >> n
correspond to the remainder x % (1ULL << n).
n >> k is the rightward arithmetic shift of the bits of n by k places.
1010_2 >> 2 = 0010_2 (2)
1 << 0010_2 = 0100_2 (4)
10 % 4 = 2 (where 10/4 = 2 and 10/4.0 = 2.5)
*/
static void test_exs_22(void **state) {
(void)state; /* unused */
uint16_t const res = 0x0002; /* 2 */
uint16_t const x_x = 0x000A; /* 10 */
uint16_t const n_x = 0x0002; /* 2 */
assert_int_equal(res, (uint16_t)(x_x >> n_x));
assert_int_equal(res, (uint16_t)(x_x % (1ULL << n_x)));
}
/*
[Exs 23]: Show that INT_MIN+INT_MAX is −1.
INT_MIN: Minimum value for an object of type int; -32767 (-215+1) or less*
INT_MAX: Maximum value for an object of type int; 32767 (215-1) or greater*
*/
static void test_exs_23(void **state) {
(void)state; /* unused */
assert_int_equal(-1, INT_MIN + INT_MAX);
}
/*
[Exs 24]: INT8_MIN, INT8_MAX, ..., INT64_MIN and INT64_MAX. If they
exist, the value of all these macros is precribed by the properties
of the types. Think of a closed formulas in N for these values.
*/
static void test_exs_24(void **state) {
(void)state; /* unused */
/* 11111111 >> 8 */
assert_int_equal(1, (uint8_t)UINT8_MAX >> 7);
assert_int_equal(0, (uint8_t)UINT8_MAX >> 8);
assert_int_equal(0, (uint16_t)UINT16_MAX >> 16);
assert_int_equal(1, (uint32_t)UINT32_MAX >> 31);
}
int test(void) {
uint32_t n = 78;
int64_t max = (-UINT64_C(1)) >> 1; // same value as INT64_MAX
printf("n is %" PRIu32 ", and max is %" PRId64 "\n", n, max);
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_int_print_bin),
cmocka_unit_test(test_eql),
cmocka_unit_test(test_conversions),
cmocka_unit_test(test_exs_16),
cmocka_unit_test(test_exs_17),
cmocka_unit_test(test_exs_18),
cmocka_unit_test(test_exs_19),
cmocka_unit_test(test_exs_20),
cmocka_unit_test(test_exs_21),
cmocka_unit_test(test_exs_22),
cmocka_unit_test(test_exs_23),
cmocka_unit_test(test_exs_24),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#include "pascals_triangle.h"
#include <limits.h>
#include <stdio.h>
int binomial_recursive(int n, int k) {
if (k == 0)
return 1;
if (n <= k)
return 0;
return (n * binomial_recursive(n - 1, k - 1)) / k;
}
/* We go to some effort to handle overflow situations
* source https://rosettacode.org/wiki/Evaluate_binomial_coefficients#C
*/
static size_t gcd_ui(size_t x, size_t y) {
size_t t;
if (y < x) {
t = x;
x = y;
y = t;
}
while (y > 0) {
t = y;
y = x % y;
x = t; /* y1 <- x0 % y0 ; x1 <- y0 */
}
return x;
}
size_t binomial(size_t n, size_t k) {
size_t d, g, r = 1;
if (k == 0)
return 1;
if (k == 1)
return n;
if (k >= n)
return (k == n);
if (k > n / 2)
k = n - k;
for (d = 1; d <= k; d++) {
if (r >= ULONG_MAX / n) { /* Possible overflow */
size_t nr, dr; /* reduced numerator / denominator */
g = gcd_ui(n, d);
nr = n / g;
dr = d / g;
g = gcd_ui(r, dr);
r = r / g;
dr = dr / g;
if (r >= ULONG_MAX / nr)
return 0; /* Unavoidable overflow */
r *= nr;
r /= dr;
n--;
} else {
r *= n--;
r /= d;
}
}
return r;
}
void print_triangle(size_t **r, size_t rows) {
printf("----- %02lu ROWS -----\n", rows);
for (size_t x = 0; x < rows; ++x) {
printf("|");
for (size_t y = 0; y < rows; ++y) {
printf("[%02lu]", r[x][y]);
}
printf("|\n");
}
}
/*
* https://en.wikipedia.org/wiki/Pascal's_triangle
* https://en.wikipedia.org/wiki/Pascal%27s_rule
* https://en.wikipedia.org/wiki/Pascal_matrix
*
* givent the fact that the element at the row n, position k is
* (n k) = n!/((n-k)!k!)
*/
size_t **create_triangle(size_t n) {
if (n < 0 || (n > 0 && n > ULONG_MAX / n))
return (void *)(0);
size_t rows = n > 0 ? n : 1;
size_t **r = malloc(sizeof(size_t *) * rows);
if (n == 0) {
r[0] = malloc(sizeof(size_t));
r[0][0] = 0;
return r;
}
size_t i, j;
for (i = 0; i < n; i++) {
/* malloc(sizeof(size_t) * n); */
r[i] = calloc(n, sizeof(size_t));
}
r[0][0] = 1;
for (i = 1; i < rows; ++i) {
r[i][0] = r[i][i] = 1;
for (j = 1; j < i; ++j)
r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
}
#ifdef PASCALS_TRIANGLE_DEBUG
print_triangle(r, rows);
#endif
return r;
}
void free_triangle(size_t **r, size_t n) {
for (size_t i = 0; i < n; ++i) {
free(r[i]);
}
free(r);
}
<file_sep>#include "word_count.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/* char_to_lower converts a character to its lowercase version. */
int char_to_lower(char c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
/* contains_word returns the index of the given word in the word counter
* structure pointed by `words`.
* returns -1 otherwise. */
int contains_word(const char *word, word_count_word_t *words) {
for (int i = 0; i < MAX_WORDS; i++) {
if (strncmp(words[i].text, word, MAX_WORD_LENGTH) == 0) {
return i;
}
}
return -1;
}
/* convert all characters in string to lower_case.
*
* using a for loop:
*
* for (int i = 0; token[i]; i++) {
* token[i] = tolower(token[i]);
* }
*
*/
char *str_to_lower(char *t) {
char *start = t;
do {
*t = tolower(*t);
} while (*t++);
return start;
}
/* get a mutable copy of the input string. */
char *copy(const char *input) {
char *input_copy = malloc(MAX_WORDS * MAX_WORD_LENGTH);
strcpy(input_copy, input);
return input_copy;
}
/* initialise the "words counter" ensuring that the word_count_word structure
* pointed by 'words' will contains MAX_WORDS words, zeroed of MAX_WORD_LENGHT
* length. */
void initialise(word_count_word_t *words) {
for (int i = 0; i < MAX_WORDS; i++) {
words[i].count = 0;
memset(words[i].text, 0, MAX_WORD_LENGTH);
}
}
/* str_to_unquoted removes leading and trailing single quote from the given
* string. */
char *str_to_unquoted(char *input) {
if (input[0] == '\'' && input[strlen(input) - 1] == '\'') {
input[strlen(input) - 1] = '\0';
input++;
}
return input;
}
/* search and if found, count and stop. */
int search_and_count(word_count_word_t *words, char *word, int unique_words) {
for (int i = 0; i < unique_words; i++) {
if (!strcmp(word, words[i].text)) {
words[i].count++;
return 1;
}
}
return 0;
}
/* insert the given word in the first available space, indicated by the
* unique_words counter, in the words structure.
* returns the updated count (that is also the next available position. */
int insert(word_count_word_t *words, char *word, int unique_words) {
strcpy(words[unique_words].text, word);
words[unique_words].count = 1;
return ++unique_words;
}
/* symbols to be considered delimiters. */
const char delimiters[] = " ,\n!\"#$%%&()*+.-/:;<=>?@[\\]^_`{|}~";
/* WORD_COUNT
*
* word_count - routine to classify the unique words and their frequency in a
* test input string inputs: input_text = a null-terminated string containing
* that is analyzed
*
* OUTPUTS:
* words = allocated structure to record the words found and their frequency
* uniqueWords - number of words in the words structure
* returns a negative number if an error.
* words will contain the results up to that point.
*
* LIBRARY FUNCTIONS:
*
* STRTOK
* strtok, strtok_r -- string tokens
* Standard C Library (libc, -lc)
*
* #include <string.h>
* char *
* strtok(char *restrict str, const char *restrict sep);
*
* TOLOWER
* tolower, tolower_l -- upper case to lower case letter conversion
* Standard C Library (libc, -lc)
*
* #include <ctype.h>
* int
* tolower(int c);
*/
int word_count(const char *input_text, word_count_word_t *words) {
char *input = copy(input_text);
initialise(words);
int unique_words = 0;
char *token = strtok(input, delimiters);
while (token != NULL) {
token = str_to_lower(token);
token = str_to_unquoted(token);
if (strlen(token) > MAX_WORD_LENGTH)
return EXCESSIVE_LENGTH_WORD;
int found = 0;
found = search_and_count(words, token, unique_words);
if (!found) {
if (unique_words >= MAX_WORDS) {
return EXCESSIVE_NUMBER_OF_WORDS;
}
unique_words = insert(words, token, unique_words);
}
token = strtok(NULL, delimiters);
}
free(input);
return unique_words;
}
<file_sep>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
/*
Exs 3.8
Implement some computations using a 24 hour clock, e.g. 3 hours after
ten, 8 hours after twenty.
For unsigned values, a == (a/b)*b + (a%b).
*/
void floor_some() {
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = 2.8;
val4 = 2.3;
printf("Value1 = %.1lf\n", floor(val1));
printf("Value2 = %.1lf\n", floor(val2));
printf("Value3 = %.1lf\n", floor(val3));
printf("Value4 = %.1lf\n", floor(val4));
}
void ceil_some() {
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = 2.8;
val4 = 2.3;
printf("value1 = %.1lf\n", ceil(val1));
printf("value2 = %.1lf\n", ceil(val2));
printf("value3 = %.1lf\n", ceil(val3));
printf("value4 = %.1lf\n", ceil(val4));
}
void round_some() {
for (double a = 120; a <= 130;
a += 1.0) /* note: increments by fraction are not exact! */
printf("round of %.1lf is %.1lf\n", a / 10.0, round(a / 10.0));
}
int add_hours(int a, int b) {
int r = (24 + a + (b % 24)) % 24;
return r;
}
int delta_days(int a, int b) {
float r = (abs(a) + b) / 24.0;
return floor(r);
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_add_base(void **state) {
(void)state; /* unused */
assert_int_equal(add_hours(11, 1), 12);
assert_int_equal(add_hours(11, 4), 15);
assert_int_equal(add_hours(22, 2), 0);
assert_int_equal(add_hours(22, 4), 2);
assert_int_equal(add_hours(22, 22), 20);
assert_int_equal(add_hours(11, 0), 11);
assert_int_equal(add_hours(11, 24), 11);
assert_int_equal(add_hours(11, 48), 11);
assert_int_equal(add_hours(22, 24), 22);
assert_int_equal(add_hours(11, 70), 9);
}
static void test_sub_base(void **state) {
(void)state; /* unused */
assert_int_equal(add_hours(11, -1), 10);
assert_int_equal(add_hours(11, -4), 7);
assert_int_equal(add_hours(22, -2), 20);
assert_int_equal(add_hours(22, -4), 18);
assert_int_equal(add_hours(22, -22), 0);
assert_int_equal(add_hours(11, -0), 11);
}
static void test_sub_more(void **state) {
(void)state; /* unused */
assert_int_equal(add_hours(11, -24), 11);
assert_int_equal(add_hours(11, -48), 11);
assert_int_equal(add_hours(22, -24), 22);
assert_int_equal(add_hours(11, -70), 13);
}
static void test_add_days(void **state) {
(void)state; /* unused */
assert_int_equal(delta_days(11, 24), 1);
assert_int_equal(delta_days(11, 48), 2);
assert_int_equal(delta_days(11, 72), 3);
assert_int_equal(delta_days(11, 96), 4);
}
static void test_sub_days(void **state) {
(void)state; /* unused */
assert_int_equal(delta_days(11, -24), -1);
assert_int_equal(delta_days(11, -48), -2);
assert_int_equal(delta_days(11, -72), -3);
assert_int_equal(delta_days(11, -96), -4);
}
int test(void) {
// clang-format off
// http://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code
const struct CMUnitTest tests[] = {
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_add_base),
cmocka_unit_test(test_sub_base),
cmocka_unit_test(test_sub_more),
cmocka_unit_test(test_add_days),
cmocka_unit_test(test_sub_days),
};
// clang-format on
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(int argc, char *argv[argc + 1]) {
printf("running as %s\n", argv[0]);
int delta = 10;
if (argc == 1) {
printf("no input given... running for delta %+d!\n\n", delta);
/*
https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html
4.2.1 Ifdef
The simplest sort of conditional is
#ifdef MACRO
controlled text
#endif // END MACRO //
This block is called a conditional group. controlled text will be
included in the output of the preprocessor if and only if MACRO is
defined. We say that the conditional succeeds if MACRO is defined, fails
if it is not.
The controlled text inside of a conditional can include preprocessing
directives. They are executed only if the conditional succeeds. You can
nest conditional groups inside other conditional groups, but they must
be completely nested. In other words, #endif always matches the
nearest #ifdef (or #ifndef, or #if). Also, you cannot start a
conditional group in one file and end it in another.
Even if a conditional fails, the controlled text inside it is still run
through initial transformations and tokenization. Therefore, it must all
be lexically valid C. Normally the only way this matters is that all
comments and string literals inside a failing conditional group must
still be properly ended.
The comment following the #endif is not required, but it is a good
practice if there is a lot of controlled text, because it helps people
match the #endif to the corresponding #ifdef. Older programs
sometimes put MACRO directly after the #endif without enclosing it in
a comment. This is invalid code according to the C standard. CPP accepts
it with a warning. It never affects which #ifndef the #endif
matches.
Sometimes you wish to use some code if a macro is not defined. You can do this
by writing #ifndef instead of #ifdef. One common use of #ifndef is to
include code only the first time a header file is included. See Once-Only
Headers.
Macro definitions can vary between compilations for several reasons. Here are
some samples.
Some macros are predefined on each kind of machine (see System-specific
Predefined Macros). This allows you to provide code specially tuned for a
particular machine.
System header files define more macros, associated with the features they
implement. You can test these macros with conditionals to avoid using a system
feature on a machine where it is not implemented.
Macros can be defined or undefined with the -D and -U command-line options
when you compile the program. You can arrange to compile the same source file
into two different programs by choosing a macro name to specify which program
you want, writing conditionals to test whether or how this macro is defined, and
then controlling the state of the macro with command-line options, perhaps set
in the Makefile. See Invocation.
Your program might have a special header file (often called config.h) that
is adjusted when the program is compiled. It can define or not define macros
depending on the features of the system and the desired capabilities of the
program. The adjustment can be automated by a tool such as autoconf, or done by
hand.
Next: If, Up: Conditional Syntax [Contents][Index]
*/
#if defined(SAMPLE)
const char *format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
printf("value\tround\tfloor\tceil\ttrunc\n");
printf("-----\t-----\t-----\t----\t-----\n");
printf(format, 2.3, round(2.3), floor(2.3), ceil(2.3), trunc(2.3));
printf(format, 3.8, round(3.8), floor(3.8), ceil(3.8), trunc(3.8));
printf(format, 5.5, round(5.5), floor(5.5), ceil(5.5), trunc(5.5));
printf("value\tround\tfloor\tceil\ttrunc\n");
printf("-----\t-----\t-----\t----\t-----\n");
printf(format, -2.3, round(-2.3), floor(-2.3), ceil(-2.3), trunc(-2.3));
printf(format, -3.8, round(-3.8), floor(-3.8), ceil(-3.8), trunc(-3.8));
printf(format, -5.5, round(-5.5), floor(-5.5), ceil(-5.5), trunc(-5.5));
return EXIT_SUCCESS;
#elif defined(TEST)
printf("Running the test suite\n");
return test();
#endif
} else {
delta = atoi(argv[1]);
}
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
printf("Current local time and date: %s\n", asctime(timeinfo));
printf("Hours (0-23): %d\n", timeinfo->tm_hour);
printf("Hours (0-23)%+d: %d (%+d days)\n", delta,
add_hours(timeinfo->tm_hour, delta),
delta_days(timeinfo->tm_hour, delta));
return EXIT_SUCCESS;
}
<file_sep>#ifndef GIGASECOND_H
#define GIGASECOND_H
#include <time.h>
time_t gigasecond_after(time_t t);
#endif /* end GIGASECOND_H */
<file_sep>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/* Exercises
[Exs 40]: Write a function my_strtod that implements the functionality of
strtod for decimal floating point con- stants.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
/* strtod
The C library function double strtod(const char *str, char **endptr)
converts the string pointed to by the argument str to a floating-point
number (type double). If endptr is not NULL, a pointer to the character
after the last character used in the conversion is stored in the
location referenced by endptr.
Declaration
Following is the declaration for strtod() function.
double strtod(const char *str, char **endptr)
Parameters
str − This is the value to be converted to a string.
endptr − This is the reference to an already allocated object of type char*,
whose value is set by the function to the next character in str after
the numerical value.
Return Value
This function returns the converted floating point number as a double value,
else zero value (0.0) is returned.
*/
void strtod_sample() {
char str[30] = "20.30300 This is test";
char *ptr;
double ret;
ret = strtod(str, &ptr);
printf("The number(double) is %lf\n", ret);
printf("String part is |%s|", ptr);
}
/*
Original STRTOD code
http://www.jbox.dk/sanos/source/lib/strtod.c.html
*/
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
double strtod_original(const char *str, char **endptr) {
double number;
int exponent;
int negative;
char *p = (char *)str;
double p10;
int n;
int num_digits;
int num_decimals;
// Skip leading whitespace
while (isspace(*p))
p++;
// Handle optional sign
negative = 0;
switch (*p) {
case '-':
negative = 1; // Fall through to increment position
case '+':
p++;
}
number = 0.;
exponent = 0;
num_digits = 0;
num_decimals = 0;
// Process string of digits
while (isdigit(*p)) {
number = number * 10. + (*p - '0');
p++;
num_digits++;
}
// Process decimal part
if (*p == '.') {
p++;
while (isdigit(*p)) {
number = number * 10. + (*p - '0');
p++;
num_digits++;
num_decimals++;
}
exponent -= num_decimals;
}
if (num_digits == 0) {
errno = ERANGE;
return 0.0;
}
// Correct for sign
if (negative)
number = -number;
// Process an exponent string
if (*p == 'e' || *p == 'E') {
// Handle optional sign
negative = 0;
switch (*++p) {
case '-':
negative = 1; // Fall through to increment pos
case '+':
p++;
}
// Process string of digits
n = 0;
while (isdigit(*p)) {
n = n * 10 + (*p - '0');
p++;
}
if (negative) {
exponent -= n;
} else {
exponent += n;
}
}
if (exponent < DBL_MIN_EXP || exponent > DBL_MAX_EXP) {
errno = ERANGE;
return HUGE_VAL;
}
// Scale the result
p10 = 10.;
n = exponent;
if (n < 0)
n = -n;
while (n) {
if (n & 1) {
if (exponent < 0) {
number /= p10;
} else {
number *= p10;
}
}
n >>= 1;
p10 *= p10;
}
if (number == HUGE_VAL)
errno = ERANGE;
if (endptr)
*endptr = p;
return number;
}
int to_digit(char p) {
int res;
res = p - '0';
assert(res >= 0 && res <= 9);
return res;
}
void test_to_digit(void **state) {
(void)state;
assert_int_equal(3, to_digit('3'));
assert_int_equal(0, to_digit('0'));
}
void test_right_shift(void **state) {
(void)state;
assert_int_equal(3, 6 >> 1);
assert_int_equal(5, 10 >> 1);
}
int is_odd(int n) {
return n & 1;
}
void test_is_odd(void **state) {
(void)state;
assert_true(is_odd(3));
assert_false(is_odd(2));
assert_false(is_odd(2));
}
double strtod_simple(const char *str) {
double number;
int exponent;
char *p = (char *)str;
double p10;
int n;
int num_digits;
int num_decimals;
number = 0.;
exponent = 0;
num_digits = 0;
num_decimals = 0;
// Process string of digits
while (isdigit(*p)) {
number = number * 10. + to_digit(*p);
p++;
num_digits++;
}
// Process decimal part
if (*p == '.') {
p++;
while (isdigit(*p)) {
number = number * 10. + to_digit(*p);
p++;
num_digits++;
num_decimals++;
}
exponent -= num_decimals;
}
if (num_digits == 0) {
errno = ERANGE;
return 0.0;
}
// Scale the result
p10 = 10.;
n = exponent;
if (n < 0) {
n = -n;
}
while (n) {
if (is_odd(n)) {
if (exponent < 0) {
number /= p10;
} else {
number *= p10;
}
}
n >>= 1;
p10 *= p10;
}
return number;
}
void strtod_not(const char *str, char **endptr) {
char *p = (char *)str;
while (isspace(*p)) { p++; }
switch (*p) {
case '-':
case '+':
p++;
}
while (isdigit(*p)) {
p++;
}
if (*p == '.') {
p++;
while (isdigit(*p)) {
p++;
}
}
if (*p == 'e' || *p == 'E') {
switch (*++p) {
case '-':
case '+':
p++;
}
while (isdigit(*p)) {
p++;
}
}
if (endptr) {
*endptr = p;
}
}
void test_strtod_not_comparison(void **state) {
(void)state;
char str[30] = "20.30300 This is test";
char *expected;
char *actual;
strtod_original(str, &expected);
strtod_not(str, &actual);
DEBUG_PRINT(("comparing\nactual:\t\t[%s] with\nexpected:\t[%s]\n", actual, expected));
assert_true(strcmp(expected, actual) == 0);
strcpy(str, "-0.42 is a test");
expected = NULL;
actual = NULL;
strtod_original(str, &expected);
strtod_not(str, &actual);
DEBUG_PRINT(("comparing\nactual:\t\t[%s] with\nexpected:\t[%s]\n", actual, expected));
assert_true(strcmp(expected, actual) == 0);
}
void test_strtod_comparison(void **state) {
(void)state;
char str[30] = "20.30300 This is test";
double expected = 20.30300;
double ret_a;
double ret_b;
ret_a = strtod_original(str, NULL);
ret_b = strtod_simple(str);
assert_true(expected == ret_a);
assert_true(expected == ret_b);
strcpy(str, "0.42 This is test");
expected = 0.42;
ret_a = strtod_original(str, NULL);
ret_b = strtod_simple(str);
assert_true(expected == ret_a);
assert_true(expected == ret_b);
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_to_digit),
cmocka_unit_test(test_is_odd),
cmocka_unit_test(test_right_shift),
cmocka_unit_test(test_strtod_comparison),
cmocka_unit_test(test_strtod_not_comparison),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#ifndef ETL_H
#define ETL_H
typedef struct legacy_map_t {
int key;
char *value;
} legacy_map;
typedef struct new_map_t {
char key;
int value;
} new_map;
int convert(legacy_map *input, int input_len, new_map **output);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/float.h.html */
#include <float.h>
/* http://www.cplusplus.com/reference/cmath/ */
#include <math.h>
/* typedef enum { false, true } bool; */
/* (C99) */
#include <stdbool.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
#include "nearly.h"
/*
* TODO:
* - [x] circular_append;
* - [x] circular_pop;
* - [x] circular_element;
* - [x] circular_init;
* - [x] circular_destroy;
* - [x] circular_new;
* - [x] circular_delete;
* - [x] circular_resize;
* - [x] circular_getlength;
* - [x] circular_shrink;
*/
/*
* circular.h
*/
/*
* circular: an opaque type for a circular buffer for double values
* This data structure allows to add double values in rear and to take them out
* in front. Each such structure has a maximal amount of elements that can be
* stored in it.
*/
typedef struct circular circular;
/*
* circular_append: Append a new element with value value to the buffer c.
* Returns: c if the new element could be appended, 0 otherwise.
*/
circular *circular_append(circular *c, double value);
/*
* circular_pop: Remove the oldest element from c and return its value.
* Returns: the removed element if it exists, 0.0 otherwise.
*/
double circular_pop(circular *c);
/*
* circular_element: Return a pointer to position pos in buffer c.
* Returns: a pointer to the pos' element of the buffer, 0 otherwise.
*/
double *circular_element(circular *c, size_t pos);
/*
* circular_init: Initialize a circular buffer c with maximally max_len
* elements. Only use this function on an uninitialized buffer. Each buffer that
* is initialized with this function must be destroyed with a call to
* circular_destroy.
*/
circular *circular_init(circular *c, size_t max_len);
/* circular_destroy: Destroy circular buffer c.
* c must have been initialized with a call to circular_init
*/
void circular_destroy(circular *c);
/* circular_new: Allocate and initialize a circular buffer with maximally len
* elements. Each buffer that is allocated with this function must be deleted
* with a call to circular_delete.
*/
circular *circular_new(size_t len);
/* circular_delete : Delete circular buffer c.
* c must have been allocated with a call to circular_new.
*/
void circular_delete(circular *c);
/*
* circular_resize: Resize to capacity max_len.
*/
circular *circular_resize(circular *c, size_t max_len);
/*
* circular_getlength: Return the number of elements stored.
*/
size_t circular_getlength(circular *c);
/*
* end circular.h
*/
/** @brief the hidden implementation of the circular buffer type */
struct circular {
size_t start; /**< position of element 0 */
size_t len; /**< number of elements stored */
size_t max_len; /**< maximum capacity */
double *tab; /**< array holding the data */
};
/*
* modf
* http://www.cplusplus.com/reference/cmath/modf/
* double modf (double x, double* intpart);
* Break into fractional and integral parts
* Breaks x into an integral and a fractional part.
*
* The integer part is stored in the object pointed by intpart, and the
* fractional part is returned by the function. Both parts have the same sign as
* x.
*
* int main() {
* double param, fractpart, intpart;
* param = 3.14159265;
* fractpart = modf(param, &intpart);
* printf("%f = %f + %f \n", param, intpart, fractpart);
* return 0;
* }
*/
circular *circular_append(circular *c, double value) {
if (c) {
if (c->len == c->max_len) {
return 0;
}
(c->tab)[((c->start) + (c->len)) % (c->max_len)] = value;
(c->len)++;
return c;
}
return 0;
}
double circular_pop(circular *c) {
if (c) {
if (!(c->len)) {
return 0.0;
}
double v = 0.0;
v = (c->tab)[(c->len) - 1];
(c->len)--;
return v;
}
return 0.0;
}
size_t circular_getlength(circular *c) {
if (c) {
return c->len;
}
return 0;
}
void circular_print(circular *c) {
printf("MAX: %lu\n", c->max_len);
printf("LEN: %lu\n", c->len);
printf("SRT: %lu\n", c->start);
printf("TAB: \n");
for (size_t i = 0; i < c->max_len; i++) {
printf("- %02lu: tab: [%06.3f] element at %02lu: [%06.3f]\n", i, c->tab[i],
i, *circular_element(c, i));
}
printf("---\n");
}
bool circular_full(circular *c) {
if (c) {
return (c->len == c->max_len);
}
return false;
}
/*
* new replaces code like:
* size_t ml = 3;
* double *t;
* t = calloc(ml, sizeof(double));
* circular *c = &(circular){
* .max_len = ml,
* .start = 0,
* .len = 0,
* .tab = t,
* };
*/
circular *circular_new(size_t ml) {
circular *c = &(circular){0};
c = circular_init(c, ml);
memset(c->tab, 0.0, ml * sizeof(double));
return c;
}
circular *circular_init(circular *c, size_t max_len) {
if (c) {
if (max_len) {
*c = (circular){
.max_len = max_len,
.tab = malloc(sizeof(double[max_len])),
};
/* allocation failed */
if (!c->tab) {
printf("allocation failed\n");
c->max_len = 0;
}
} else {
/* printf("no max_len to initialize\n"); */
*c = (circular){0};
}
} else {
printf("no circular to initialize\n");
}
return c;
}
void circular_delete(circular *c) {
if (c) {
circular_destroy(c);
c = &(circular){0};
}
}
void circular_destroy(circular *c) {
if (c) {
free(c->tab);
circular_init(c, 0);
}
}
/*
* The implementation of some of the other functions uses an internal function
* to compute the "circular" aspect of the buffer. It is declared static such
* that it is only visible for those functions and such that it doesn't pollute
* the identifier name space,
*/
static size_t circular_getpos(circular *c, size_t pos) {
pos += c->start;
pos %= c->max_len;
return pos;
}
double *circular_element(circular *c, size_t pos) {
double *ret = 0;
if (c) {
if (pos < c->max_len) {
pos = circular_getpos(c, pos);
ret = &c->tab[pos];
}
}
return ret;
}
circular *circular_resize(circular *c, size_t nlen) {
if (c) {
size_t len = c->len;
size_t olen = c->max_len;
if (nlen != olen) {
size_t ostart = circular_getpos(c, 0);
size_t nstart = ostart;
double *otab = c->tab;
double *ntab = 0;
printf("TEST RESIZE");
if (nlen > olen) {
/*
* increasing size
*/
printf(" - INCREASING");
/*
* For this call realloc receives the pointer to the existing object and
* the new size that the relocation should have. It either returns a
* pointer to the new object with the desired size or null. In the line
* immediately after we check the later case and terminate the function
* if it was not possible to relocate the object. The function realloc
* has interesting properties:
* - The returned pointer may or may not be the same as the argument. It
* is left to the discretion of the runtime system to realize if the
* resizing can be performed in place (if there is space available
* behind the object, e.g.) or if a new object must be provided.
* - If the argument pointer and the returned one are distinct (that is
* the object has been copied) nothing has to be done (or even should)
* with the previous pointer, the old object is taken care of.
* - As far as this is possible, existing content of the object is
* preserved:
* -- If the object is enlarged, the initial part of the
* object that corresponds to the previous size is left intact.
* -- If the object shrank, the relocated object has a content that
* corresponds to the initial part before the call.
* - If 0 is returned, that is there location request could not be
* fulfilled by the runtime system, the old object is unchanged. So
* nothing is lost, then.
*
*/
ntab = realloc(c->tab, sizeof(double[nlen]));
if (!ntab) {
return 0;
}
/*
* If previously the situation has been as in the first table, above,
* that is the part that corresponds to the buffer elements is
* contiguous, we have nothing to do. All data is nicely preserved. If
* our circular buffer wrapped around, we have to do some adjustments:
*/
/* two separate chunks. */
bool is_chunked = (ostart + len > olen);
if (is_chunked) {
printf(" - SEPARATE CHUNKS");
size_t ulen = olen - ostart;
size_t llen = len - ulen;
bool is_fitting = llen <= (nlen - olen);
if (is_fitting) {
/*
* copy the lower one up after the old end because the lower
* chunk fits in the difference between the new length and the
* old length (the space we just gained in the resize).
* NAME
* memcpy -- copy memory area
*
* Synopsis
* void *
* memcpy(void *restrict dst, const void *restrict src, size_t n);
*
* Description
* The memcpy() function copies n bytes from memory area src to
* memory area dst. If dst and src overlap, behavior is undefined.
* Applications in which dst and src might overlap should use
* memmove(3) instead.
*
* RETURN VALUES
* The memcpy() function returns the original value of dst.
*/
printf(" - FITTING in the MARGIN (memcpy)\n");
memcpy(ntab + olen, otab, llen * sizeof(double));
} else {
/* if we did not gained enough space in the resize, let's just
* move the upper one up to the new end. The new/next start is
* the new length minus the lenght of the upper chunk. This means
* move the upper chunk again at the bottom of the buffer.
*/
printf(" - NOT FITTING in the MARGIN (memmove)\n");
nstart = nlen - ulen;
/* destination: the new tab + new start, the source the new tab +
* the old start, for all the data that there was from the old max
* length.
* it uses memmove:
*
* void *
* memmove(void *dst, const void *src, size_t len);
*
* Description:
* The memmove() function copies len bytes from string src to
* string dst. The two strings may overlap; the copy is
* always done in a non-destructive manner.
*
* Return Values:
* The memmove() function returns the original value of dst.
*
*/
memmove(ntab + nstart, otab + ostart, ulen * sizeof(double));
}
}
}
if (nlen < olen) {
/*
* shrink size
*/
printf(" - SHRINKING");
/*
* size_t len = c->len;
* size_t olen = c->max_len;
* size_t ostart = circular_getpos(c, 0);
* size_t nstart = ostart;
*
* example:
* |xxxooxxxxx|
* - max_len: 10
* - start: 5
* - length: 8
*
* ostart: 5
* len: 8
* olen: 10
* if ostart + length GT max_len the buffer data is wrapping the end.
* then we want to find the two chunks.
* the upper goes from (max_length - ostart) to max_length;
* the lower goes from 0 to length - upper_start;
*/
int wrapping = ostart + len > olen;
/*
* the old_start + length goes over the old_max_length:
* it's wrapping
*/
if (wrapping) {
/*
* If our circular buffer wrapped around, we have to do some
* adjustments before resizing:
*/
printf(" - WRAPPING");
/* upper chunk length */
size_t ulen = olen - ostart;
/* lower chunk length */
size_t llen = len - ulen;
size_t diff_lost = olen - nlen;
size_t distance_between_chunks = ulen - llen;
if (distance_between_chunks >= diff_lost) {
/* printf("distance between chunks: %lu\n",
* distance_between_chunks); */
}
size_t diff = olen - nlen;
if (ostart >= nlen) {
printf(" - UPDATING THE START");
nstart = ostart - diff;
/* https://en.cppreference.com/w/c/string/byte/memmove
*
* void *memmove(void *dst, const void *src, size_t len);
*/
memcpy(otab + nstart, otab + ostart, ulen * sizeof(double));
} else {
printf(" - KEEPING THE START");
/* the old start is still within the limit of the new length
* but it's necessary to move the rest of the wrapping on the other
* side.
* what remains to be moved or done before is the data is already
* at the previous beginning of the tab and has to be moved forward.
*/
size_t dff = olen - nlen;
if (dff - ostart) {
memcpy(otab + dff, otab, abs((int)dff - (int)ostart) * sizeof(double));
}
/* TODO: +1 does not have a check */
memcpy(otab, otab + ostart + 1, dff * sizeof(double));
}
} else {
printf(" - ONE BLOCK");
}
printf(" - REALLOC\n");
ntab = realloc(c->tab, sizeof(double[nlen]));
if (!ntab) {
printf("cannot reallocate a %lu buffer\n", nlen);
return 0;
} else {
/* printf("new tab of %lu length\n", nlen); */
}
}
*c = (circular){
.max_len = nlen,
.start = nstart,
.len = (len > nlen) ? nlen : len,
.tab = ntab,
};
}
}
return c;
}
/*
* Exercises
*
* - [Exs 26]: Write implementations of the missing functions.
* - [Exs 27]: Implement shrinking of the table: it is important to reorganize
* the table contents before calling realloc.
*
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void circular_append_test(void **state) {
(void)state;
double prec = 0.0001;
/* max_len is 3 */
size_t ml = 3;
circular c_o;
circular *c;
c_o = *(circular_new(ml));
c = &c_o;
assert_non_null(c);
assert_int_equal(0, circular_getlength(c));
assert_true(nearly_equal(0.0, (c->tab)[0], prec));
c = circular_append(c, 1.1);
assert_int_equal(1, circular_getlength(c));
assert_true(nearly_equal(1.1, (c->tab)[0], prec));
c = circular_append(c, 2.2);
assert_int_equal(2, circular_getlength(c));
assert_true(nearly_equal(2.2, (c->tab)[1], prec));
c = circular_append(c, 3.3);
assert_int_equal(3, circular_getlength(c));
assert_true(nearly_equal(3.3, (c->tab)[2], prec));
size_t f = (size_t)circular_append(c, 4.4);
assert_false(f);
circular_delete(c);
/*
* double *t = calloc(ml, sizeof(double));
* circular *c = &(circular){
* .max_len = ml, * capacity is 10 elements
* .start = ((size_t)ml / 2), * the first element is at 5
* .len = 0, * current usage is 0 elements
* .tab = t, * the content of the buffer
* };
*/
ml = 10;
c_o = *(circular_new(ml));
c = &c_o;
assert_true(c);
c = circular_append(c, 5.5);
c = circular_append(c, 6.6);
c = circular_append(c, 7.7);
c = circular_append(c, 8.8);
c = circular_append(c, 9.9);
c = circular_append(c, 10.10);
c = circular_append(c, 11.11);
c = circular_append(c, 12.12);
c = circular_append(c, 13.13);
assert_true((size_t)c);
/* circular_element consider the offset from start) */
assert_true(nearly_equal(5.5, *circular_element(c, 0), prec));
assert_true(nearly_equal(6.6, *circular_element(c, 1), prec));
assert_true(nearly_equal(7.7, *circular_element(c, 2), prec));
/* assert_true(nearly_equal(13.13, *circular_element(c, 8), prec)); */
assert_true(nearly_equal(0.0, *circular_element(c, 9), prec));
c = circular_append(c, 14.14);
f = (size_t)circular_append(c, 15.15);
assert_false(f);
assert_true(nearly_equal(5.5, *circular_element(c, 0), prec));
assert_true(nearly_equal(10.10, c->tab[5], prec));
circular_delete(c);
}
static void circular_pop_test(void **state) {
(void)state;
/* max_len is 3 */
size_t ml = 3;
circular *c = circular_new(ml);
double prec = 0.0001;
assert_non_null(c);
assert_int_equal(0, circular_getlength(c));
double d;
d = circular_pop(c);
assert_true(nearly_equal(0.0, d, prec));
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
assert_int_equal(3, circular_getlength(c));
size_t f = (size_t)circular_append(c, 4.4);
assert_false(f);
d = circular_pop(c);
assert_int_equal(2, circular_getlength(c));
assert_true(nearly_equal(3.3, d, prec));
d = circular_pop(c);
assert_int_equal(1, circular_getlength(c));
assert_true(nearly_equal(2.2, d, prec));
c = circular_append(c, 4.4);
assert_true(c != 0);
assert_true(nearly_equal(3.3, (c->tab)[2], prec));
circular_delete(c);
}
static void circular_getlength_test(void **state) {
(void)state;
/* max_len is 3 */
size_t ml = 3;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
assert_int_equal(0, circular_getlength(c));
c = circular_append(c, 1.1);
assert_int_equal(1, circular_getlength(c));
c = circular_append(c, 2.2);
assert_int_equal(2, circular_getlength(c));
c = circular_append(c, 3.3);
assert_int_equal(3, circular_getlength(c));
double d;
d = circular_pop(c);
assert_int_equal(2, circular_getlength(c));
d = circular_pop(c);
assert_int_equal(1, circular_getlength(c));
d = circular_pop(c);
assert_int_equal(0, circular_getlength(c));
circular_delete(c);
}
static void circular_resize_up_test(void **state) {
(void)state;
size_t ml = 5;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
/*
* - 00: tab: [00.000] element at 00: [00.000]
* - 01: tab: [00.000] element at 01: [00.000]
* - 02: tab: [00.000] element at 02: [00.000]
* - 03: tab: [00.000] element at 03: [00.000]
* - 04: tab: [00.000] element at 04: [00.000]
*/
c->start = 3;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
/*
* circular_print(c);
* - 00: tab: [03.300] element at 00: [01.100]
* - 01: tab: [04.400] element at 01: [02.200]
* - 02: tab: [00.000] element at 02: [03.300]
* - 03: tab: [01.100] element at 03: [04.400]
* - 04: tab: [02.200] element at 04: [00.000]
*/
c = circular_resize(c, 10);
/*
* circular_print(c);
* - 00: tab: [03.300] element at 00: [01.100]
* - 01: tab: [04.400] element at 01: [02.200]
* - 02: tab: [00.000] element at 02: [03.300]
* - 03: tab: [01.100] element at 03: [04.400]
* - 04: tab: [02.200] element at 04: [23178915168015826259279872.000]
* - 05: tab: [03.300] element at 05: [13.130]
* - 06: tab: [04.400] element at 06: [00.000]
* - 07: tab: [23158915168015826259279872.000] element at 07: [03.300]
* - 08: tab: [13.130] element at 08: [04.400]
* - 09: tab: [00.000] element at 09: [00.000]
*/
double prec = 0.0001;
assert_int_equal(4, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[3], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[4], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[5], prec));
assert_true(nearly_equal(4.4, *circular_element(c, 3), prec));
assert_true(nearly_equal(4.4, c->tab[6], prec));
c = circular_append(c, 5.5);
assert_true(nearly_equal(5.5, *circular_element(c, 4), prec));
assert_true(nearly_equal(5.5, c->tab[7], prec));
circular_delete(c);
}
static void circular_resize_down_test_0(void **state) {
(void)state;
size_t ml = 10;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 8;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_resize(c, 5);
double prec = 0.0001;
assert_int_equal(4, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[3], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[4], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[0], prec));
assert_true(nearly_equal(4.4, *circular_element(c, 3), prec));
assert_true(nearly_equal(4.4, c->tab[1], prec));
c = circular_append(c, 5.5);
assert_true(nearly_equal(5.5, *circular_element(c, 4), prec));
assert_true(nearly_equal(5.5, c->tab[2], prec));
circular_delete(c);
}
static void circular_resize_down_test_1(void **state) {
(void)state;
size_t ml = 5;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 0;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_resize(c, 3);
double prec = 0.0001;
assert_int_equal(3, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[0], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[1], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[2], prec));
bool success;
success = (bool)circular_append(c, 5.5);
assert_true(circular_full(c));
assert_false(success);
circular_delete(c);
}
static void circular_resize_down_test_2(void **state) {
(void)state;
size_t ml = 5;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 3;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_resize(c, 3);
double prec = 0.0001;
assert_int_equal(3, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[1], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[2], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[0], prec));
bool success;
success = (bool)circular_append(c, 5.5);
assert_true(circular_full(c));
assert_false(success);
circular_delete(c);
}
static void circular_resize_down_test_3(void **state) {
(void)state;
size_t ml = 5;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 0;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_resize(c, 3);
double prec = 0.0001;
assert_int_equal(3, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[0], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[1], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[2], prec));
bool success;
success = (bool)circular_append(c, 5.5);
assert_true(circular_full(c));
assert_false(success);
circular_delete(c);
}
static void circular_resize_down_test_4(void **state) {
(void)state;
size_t ml = 5;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 2;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_resize(c, 3);
double prec = 0.0001;
assert_int_equal(3, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[2], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[0], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[1], prec));
bool success;
success = (bool)circular_append(c, 5.5);
assert_true(circular_full(c));
assert_false(success);
circular_delete(c);
}
static void circular_resize_down_test_5(void **state) {
(void)state;
size_t ml = 6;
circular c_o = *circular_new(ml);
circular *c = &c_o;
assert_non_null(c);
c->start = 3;
c->len = 0;
c = circular_append(c, 1.1);
c = circular_append(c, 2.2);
c = circular_append(c, 3.3);
c = circular_append(c, 4.4);
c = circular_append(c, 5.5);
c = circular_append(c, 6.6);
c = circular_resize(c, 4);
double prec = 0.0001;
assert_int_equal(4, circular_getlength(c));
assert_true(nearly_equal(1.1, *circular_element(c, 0), prec));
assert_true(nearly_equal(1.1, c->tab[3], prec));
assert_true(nearly_equal(2.2, *circular_element(c, 1), prec));
assert_true(nearly_equal(2.2, c->tab[4], prec));
assert_true(nearly_equal(3.3, *circular_element(c, 2), prec));
assert_true(nearly_equal(3.3, c->tab[5], prec));
assert_true(nearly_equal(4.4, *circular_element(c, 3), prec));
assert_true(nearly_equal(4.4, c->tab[2], prec));
bool success;
success = (bool)circular_append(c, 5.5);
assert_true(circular_full(c));
assert_false(success);
circular_delete(c);
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(circular_append_test),
cmocka_unit_test(circular_pop_test),
cmocka_unit_test(circular_getlength_test),
cmocka_unit_test(circular_resize_up_test),
cmocka_unit_test(circular_resize_down_test_0),
cmocka_unit_test(circular_resize_down_test_1),
cmocka_unit_test(circular_resize_down_test_2),
cmocka_unit_test(circular_resize_down_test_3),
cmocka_unit_test(circular_resize_down_test_4),
cmocka_unit_test(circular_resize_down_test_5),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#ifndef ALL_YOUR_BASE_H
#define ALL_YOUR_BASE_H
#define DIGITS_ARRAY_SIZE 64
#include <stdlib.h>
size_t rebase(int8_t digits[], int16_t input_base, int16_t output_base, size_t input_length);
#endif
<file_sep>/*
* URLr - based on libcURL
* https://curl.haxx.se/libcurl/
* https://curl.haxx.se/libcurl/c/
*
* http://xmlsoft.org/index.html
* http://tidy.sourceforge.net
* https://github.com/htacg/tidy-html5
* https://github.com/google/gumbo-parser
* https://libexpat.github.io/
* https://github.com/arjunc77/htmlstreamparser
*
* https://github.com/curl/curl/raw/master/docs/examples/crawler.c
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/href_extractor.c
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/getinmemory.c
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/https.c
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/multithread.c
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/htmltidy.c
* http://xmlsoft.org/examples/index.html
* http://xmlsoft.org/examples/parse1.c
* http://xmlsoft.org/examples/parse2.c
* http://xmlsoft.org/examples/parse3.c
* http://xmlsoft.org/examples/parse4.c
* gcc -Wall -o ~/Downloads/a.out ~/workspaces/pebbles/sample_libxml.c
* $(xml2-config --cflags --libs)
*
* For compilers to find libxml2 you may need to set:
* export LDFLAGS="-L/usr/local/opt/libxml2/lib"
* export CPPFLAGS="-I/usr/local/opt/libxml2/include"
*
* For pkg-config to find libxml2 you may need to set:
* export PKG_CONFIG_PATH="/usr/local/opt/libxml2/lib/pkgconfig"
*
* PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl tidy)
* -I/usr/local/Cellar/tidy-html5/5.6.0/include
* -L/usr/local/Cellar/tidy-html5/5.6.0/lib -lcurl -ltidy
*
* LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
* $ /usr/local/opt/libxml2/bin/xml2-config --cflags
* -I/usr/local/Cellar/libxml2/2.9.7/include/libxml2
* $ /usr/local/opt/libxml2/bin/xml2-config --libs
* -L/usr/local/Cellar/libxml2/2.9.7/lib -lxml2 -lz -lpthread -liconv -lm
*
*
*/
/* Parameters */
int max_con = 200;
int max_total = 20000;
int max_requests = 500;
int max_link_per_page = 5;
int follow_relative_links = 0;
char *start_page = "https://www.example.org";
#include <ctype.h>
#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libxml/HTMLparser.h>
#include <libxml/uri.h>
#include <libxml/xpath.h>
/*
* https://github.com/curl/curl/pull/3050
* https://github.com/curl/curl/blob/master/docs/examples/htmltidy.c
*/
#include <tidy.h>
#include <tidybuffio.h>
/* curl write callback, to fill tidy's input buffer...
*
* CURLOPT_WRITEFUNCTION explained
* CURLOPT_WRITEFUNCTION - set callback for writing received data
*
* SYNOPSIS
* #include <curl/curl.h>
*
* size_t write_callback(char *ptr, size_t size, size_t nmemb, void
* *userdata);
*
* CURLcode curl_easy_setopt(CURL *handle, CURLOPT_WRITEFUNCTION,
* write_callback);
*
* DESCRIPTION
* Pass a pointer to your callback function, which should match the
* prototype shown above.
*
* This callback function gets called by libcurl as soon as there is
* data received that needs to be saved. ptr points to the delivered
* data, and the size of that data is nmemb; size is always 1.
*
* The callback function will be passed as much data as possible in all
* invokes, but you must not make any assumptions.
*
*/
uint write_callback(char *in, uint size, uint nmemb, TidyBuffer *out) {
uint r;
r = size * nmemb;
tidyBufAppend(out, in, r);
return r;
}
/*
* Uses the "Streaming HTML parser" to extract the href pieces in a streaming
* manner from a downloaded HTML.
*
* The HTML parser is found at https://github.com/arjunc77/htmlstreamparser
* https://github.com/doronbehar/curl/blob/ce3c5d66a9a7843398dc4f2464a50f35a5f22336/docs/examples/href_extractor.c
*/
/*
* static size_t parse_callback(void *buffer, size_t size, size_t nmemb,
* void *hsp) {
* size_t realsize = size * nmemb, p;
* for (p = 0; p < realsize; p++) {
* html_parser_char_parse(hsp, ((char *)buffer)[p]);
* if (html_parser_cmp_tag(hsp, "a", 1))
* if (html_parser_cmp_attr(hsp, "href", 4))
* if (html_parser_is_in(hsp, HTML_VALUE_ENDED)) {
* html_parser_val(hsp)[html_parser_val_length(hsp)] = '\0';
* printf("%s\n", html_parser_val(hsp));
* }
* }
* return realsize;
* }
*/
/*
* Tidy HTML traverse
*
* http://api.html-tidy.org/tidy/tidylib_api_5.6.0/modules.html
* https://github.com/htacg/tidy-html5/tree/master/README
* http://api.html-tidy.org
*
* Traverse the document tree
*/
void dumpNode(TidyDoc doc, TidyNode tnod, int indent) {
TidyNode child;
for (child = tidyGetChild(tnod); child; child = tidyGetNext(child)) {
ctmbstr name = tidyNodeGetName(child);
if (name) {
/* if it has a name, then it's an HTML tag ... */
TidyAttr attr;
printf("%*.*s%s ", indent, indent, "<", name);
/* walk the attribute list */
for (attr = tidyAttrFirst(child); attr; attr = tidyAttrNext(attr)) {
printf("%s", tidyAttrName(attr));
tidyAttrValue(attr) ? printf("=\"%s\" ", tidyAttrValue(attr))
: printf(" ");
}
printf(">\n");
} else {
/* if it doesn't have a name, then it's probably text, cdata, etc... */
TidyBuffer buf;
tidyBufInit(&buf);
tidyNodeGetText(doc, child, &buf);
printf("%*.*s\n", indent, indent, buf.bp ? (char *)buf.bp : "");
tidyBufFree(&buf);
}
dumpNode(doc, child, indent + 4); /* recursive */
}
}
/* resizable buffer */
typedef struct {
char *buf;
size_t size;
} memory;
size_t grow_buffer(void *contents, size_t sz, size_t nmemb, void *ctx) {
size_t realsize = sz * nmemb;
memory *mem = (memory *)ctx;
char *ptr = realloc(mem->buf, mem->size + realsize);
if (!ptr) {
/* out of memory */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->buf = ptr;
memcpy(&(mem->buf[mem->size]), contents, realsize);
mem->size += realsize;
return realsize;
}
CURL *make_handle(char *url) {
CURL *handle = curl_easy_init();
/* Important: use HTTP2 over HTTPS */
curl_easy_setopt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
curl_easy_setopt(handle, CURLOPT_URL, url);
/* buffer body */
memory *mem = malloc(sizeof(memory));
mem->size = 0;
mem->buf = malloc(1);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, grow_buffer);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, mem);
curl_easy_setopt(handle, CURLOPT_PRIVATE, mem);
/* For completeness */
curl_easy_setopt(handle, CURLOPT_ENCODING, "gzip, deflate");
curl_easy_setopt(handle, CURLOPT_TIMEOUT, 5L);
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 10L);
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 2L);
curl_easy_setopt(handle, CURLOPT_COOKIEFILE, "");
curl_easy_setopt(handle, CURLOPT_FILETIME, 1L);
curl_easy_setopt(handle, CURLOPT_USERAGENT, "mini crawler");
curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_easy_setopt(handle, CURLOPT_UNRESTRICTED_AUTH, 1L);
curl_easy_setopt(handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
curl_easy_setopt(handle, CURLOPT_EXPECT_100_TIMEOUT_MS, 0L);
return handle;
}
int config_curl(CURL *curl, char *url, char curl_errbuf[]) {
/* CURLOPT_URL - provide the URL to use in the request */
curl_easy_setopt(curl, CURLOPT_URL, url);
/* if the URL is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/* CURLOPT_ERRORBUFFER - set error buffer for error messages */
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf);
/* CURLOPT_NOPROGRESS - with 1 switch off the progress meter */
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
/* CURLOPT_VERBOSE - set verbose mode on/off */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);
/* CURLOPT_WRITEFUNCTION - set callback for writing received data */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
return 0;
}
/* HREF finder implemented in libxml2 but could be any HTML parser
*
* Web crawler based on curl and libxml2 to stress-test curl with
* hundreds of concurrent connections to various servers.
* https://github.com/doronbehar/curl/blob/ce3c5d66a9a7843398dc4f2464a50f35a5f22336/docs/examples/crawler.c
*/
/*
* size_t follow_links(CURLM *multi_handle, memory *mem, char *url) {
* int opts = HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING
* | HTML_PARSE_NONET; htmlDocPtr doc = htmlReadMemory(mem->buf, mem->size, url,
* NULL, opts); if (!doc) return 0; xmlChar *xpath = (xmlChar *)"//a/@href";
* xmlXPathContextPtr context = xmlXPathNewContext(doc);
* xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context);
* xmlXPathFreeContext(context);
* if (!result)
* return 0;
* xmlNodeSetPtr nodeset = result->nodesetval;
* if (xmlXPathNodeSetIsEmpty(nodeset)) {
* xmlXPathFreeObject(result);
* return 0;
* }
* size_t count = 0;
* for (int i = 0; i < nodeset->nodeNr; i++) {
* double r = rand();
* int x = r * nodeset->nodeNr / RAND_MAX;
* const xmlNode *node = nodeset->nodeTab[x]->xmlChildrenNode;
* xmlChar *href = xmlNodeListGetString(doc, node, 1);
* if (follow_relative_links) {
* xmlChar *orig = href;
* href = xmlBuildURI(href, (xmlChar *)url);
* xmlFree(orig);
* }
* char *link = (char *)href;
* if (!link || strlen(link) < 20)
* continue;
* if (!strncmp(link, "http://", 7) || !strncmp(link, "https://", 8)) {
* curl_multi_add_handle(multi_handle, make_handle(link));
* if (count++ == max_link_per_page)
* break;
* }
* xmlFree(link);
* }
* xmlXPathFreeObject(result);
* return count;
* }
*/
/* HTMLTIDY configuration:
* http://api.html-tidy.org/tidy/tidylib_api_5.2.0/tidy_8h.html
* https://github.com/htacg/tidy-html5
*/
int config_tidy(CURL *curl, TidyDoc tdoc, TidyBuffer *docbuf,
TidyBuffer *tidy_errbuf) {
tidyOptSetBool(tdoc, TidyForceOutput, yes);
tidyOptSetInt(tdoc, TidyWrapLen, 4096);
tidyBufInit(tidy_errbuf);
tidySetErrorBuffer(tdoc, tidy_errbuf);
tidyBufInit(docbuf);
/* CURLOPT_WRITEDATA - custom pointer passed to the write callback */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, docbuf);
return 0;
}
/* TODO: add meaningful error codes. */
int config(CURL *curl, char *url, char curl_errbuf[], TidyDoc *tdoc,
TidyBuffer *tidy_errbuf, TidyBuffer *docbuf) {
config_tidy(curl, *tdoc, docbuf, tidy_errbuf);
config_curl(curl, url, curl_errbuf);
return 0;
}
/*
* Download a document and use libtidy to parse the HTML.
*
* LibTidy => https://www.html-tidy.org/
*/
int tidy(char *url) {
CURL *curl;
char curl_errbuf[CURL_ERROR_SIZE];
TidyDoc tdoc = {0};
TidyBuffer docbuf = {0};
TidyBuffer tidy_errbuf = {0};
int conf_err = 0;
int curl_err = 0;
curl = curl_easy_init();
if (!curl) {
fprintf(stderr, "cannot create a cURL handler\n");
return EXIT_FAILURE;
}
tdoc = tidyCreate();
if (tdoc == NULL) {
fprintf(stderr, "cannot create a TidyDoc\n");
curl_easy_cleanup(curl);
return EXIT_FAILURE;
}
conf_err = config(curl, url, curl_errbuf, &tdoc, &tidy_errbuf, &docbuf);
if (conf_err) {
fprintf(stderr, "cannot configure cURL and TidyDoc!\n");
curl_easy_cleanup(curl);
tidyBufFree(&docbuf);
tidyBufFree(&tidy_errbuf);
tidyRelease(tdoc);
return EXIT_FAILURE;
}
/*
* curl_easy_perform - perform a blocking file transfer
*
* https://curl.haxx.se/libcurl/c/curl_easy_perform.html
*
* #include <curl/curl.h>
* CURLcode curl_easy_perform(CURL * easy_handle );
*
* Invoke this function after curl_easy_init and all the curl_easy_setopt
* calls are made, and will perform the transfer as described in the options.
* It must be called with the same easy_handle as input as the curl_easy_init
* call returned.
*
* curl_easy_perform performs the entire request in a blocking manner and
* returns when done, or if it failed. For non-blocking behavior, see
* curl_multi_perform.
*
* You can do any amount of calls to curl_easy_perform while using the same
* easy_handle. If you intend to transfer more than one file, you are even
* encouraged to do so. libcurl will then attempt to re-use the same
* connection for the following transfers, thus making the operations faster,
* less CPU intense and using less network resources. Just note that you will
* have to use curl_easy_setopt between the invokes to set options for the
* following curl_easy_perform.
*
* You must never call this function simultaneously from two places using the
* same easy_handle. Let the function return first before invoking it another
* time. If you want parallel transfers, you must use several curl
* easy_handles.
*
* While the easy_handle is added to a multi handle, it cannot be used by
* curl_easy_perform.
*
* Return value
* CURLE_OK (0) means everything was ok, non-zero means an error occurred as
* <curl/curl.h> defines - see libcurl-errors. If the CURLOPT_ERRORBUFFER was
* set with curl_easy_setopt there will be a readable error message in the
* error buffer when non-zero is returned.
*/
curl_err = curl_easy_perform(curl);
/* Check for errors */
if (curl_err != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(curl_err));
} else {
/* https://curl.haxx.se/libcurl/c/libcurl-errors.html */
fprintf(stdout, "curl_easy_perform() success: %d\n", curl_err);
/* parse the input
*
* http://api.html-tidy.org/tidy/tidylib_api_5.6.0/group__Parse.html
*
* int TIDY_CALL tidyParseBuffer(TidyDoc tdoc, TidyBuffer * buf)
*
* Parse markup in given buffer.
* Returns the highest of 2 indicating that errors were present in the
* document, 1 indicating warnings, and 0 in the case of everything being
* okay.
* Parameters
* tdoc: The tidy document to use for parsing.
* buf: The TidyBuffer containing data to parse.
*/
int tidy_err = 0;
tidy_err = tidyParseBuffer(tdoc, &docbuf);
if (tidy_err >= 0) {
tidy_err = tidyCleanAndRepair(tdoc);
if (tidy_err > 0) {
/* load tidy error buffer */
tidy_err = tidyRunDiagnostics(tdoc);
if (tidy_err > 0) {
/* walk the tree */
dumpNode(tdoc, tidyGetRoot(tdoc), 0);
/* show errors */
fprintf(stderr, "%s\n", tidy_errbuf.bp);
}
}
}
}
/* clean-up */
curl_easy_cleanup(curl);
tidyBufFree(&docbuf);
tidyBufFree(&tidy_errbuf);
tidyRelease(tdoc);
return curl_err;
}
int parse(char *url) {
CURL *curl;
/* HTMLSTREAMPARSER *hsp; */
int curl_err = 0;
curl = curl_easy_init();
if (!curl) {
fprintf(stderr, "cannot create a cURL handler\n");
return EXIT_FAILURE;
}
/*
* hsp = html_parser_init();
* html_parser_set_tag_to_lower(hsp, 1);
* html_parser_set_attr_to_lower(hsp, 1);
* html_parser_set_tag_buffer(hsp, tag, sizeof(tag));
* html_parser_set_attr_buffer(hsp, attr, sizeof(attr));
* html_parser_set_val_buffer(hsp, val, sizeof(val) - 1);
*/
curl_easy_setopt(curl, CURLOPT_URL, url);
/* curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, parse_callback); */
/* curl_easy_setopt(curl, CURLOPT_WRITEDATA, hsp); */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_err = curl_easy_perform(curl);
if (curl_err != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(curl_err));
} else {
/* https://curl.haxx.se/libcurl/c/libcurl-errors.html */
fprintf(stdout, "curl_easy_perform() success: %d\n", curl_err);
}
curl_easy_cleanup(curl);
/* html_parser_cleanup(hsp); */
return curl_err;
}
int main(int argc, char **argv) {
int aflag = 0;
int tflag = 0;
char *url = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "atu:")) != -1)
switch (c) {
case 'a':
aflag = 1;
break;
case 't':
tflag = 1;
break;
case 'u':
url = optarg;
break;
case '?':
if (optopt == 'u')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
abort();
}
printf("aflag = %d, tflag = %d, URL = %s\n", aflag, tflag, url);
for (index = optind; index < argc; index++) {
printf("Non-option argument %s\n", argv[index]);
}
if (url == NULL) {
url = "https://www.example.org";
}
int ret = 0;
if (tflag == 1) {
ret = tidy(url);
} else {
ret = parse(url);
}
printf("quitting with %d\n", ret);
return ret;
}
<file_sep>#include <stdlib.h>
#include "sieve.h"
/*
* #define MAX_LIMIT_TESTED (1000)
* typedef unsigned int primes_array_t[MAX_LIMIT_TESTED];
*/
unsigned int sieve(const unsigned int limit, primes_array_t primes) {
if (limit < 2)
return 0;
char *sieve = calloc(limit + 1, sizeof(int));
unsigned int i = 0, j = 0;
for (i = 2; i <= limit; i++) {
sieve[i] = 1;
}
unsigned int r = 0;
for (i = 2; i <= limit; i++) {
if (sieve[i] == 1) {
primes[r++] = i;
/* marking as non-prime all the numbers from here, until the limit
* that have i as factor, so, all the numbers that are results of
* (i * j).
*/
for (j = i; (i * j) <= limit; j++) {
sieve[(i * j)] = 0;
}
}
}
return r;
}
<file_sep>/* Snail
* cURL and libXML2.
*
* http://xmlsoft.org/html/libxml-lib.html
* https://www.w3.org/TR/2017/REC-xpath-31-20170321/
* http://xmlsoft.org/tutorial/index.html
* http://xmlsoft.org/tutorial/xmltutorial.pdf
*/
/* -------------------------------- TODO/DONE ------------------------------- */
/* TODO:
*
* - [x] extract inner links for comment (HN only);
* - [x] clear trailing and leading spaces;
* - [ ] parse HN specifically (add source and source search link);
* - [x] add long option for HN;
* - [ ] add "ASK/SHOW" text (HN only);
* - [ ] print links in bold;
* - [ ] print only in the main function;
* - [ ] add ncurses for bold;
* - [ ] add option to copy the output directly to the system clipboard;
*/
/* -------------------------------- references ------------------------------ */
/*
* http://xmlsoft.org/examples/index.html
* http://xmlsoft.org/examples/parse1.c
* http://xmlsoft.org/examples/parse2.c
* http://xmlsoft.org/examples/parse3.c
* http://xmlsoft.org/examples/parse4.c
* https://github.com/curl/curl/tree/master/docs/examples
* https://raw.githubusercontent.com/curl/curl/master/docs/examples/crawler.c
*/
/* -------------------------------- buildme --------------------------------- */
/*
* For compilers to find libxml2 you may need to set:
* export LDFLAGS="-L/usr/local/opt/libxml2/lib"
* export CPPFLAGS="-I/usr/local/opt/libxml2/include"
*
* For pkg-config to find libxml2 you may need to set:
* export PKG_CONFIG_PATH="/usr/local/opt/libxml2/lib/pkgconfig"
*
* PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl tidy)
* -I/usr/local/Cellar/tidy-html5/5.6.0/include
* -L/usr/local/Cellar/tidy-html5/5.6.0/lib -lcurl -ltidy
*
* LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
* $ /usr/local/opt/libxml2/bin/xml2-config --cflags
* -I/usr/local/Cellar/libxml2/2.9.7/include/libxml2
* $ /usr/local/opt/libxml2/bin/xml2-config --libs
* -L/usr/local/Cellar/libxml2/2.9.7/lib -lxml2 -lz -lpthread -liconv -lm
*
*/
/* -------------------------------- debug ----------------------------------- */
/* Turn debugging messages on/off. */
#ifdef DEBUG
#define debugf(...) \
do { \
printf("%s:%s:%d:\t", __FILE__, __FUNCTION__, __LINE__); \
printf(__VA_ARGS__); \
fflush(stdout); \
} while (0);
#else
#define debugf(...) \
do { \
} while (0);
#endif
/* -------------------------------- imports --------------------------------- */
/* http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/
* http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/attrib.html
*/
#include <ncurses.h>
/* https://curl.haxx.se/libcurl/c/ */
#include <curl/curl.h>
/* http://xmlsoft.org/html/libxml-HTMLparser.html */
#include <libxml/HTMLparser.h>
/* http://xmlsoft.org/html/libxml-parser.html */
#include <libxml/parser.h>
/* http://xmlsoft.org/html/libxml-tree.html */
#include <libxml/tree.h>
/* http://xmlsoft.org/html/libxml-uri.html */
#include <libxml/uri.h>
/* http://xmlsoft.org/html/libxml-xpath.html */
#include <libxml/xpath.h>
/* https://www.gnu.org/software/libc/manual/html_node/Getopt.html */
#include <getopt.h>
#include <ctype.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* https://ptolemy.berkeley.edu/~johnr/tutorials/assertions.html */
/* https://en.cppreference.com/w/c/error/assert */
/* uncomment to disable assert() */
/* #define NDEBUG */
#include <assert.h>
/* -------------------------------- parameters ------------------------------ */
int max_con = 200;
int max_total = 20000;
int max_requests = 500;
size_t max_link_per_page = 5;
int limited = 0;
int follow_relative_links = 0;
char *start_page = "https://www.reuters.com";
char *hackernews = "https://news.ycombinator.com";
char *XPATH_HYPERLINKS_TEXT_AND_HREF = "//a/text()|//a/@href";
char *XPATH_HYPERLINKS = "//a";
/* -------------------------------- structs --------------------------------- */
/* memory: resizable buffer
*
* used as CURLOPT_WRITEDATA
* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEDATA.html
*
* NAME
* CURLOPT_WRITEDATA - custom pointer passed to the write callback
*
* SYNOPSIS
* #include <curl/curl.h>
* CURLcode curl_easy_setopt(CURL *handle, CURLOPT_WRITEDATA, void *pointer);
*
* DESCRIPTION
* A data pointer to pass to the write callback. If you use the
* CURLOPT_WRITEFUNCTION option, this is the pointer you'll get in that
* callback's 4th argument. If you don't use a write callback, you must make
* pointer a 'FILE *' (cast to 'void *') as libcurl will pass this to fwrite(3)
* when writing data.
*
* The internal CURLOPT_WRITEFUNCTION will write the data to the FILE * given
* with this option, or to stdout if this option hasn't been set.
*
* If you're using libcurl as a win32 DLL, you MUST use a CURLOPT_WRITEFUNCTION
* if you set this option or you will experience crashes.
*
* DEFAULT
* By default, this is a FILE * to stdout.
*
* EXAMPLE
* A common technique is to use the write callback to store the incoming data
* into a dynamically growing allocated buffer, and then this CURLOPT_WRITEDATA
* is used to point to a struct or the buffer to store data in. Like in the
* getinmemory example: https://curl.haxx.se/libcurl/c/getinmemory.html
*/
typedef struct {
char *buf;
size_t size;
} memory;
/* -------------------------------- helpers --------------------------------- */
/* Note: This function returns a pointer to a substring of the original string.
* If the given string was allocated dynamically, the caller must not overwrite
* that pointer with the returned value, since the original pointer must be
* deallocated using the same allocator with which it was allocated. The return
* value must NOT be deallocated using free() etc.
*/
char *trim_whitespace(char *str) {
if (str == NULL) {
return str;
}
char *end;
// Trim leading space
while (isspace((unsigned char)*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end))
end--;
// Write new null terminator character
end[1] = '\0';
return str;
}
int is_html(char *ctype) {
return ctype != NULL && strlen(ctype) > 10 && strstr(ctype, "text/html");
}
int ends_with(const char *str, const char *suffix) {
if (!str || !suffix)
return 0;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
return 0;
return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
int has_no_comments(const char *str) {
return !strncmp((char *)str, "discuss", 7);
}
int ends_with_comment(const char *str) { return ends_with(str, "comment"); }
int ends_with_comments(const char *str) { return ends_with(str, "comments"); }
int is_comment(char *text) {
if (!text) {
return 0;
}
return has_no_comments((char *)text) || ends_with_comment((char *)text) ||
ends_with_comments((char *)text);
}
/*
* Function: xmlBuildURI
* http://xmlsoft.org/html/libxml-uri.html#xmlBuildURI
*
* xmlChar *xmlBuildURI (const xmlChar * URI, const xmlChar * base)
*
* Computes he final URI of the reference done by checking that the given URI is
* valid, and building the final URI using the base URI. This is processed
* according to section 5.2 of the RFC 2396 5.2. Resolving Relative References
* to Absolute Form
*
* URI: the URI instance found in the document
* base: the base value
* Returns: a new URI string (to be freed by the caller) or NULL in case
* of error.
*
* Function: xmlCharStrdup
* http://xmlsoft.org/html/libxml-xmlstring.html#xmlCharStrdup
*
* xmlChar *xmlCharStrdup (const char * cur)
*
* a strdup for char's to xmlChar's
*
* cur: the input char *
* Returns: a new xmlChar * or NULL
*/
void link_relative_expand(xmlChar **href_ptr, char *url) {
/*
* this is what is about to happen with the pointers:
* HREF BEFORE: 0x7fd791c82900, https://news.ycombinator.com
* HREF 0x7ffeed854770 - 0x7fd791c82900
* ORIG 0x7fd791c82900
* RES 0x7fd791c83be0
* HREF 0x7ffeed854770 - 0x7fd791c83be0
* HREF AFTER: 0x7fd791c83be0, https://news.ycombinator.com
*/
debugf("HREF %p - %p\n", href_ptr, *href_ptr);
/* `*orig` is the pointer where `**href_ptr` is pointing to */
xmlChar *orig = *href_ptr;
debugf("ORIG %p\n", orig);
xmlChar *dup = xmlCharStrdup(url);
xmlChar *res = xmlBuildURI(*href_ptr, dup);
debugf("RES %p\n", res);
/* updating the value that href_ptr is pointing to
* without changing href_ptr itself
*/
*href_ptr = res;
debugf("HREF %p - %p\n", href_ptr, *href_ptr);
xmlFree(dup);
xmlFree(orig);
}
/* used as CURLOPT_WRITEFUNCTION:
* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
*
* NAME
* CURLOPT_WRITEFUNCTION - set callback for writing received data
*
* SYNOPSIS
* #include <curl/curl.h>
* size_t write_callback(char *ptr,
* size_t size,
* size_t nmemb,
* void *userdata);
* CURLcode curl_easy_setopt(CURL *handle,
* CURLOPT_WRITEFUNCTION,
* write_callback);
*
* DESCRIPTION
* Pass a pointer to your callback function, which should match the prototype
* shown above.
*
* This callback function gets called by libcurl as soon as there is data
* received that needs to be saved. ptr points to the delivered data, and the
* size of that data is nmemb; size is always 1.
*
* The callback function will be passed as much data as possible in all invokes,
* but you must not make any assumptions. It may be one byte, it may be
* thousands. The maximum amount of body data that will be passed to the write
* callback is defined in the curl.h header file: CURL_MAX_WRITE_SIZE (the usual
* default is 16K). If CURLOPT_HEADER is enabled, which makes header data get
* passed to the write callback, you can get up to CURL_MAX_HTTP_HEADER bytes of
* header data passed into it. This usually means 100K.
*
* This function may be called with zero bytes data if the transferred file is
* empty.
*
* The data passed to this function will not be zero terminated!
*
* Set the userdata argument with the CURLOPT_WRITEDATA option.
* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEDATA.html
*
* Your callback should return the number of bytes actually taken care of. If
* that amount differs from the amount passed to your callback function, it'll
* signal an error condition to the library. This will cause the transfer to get
* aborted and the libcurl function used will return CURLE_WRITE_ERROR.
*
* If your callback function returns CURL_WRITEFUNC_PAUSE it will cause this
* transfer to become paused. See curl_easy_pause for further details.
*
* Set this option to NULL to get the internal default function used instead of
* your callback. The internal default function will write the data to the FILE
* * given with CURLOPT_WRITEDATA.
*
* DEFAULT
* libcurl will use 'fwrite' as a callback by default.
*
*/
size_t grow_buffer(void *contents, size_t sz, size_t nmemb, void *ctx) {
/* This callback function gets called by libcurl as soon as there is data
* received that needs to be saved.
* - `contents` points to the delivered data;
* - `nmemb` is the size of the data;
* - `sz` is always 1;
* - `ctx` is the destination;
*/
size_t realsize = sz * nmemb;
memory *mem = (memory *)ctx;
char *ptr = realloc(mem->buf, mem->size + realsize);
if (!ptr) {
/* out of memory */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->buf = ptr;
memcpy(&(mem->buf[mem->size]), contents, realsize);
mem->size += realsize;
return realsize;
}
CURL *snail_crawl_make_handle(char *url) {
CURL *handle = curl_easy_init();
/* Important: use HTTP2 over HTTPS */
curl_easy_setopt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
curl_easy_setopt(handle, CURLOPT_URL, url);
/* buffer body */
memory *mem = malloc(sizeof(memory));
mem->size = 0;
mem->buf = malloc(1);
/* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html */
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, grow_buffer);
/* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEDATA.html */
curl_easy_setopt(handle, CURLOPT_WRITEDATA, mem);
curl_easy_setopt(handle, CURLOPT_PRIVATE, mem);
/* For completeness */
curl_easy_setopt(handle, CURLOPT_ENCODING, "gzip, deflate");
curl_easy_setopt(handle, CURLOPT_TIMEOUT, 5L);
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 10L);
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 2L);
curl_easy_setopt(handle, CURLOPT_COOKIEFILE, "");
curl_easy_setopt(handle, CURLOPT_FILETIME, 1L);
curl_easy_setopt(handle, CURLOPT_USERAGENT, "mini crawler");
curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_easy_setopt(handle, CURLOPT_UNRESTRICTED_AUTH, 1L);
curl_easy_setopt(handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
curl_easy_setopt(handle, CURLOPT_EXPECT_100_TIMEOUT_MS, 0L);
return handle;
}
/* -------------------------------- functions ------------------------------- */
size_t snail_crawl_follow_links(CURLM *multi_handle, memory *mem, char *url) {
int opts = HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING |
HTML_PARSE_NONET;
htmlDocPtr doc = htmlReadMemory(mem->buf, mem->size, url, NULL, opts);
if (!doc) {
return 0;
}
xmlChar *xpath = (xmlChar *)"//a/@href";
xmlXPathContextPtr context = xmlXPathNewContext(doc);
xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
if (!result) {
return 0;
}
xmlNodeSetPtr nodeset = result->nodesetval;
if (xmlXPathNodeSetIsEmpty(nodeset)) {
xmlXPathFreeObject(result);
return 0;
}
size_t count = 0;
for (int i = 0; i < nodeset->nodeNr; i++) {
double r = rand();
int x = r * nodeset->nodeNr / RAND_MAX;
const xmlNode *node = nodeset->nodeTab[x]->xmlChildrenNode;
xmlChar *href = xmlNodeListGetString(doc, node, 1);
if (follow_relative_links) {
xmlChar *orig = href;
href = xmlBuildURI(href, (xmlChar *)url);
xmlFree(orig);
}
char *link = (char *)href;
if (!link || strlen(link) < 20) {
continue;
}
if (!strncmp(link, "http://", 7) || !strncmp(link, "https://", 8)) {
curl_multi_add_handle(multi_handle, snail_crawl_make_handle(link));
if (count++ == max_link_per_page)
break;
}
xmlFree(link);
}
xmlXPathFreeObject(result);
return count;
}
/**
* snail_html_parse
* @content: the content of the document
* @length: the length in bytes
*
* Parse the in memory document and free the resulting tree
*
* http://xmlsoft.org/html/libxml-HTMLparser.html#htmlCtxtReadMemory
*
* htmlDocPtr htmlCtxtReadMemory (htmlParserCtxtPtr ctxt,
* const char * buffer,
* int size,
* const char * URL,
* const char * encoding,
* int options)
*
* parse an XML in-memory document and build a tree. This reuses the existing
* @ctxt parser context
*
* ctxt: an HTML parser context
* buffer: a pointer to a char array
* size: the size of the array
* URL: the base URL to use for the document
* encoding: the document encoding, or NULL
* options: a combination of htmlParserOption(s)
* Returns: the resulting document tree
*/
void snail_html_parse(const char *content, int length, char *url) {
assert(url);
assert(content);
assert(length > 0);
char *base_url = url;
/* the parser context */
htmlParserCtxtPtr ctxt;
/* the resulting document tree */
xmlDocPtr doc;
/* create a parser context */
ctxt = htmlNewParserCtxt();
if (ctxt == NULL) {
fprintf(stderr, "failed to allocate parser context\n");
return;
} else {
debugf("in memory parser context created correctly\n");
}
/*
* The document being in memory, it have no base per RFC 2396,
* and the "noname.xml" argument will serve as its base.
*
* http://xmlsoft.org/html/libxml-parser.html#xmlParserOption
* http://xmlsoft.org/html/libxml-HTMLparser.html#htmlReadMemory
* http://xmlsoft.org/html/libxml-HTMLparser.html#htmlParserOption
*
* htmlParserOption
* HTML_PARSE_RECOVER = 1 : Relaxed parsing
* HTML_PARSE_NODEFDTD = 4 : do not default a doctype if not found
* HTML_PARSE_NOERROR = 32 : suppress error reports
* HTML_PARSE_NOWARNING = 64 : suppress warning reports
* HTML_PARSE_PEDANTIC = 128 : pedantic error reporting
* HTML_PARSE_NOBLANKS = 256 : remove blank nodes
* HTML_PARSE_NONET = 2048 : Forbid network access
* HTML_PARSE_NOIMPLIED = 8192 : Do not add implied html/body... elements
* HTML_PARSE_COMPACT = 65536 : compact small text nodes
* HTML_PARSE_IGNORE_ENC = 2097152 : ignore internal document encoding hint
*
* htmlStatus
* HTML_NA = 0 : something we don't check at all
* HTML_INVALID = 1
* HTML_DEPRECATED = 2
* HTML_VALID = 4
* HTML_REQUIRED = 12 : VALID bit set so ( & HTML_VALID ) is TRUE
*/
int opts = HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING |
HTML_PARSE_NONET;
debugf("parsing content: %lu size and %d long\n", sizeof(*content), length);
/* parse the file, activating the DTD validation option */
/* doc = xmlCtxtReadFile(ctxt, filename, NULL, XML_PARSE_DTDVALID); */
doc = htmlReadMemory(content, length, base_url, NULL, opts);
if (doc == NULL) {
fprintf(stderr, "failed to parse; trying with relaxed parsing\n");
/* https://stackoverflow.com/a/256223 */
fprintf(stderr, "lenght: %d, snippet: %.*s", length, 40, content + 1);
doc = htmlReadMemory(content, length, base_url, NULL, 1);
}
if (doc == NULL) {
fprintf(stderr, "failed to parse document\n");
return;
} else {
debugf("HTML document read in memory\n");
}
/* using the XML Path Language implementation
* http://xmlsoft.org/html/libxml-xpath.html
*
* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathNewContext
* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathFreeContext
* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathEvalExpression
*
* Function: xmlXPathEvalExpression
* xmlXPathObjectPtr xmlXPathEvalExpression (const xmlChar * str,
* xmlXPathContextPtr ctxt)
* Alias for xmlXPathEval().
* str: the XPath expression
* ctxt: the XPath context
* Returns: the xmlXPathObjectPtr resulting from the evaluation or NULL. the
* caller has to free the object.
*/
xmlChar *xpath = (xmlChar *)XPATH_HYPERLINKS;
xmlXPathContextPtr context = xmlXPathNewContext(doc);
/*
* Structure xmlXPathObject
* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathObject
*
* struct _xmlXPathObject {
* xmlXPathObjectType type
* xmlNodeSetPtr nodesetval
* int boolval
* double floatval
* xmlChar *stringval
* void *user
* int index
* void *user2
* int index2
* }
* Function: xmlXPathEvalExpression
*
* xmlXPathObjectPtr xmlXPathEvalExpression (const xmlChar *str,
* xmlXPathContextPtr ctxt)
*
* Alias for xmlXPathEval().
*
* str: the XPath expression
* ctxt: the XPath context
* Returns: the xmlXPathObjectPtr resulting from the evaluation or NULL.
* the caller has to free the object.
*
*/
xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
if (!result) {
fprintf(stderr, "Failed to path eval document\n");
return;
} else {
/* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathObjectType
*
* Enum xmlXPathObjectType {
* XPATH_UNDEFINED = 0
* XPATH_NODESET = 1
* XPATH_BOOLEAN = 2
* XPATH_NUMBER = 3
* XPATH_STRING = 4
* XPATH_POINT = 5
* XPATH_RANGE = 6
* XPATH_LOCATIONSET = 7
* XPATH_USERS = 8
* XPATH_XSLT_TREE = 9 : An XSLT value tree, non modifiable
* }
*/
}
/*
* --- result ---
* http://xmlsoft.org/html/libxml-xpath.html#xmlXPathObject
* structure xmlXPathObject
* struct _xmlXPathObject {
* xmlXPathObjectType type
* xmlNodeSetPtr nodesetval
* int boolval
* double floatval
* xmlChar *stringval
* void *user
* int index
* void *user2
* int index2
* }
*/
xmlNodeSetPtr nodeset = result->nodesetval;
/*
* --- nodeset ---
* http://xmlsoft.org/html/libxml-xpath.html#xmlNodeSet
* Structure xmlNodeSet
* struct _xmlNodeSet {
* int nodeNr : number of nodes in the set
* int nodeMax : size of the array as allocated
* xmlNodePtr * nodeTab : array of nodes in no particular order @
* }
*/
if (xmlXPathNodeSetIsEmpty(nodeset)) {
fprintf(stdout, "no results found\n");
xmlXPathFreeObject(result);
return;
} else {
size_t l = xmlXPathNodeSetGetLength(nodeset);
fprintf(stdout, "found %lu results\n", l);
}
size_t count = 0;
for (int i = 0; i < nodeset->nodeNr; ++i) {
int x = i;
if (limited) {
double r = rand();
x = r * nodeset->nodeNr / RAND_MAX;
}
/*
* --- curr ---
* http://xmlsoft.org/html/libxml-tree.html#xmlNode
* Structure xmlNode
* struct _xmlNode {
* void *_private : application data
* xmlElementType type : type number, must be second !
* const xmlChar *name : the name of the node, or the entity
* struct _xmlNode *children : parent->childs link
* struct _xmlNode *last : last child link
* struct _xmlNode *parent : child->parent link
* struct _xmlNode *next : next sibling link
* struct _xmlNode *prev : previous sibling link
* struct _xmlDoc *doc : the containing document End of common p
* xmlNs *ns : pointer to the associated namespace
* xmlChar *content : the content
* struct _xmlAttr *properties : properties list
* xmlNs *nsDef : namespace definitions on this node
* void *psvi : for type/PSVI informations
* unsigned short line : line number
* unsigned short extra : extra data for XPath/XSLT
* }
*/
xmlNode *curr = nodeset->nodeTab[x];
/* http://xmlsoft.org/html/libxml-tree.html#xmlGetProp
* xmlGetProp
*
* xmlChar *xmlGetProp (const xmlNode * node,
* const xmlChar * name)
*
* Search and get the value of an attribute associated to a node This does
* the entity substitution. This function looks in DTD attribute declaration
* for #FIXED or default declaration values unless DTD use has been turned
* off. NOTE: this function acts independently of namespaces associated to
* the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware
* processing.
*
* node: the node
* name: the attribute name
* Returns: the attribute value or NULL if not found. It's up to the caller
* to free the memory with xmlFree().
*
* xmlChar *xmlGetProp(const xmlNode *node, *const xmlChar *name)
*/
xmlChar *href = xmlGetProp(curr, (xmlChar *)"href");
debugf("CURR NAME: %s, CONTENT: %s, HREF: %s\n", (char *)curr->name,
(char *)curr->content, (char *)href);
/* http://xmlsoft.org/html/libxml-tree.html#xmlChildrenNode
* http://xmlsoft.org/html/libxml-tree.html#xmlNodeListGetString
*
* const xmlNode *sibling = xmlNextElementSibling((xmlNode *)curr);
* xmlChar *siblingText = xmlNodeListGetString(doc, sibling, 1);
* xmlChar *siblingProp = xmlGetProp(sibling, (xmlChar *)"href");
* printf("SIBLING: %s, HREF: %s\n", siblingText, (char *)siblingProp);
*/
const xmlNode *children = curr->xmlChildrenNode;
xmlChar *raw_text = xmlNodeListGetString(doc, children, 1);
char *text = (char *)raw_text;
trim_whitespace(text);
debugf("CHILDREN: %s, HREF: %s\n", childrenText, (char *)text);
if (!href) {
debugf("not a good link: %s\n", (char *)href);
continue;
}
/* add also span class="sitestr" */
if (!strcmp(base_url, hackernews)) {
if (is_comment((char *)text)) {
link_relative_expand(&href, url);
char *link = (char *)href;
fprintf(stdout, "([[%s][%s]])\n\n", link, text);
continue;
}
}
char *link = (char *)href;
if (!strncmp(link, "http://", 7) || !strncmp(link, "https://", 8)) {
count++;
debugf("- (%03lu/%03d): %s\n", count, i, link);
fprintf(stdout, "- [[%s][%s]]\n", link, (char *)text);
}
xmlFree(raw_text);
xmlFree(href);
}
xmlXPathFreeObject(result);
xmlFreeDoc(doc);
return;
}
void snail_html_parse_hackernews(const char *content, int length) {
return snail_html_parse(content, length, "https://news.ycombinator.com");
}
void snail_html_parse_content(const char *content, int length) {
return snail_html_parse(content, length, NULL);
}
void snail_html_parse_url(const char *content, int length, char *url) {
return snail_html_parse(content, length, url);
}
int pending_interrupt = 0;
void sighandler(int dummy) {
(void)dummy;
pending_interrupt = 1;
}
int snail_crawl(void) {
signal(SIGINT, sighandler);
LIBXML_TEST_VERSION;
curl_global_init(CURL_GLOBAL_DEFAULT);
CURLM *multi_handle = curl_multi_init();
curl_multi_setopt(multi_handle, CURLMOPT_MAX_TOTAL_CONNECTIONS, max_con);
curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, 6L);
/* enables http/2 if available */
#ifdef CURLPIPE_MULTIPLEX
curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
#endif
/* sets html start page */
curl_multi_add_handle(multi_handle, snail_crawl_make_handle(start_page));
int msgs_left;
int pending = 0;
int complete = 0;
int still_running = 1;
while (still_running && !pending_interrupt) {
int numfds;
curl_multi_wait(multi_handle, NULL, 0, 1000, &numfds);
curl_multi_perform(multi_handle, &still_running);
/* See how the transfers went */
CURLMsg *m = NULL;
while ((m = curl_multi_info_read(multi_handle, &msgs_left))) {
if (m->msg == CURLMSG_DONE) {
CURL *handle = m->easy_handle;
char *url;
memory *mem;
curl_easy_getinfo(handle, CURLINFO_PRIVATE, &mem);
curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &url);
if (m->data.result == CURLE_OK) {
long res_status;
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res_status);
if (res_status == 200) {
char *ctype;
curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &ctype);
printf("[%d] HTTP 200 (%s): %s\n", complete, ctype, url);
if (is_html(ctype) && mem->size > 100) {
if (pending < max_requests && (complete + pending) < max_total) {
pending += snail_crawl_follow_links(multi_handle, mem, url);
still_running = 1;
}
}
} else {
printf("[%d] HTTP %d: %s\n", complete, (int)res_status, url);
}
} else {
printf("[%d] Connection failure: %s\n", complete, url);
}
curl_multi_remove_handle(multi_handle, handle);
curl_easy_cleanup(handle);
free(mem->buf);
free(mem);
complete++;
pending--;
}
}
}
curl_multi_cleanup(multi_handle);
curl_global_cleanup();
return 0;
}
int parse(char *file_name) {
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
char *buffer = 0;
long length;
FILE *f = fopen(file_name, "rb");
if (f) {
fseek(f, 0, SEEK_END);
length = ftell(f);
fprintf(stdout, "found length of %lu in %s\n", length, file_name);
fseek(f, 0, SEEK_SET);
buffer = malloc(length + 1);
if (buffer) {
fread(buffer, 1, length, f);
}
buffer[length] = '\0';
fclose(f);
} else {
fprintf(stderr, "cannot fOpen %s\n", file_name);
return EXIT_FAILURE;
}
if (buffer) {
/* start to process your data / extract strings here... */
snail_html_parse_content(buffer, strlen(buffer));
}
/*
* Cleanup function for the XML library.
* http://xmlsoft.org/html/libxml-parser.html
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
return EXIT_SUCCESS;
}
int get(char *url) {
CURL *handle;
int curl_err;
handle = snail_crawl_make_handle(url);
if (!handle) {
fprintf(stderr, "cannot create a cURL handler\n");
return EXIT_FAILURE;
}
/*
* curl_easy_perform - perform a blocking file transfer
*
* https://curl.haxx.se/libcurl/c/curl_easy_perform.html
*
* #include <curl/curl.h>
* CURLcode curl_easy_perform(CURL * easy_handle );
*
* Invoke this function after curl_easy_init and all the curl_easy_setopt
* calls are made, and will perform the transfer as described in the
* options. It must be called with the same easy_handle as input as the
* curl_easy_init call returned.
*
* curl_easy_perform performs the entire request in a blocking manner and
* returns when done, or if it failed. For non-blocking behavior, see
* curl_multi_perform.
*
* You can do any amount of calls to curl_easy_perform while using the same
* easy_handle. If you intend to transfer more than one file, you are even
* encouraged to do so. libcurl will then attempt to re-use the same
* connection for the following transfers, thus making the operations
* faster, less CPU intense and using less network resources. Just note that
* you will have to use curl_easy_setopt between the invokes to set options
* for the following curl_easy_perform.
*
* You must never call this function simultaneously from two places using
* the same easy_handle. Let the function return first before invoking it
* another time. If you want parallel transfers, you must use several curl
* easy_handles.
*
* While the easy_handle is added to a multi handle, it cannot be used by
* curl_easy_perform.
*
* Return value
* CURLE_OK (0) means everything was ok, non-zero means an error occurred as
* <curl/curl.h> defines - see libcurl-errors. If the CURLOPT_ERRORBUFFER
* was set with curl_easy_setopt there will be a readable error message in
* the error buffer when non-zero is returned.
*/
curl_err = curl_easy_perform(handle);
/* Check for errors */
if (curl_err != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(curl_err));
} else {
/* https://curl.haxx.se/libcurl/c/libcurl-errors.html */
debugf(stdout, "curl_easy_perform() success: %d\n", curl_err);
char *u;
memory *mem;
curl_easy_getinfo(handle, CURLINFO_PRIVATE, &mem);
curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &u);
long res_status;
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res_status);
if (res_status == 200) {
fprintf(stdout, "success: %lu : %lu\n", sizeof(mem->buf), mem->size);
}
snail_html_parse_url(mem->buf, mem->size, url);
}
curl_easy_cleanup(handle);
return curl_err;
}
int get_hn() { return get(hackernews); }
int main(int argc, char *argv[]) {
int hflag = 0;
int fflag = 0;
int uflag = 0;
int hn_flag = 0;
int verbose_flag = 0;
char *filename = NULL;
char *url = NULL;
int index;
int c;
opterr = 0;
/* getopt, long options
* https://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Options.html
* https://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html
*/
struct option long_options[] = {/* These options set a flag. */
{"verbose", no_argument, &verbose_flag, 1},
{"brief", no_argument, &verbose_flag, 0},
{"hn", no_argument, &hn_flag, 1},
/* These options don’t set a flag. */
{"file", required_argument, 0, 'f'},
{0}};
/* getopt_long stores the option index here. */
int option_index = 0;
while ((c = getopt_long(argc, argv, "hf:u:", long_options, &option_index)) !=
-1)
switch (c) {
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 'h':
hflag = 1;
break;
case 'f':
fflag = 1;
filename = optarg;
break;
case 'u':
uflag = 1;
url = optarg;
break;
case '?':
if (optopt == 'u')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (optopt == 'f')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
abort();
}
debugf("fflag = %d, uflag = %d, URL = %s, FILENAME = %s\n", fflag, uflag, url,
filename);
for (index = optind; index < argc; index++) {
printf("Non-option argument %s\n", argv[index]);
}
int ret = 0;
if (fflag) {
ret = parse(filename);
} else if (hn_flag) {
ret = get_hn();
} else if (uflag) {
ret = get(url);
}
debugf("quitting with %d\n", ret);
return ret;
}
<file_sep>#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
* - size_t fread(void* restrict ptr, size_t size, size_t nmemb ,FILE* restrict
* stream);
* - size_t fwrite(void const*restrict ptr, size_t size, size_tnmemb ,FILE*
* restrict stream);
* - int fseek(FILE* stream , long int offset , int whence);
* - long int ftell(FILE* stream);
*
* The use of fread and fwrite is relatively straightforward. Each stream has a
* cur- rent file position for reading an writing. If successful, these two
* functions read or write size*nmemb bytes from that position onward and then
* update the file position to the new value. The return value of both functions
* is the number of bytes that have been read or written, so usually size*nmemb,
* and thus an error occurred if the return value is less than that. The
* functions ftell and fseek can be used to operate on that file position: ftell
* returns the position in terms of bytes from the start of the file, fseek
* positions the file according to the arguments offset and whence. Here whence
* can have one of the values, SEEK_SET refers to the start of the file and
* SEEK_CUR to current file position before the call.
*/
void print_test_file() {
FILE *fp;
int c;
fp = fopen("file.txt", "r");
while (1) {
c = fgetc(fp);
if (feof(fp)) {
break;
}
printf("%c", c);
}
fclose(fp);
printf("\n");
}
/*
* http://www.cplusplus.com/reference/cstdio/fseek/
* https://en.cppreference.com/w/c/io/fseek
*
* SEEK_END : It denotes end of the file.
* SEEK_SET : It denotes starting of the file.
* SEEK_CUR : It denotes file pointer’s current position.
*/
int sample(int (*seek_function)(FILE *stream, intmax_t offset, int whence)) {
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is abcdefghijklmnopqrstuvwxyz", fp);
/*
* int fseek(FILE *stream, long offset, int whence);
* The fseek() function sets the file position indicator for the stream
* pointed to by stream. The new position, measured in bytes, is obtained by
* adding offset bytes to the position specified by whence. If whence is set
* to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of
* the file, the current position indicator, or end-of-file, respectively. A
* successful call to the fseek() function clears the end-of-file indicator
* for the stream and undoes any effects of the ungetc(3) and ungetwc(3)
* functions on the same stream.
* The fgetpos(), fseek(), fseeko(), and fsetpos() functions return the value
* 0 if successful; otherwise the value -1 is returned and the global variable
* errno is set to indicate the error.
*/
(*seek_function)(fp, 12, SEEK_SET);
fputs("[0123456789]", fp);
fclose(fp);
print_test_file();
/*
* When you open a file with "w" flag it creates an empty file for writing. If
* a file with the same name already exists its contents are erased and the
* file is treated as an empty new file.
*/
FILE *pFile;
pFile = fopen("file.txt", "wb");
fputs("This is a circle", pFile);
(*seek_function)(pFile, -6, SEEK_END);
fputs("square", pFile);
fclose(pFile);
print_test_file();
return (0);
}
#define SIZE 5
int another_sample(int (*seek_function)(FILE *stream, intmax_t offset,
int whence)) {
/* Prepare an array of f-p values. */
double A[SIZE] = {1., 2., 3., 4., 5.};
/* Write array to a file. */
FILE *fp = fopen("file.bin", "wb");
fwrite(A, sizeof(double), SIZE, fp);
fclose(fp);
/* Read the f-p values into array B. */
double B[SIZE];
fp = fopen("file.bin", "rb");
/* Set the file position indicator in front of third f-p value. */
if ((*seek_function)(fp, sizeof(double) * 2L, SEEK_SET) != 0) {
if (ferror(fp)) {
perror("fseek()");
fprintf(stderr, "fseek() failed in file %s at line # %d\n", __FILE__,
__LINE__ - 5);
exit(EXIT_FAILURE);
}
}
int ret_code = fread(B, sizeof(double), 1, fp); /* read one f-p value */
printf("%.1f (%d)\n", B[0], ret_code); /* print one f-p value */
fclose(fp);
return EXIT_SUCCESS;
}
/* TODO: remove one layer of indirection and just return the pointer. */
void pretty_whence(char *w, int whence) {
switch (whence) {
case 0:
strcpy(w, "SEEK_SET");
break;
case 1:
strcpy(w, "SEEK_CUR");
break;
case 2:
strcpy(w, "SEEK_END");
break;
default:
strcpy(w, "error");
break;
}
}
unsigned long abs_n(long n) {
return n < 0 ? -((unsigned long)(n)) : (unsigned long)(n);
}
/*
*
* The use of the type long for file positions limits the size of files that
* can easily be handled with ftell and fseek to LONG_MAX bytes. On most modern
* platforms this corresponds to 2GiB.
*
* Exercises
*
* - [Exs 43]: Write a function fseekmax that uses intmax_t instead of long and
* that achieves large seek values by combining calls to fseek.
*
*/
/*
* whence:
* SEEK_END : It denotes end of the file.
* SEEK_SET : It denotes starting of the file.
* SEEK_CUR : It denotes file pointer’s current position.
*
* limits.h
* LONG_MAX: Maximum value for an object of type long int
* 2147483647 ((2^31)-1) or greater
* LONG_MIN: Minimum value for an object of type long int
* -2147483647 ((-2^31)+1) or les
* http://www.cplusplus.com/reference/climits/
*
* stdint.h
* INTMAX_MAX: Maximum value of intmax_t
* ((2^63)-1) or greater
* https://en.cppreference.com/w/cpp/types/integer
*
* if offset is greater than the LONG_MAX limit:
*
* whence = 00, offset > limit, remains = offset - limit, from = limit
* |whence|<---------------->|limit|----|offset|-----...
*
* whence = EOF,
* offset < 0,
* abs(offset) > limit,
* remains = offset - limit,
* from = -limit
*
* 0 -----------| -30 |----| 100 |----------------| EOF |
* |------------|offset|----|limit|<-------------->|whence|
*
* whence = 10, offset > limit, remains = offset - limit, from = limit
* |-------|whence|<--------------->|limit|----|offset|-----...
*
* we can use fseekmax once that will call fseek the necessary number of times:
* - one (or more) to cover the LONG_MAX limit
*/
int fseekmax_limit(FILE *stream, intmax_t offset, int whence,
const long limit) {
if (limit == 0) {
errno = ENOENT;
printf("limit cannot be 0! %s\n", strerror(errno));
perror("terminating with error condition");
return EXIT_FAILURE;
}
if ((offset > 0 && limit < 0) || (offset < 0 && limit > 0)) {
errno = ENOENT;
printf("limit and offset must have the same sign! %s\n", strerror(errno));
perror("terminating with error condition");
return EXIT_FAILURE;
}
/*
* https://stackoverflow.com/questions/12231560/correct-way-to-take-absolute-value-of-int-min
* https://stackoverflow.com/questions/11243014/why-the-absolute-value-of-the-max-negative-integer-2147483648-is-still-2147483
* https://stackoverflow.com/questions/22268815/absolute-value-of-int-min
*/
/*
* unsigned int abs_n = n < 0 ? UINT_MAX - ((unsigned int)(n)) + 1U
* : (unsigned int)(n);
* we can actually replace UINT_MAX + 1U by 0U:
*/
long n = -10;
unsigned long an = abs_n(n);
(void)an;
/* printf("abs of %ld: %lu\n", n, an); */
char *w = (char *)malloc(sizeof(char) * 9);
pretty_whence(w, whence);
DEBUG_PRINT(
("FSEEKMAX: offset: %ld, limit: %ld, whence: %s\n", offset, limit, w));
free(w);
unsigned long abs_offset = abs_n(offset);
unsigned long abs_limit = abs_n(limit);
if (abs_offset > abs_limit) {
DEBUG_PRINT(("FSEEKMAX: running in extended mode (%ld > %ld)\n",
labs(offset), labs(limit)));
if (fseek(stream, limit, whence) == -1) {
printf("Oh dear, something went wrong with read()! %s\n",
strerror(errno));
perror("terminating with error condition");
return EXIT_FAILURE;
}
long remains = offset - limit;
if (remains < 0) {
remains = offset - limit;
}
DEBUG_PRINT(("FSEEKMAX: sought %ld, remains %ld\n", limit, remains));
return fseekmax_limit(stream, remains, SEEK_CUR, limit);
} else {
DEBUG_PRINT(("FSEEKMAX: running in normal mode (%ld <= %ld)\n",
labs(offset), labs(limit)));
return fseek(stream, offset, whence);
}
}
int fseekmax(FILE *stream, intmax_t offset, int whence) {
/* the limit of the seek depends on the sign of the offset */
long limit = offset > 0 ? LONG_MAX : LONG_MIN;
return fseekmax_limit(stream, offset, whence, limit);
}
int fseekmax_sample(int (*seek_function)(FILE *stream, intmax_t offset,
int whence)) {
FILE *fp;
double A[SIZE] = {1., 2., 3., 4., 5.};
fp = fopen("file.bin", "wb");
fwrite(A, sizeof(double), SIZE, fp);
fclose(fp);
double B[SIZE];
fp = fopen("file.bin", "rb");
if ((*seek_function)(fp, sizeof(double) * 2L, SEEK_SET) != 0) {
if (ferror(fp)) {
perror("fseekmax()");
fprintf(stderr, "fseekmax() failed in file %s at line # %d\n", __FILE__,
__LINE__ - 5);
exit(EXIT_FAILURE);
}
}
int ret_code = fread(B, sizeof(double), 1, fp);
printf("%.1f (%d)\n", B[0], ret_code);
fclose(fp);
fp = fopen("file.txt", "w");
fputs("This is abcdefghijklmnopqrstuvwxyz", fp);
(*seek_function)(fp, -12, SEEK_END);
fputs("[0123456789]", fp);
fclose(fp);
print_test_file();
fp = fopen("file.txt", "wb");
fputs("This is a circle", fp);
(*seek_function)(fp, -6, SEEK_END);
fputs("square", fp);
(*seek_function)(fp, 6, SEEK_CUR);
fputs(" but was a circle", fp);
fclose(fp);
print_test_file();
return EXIT_SUCCESS;
}
int sample_extended() {
FILE *fp;
fp = fopen("file.txt", "wb");
fputs("This is a circle", fp);
fseekmax_limit(fp, 10, SEEK_SET, 3);
fputs("square", fp);
fseekmax(fp, 6, SEEK_CUR);
fputs(" but was a circle", fp);
fclose(fp);
print_test_file();
fp = fopen("file.txt", "wb");
fputs("This is a negative circle", fp);
fseekmax_limit(fp, -6, SEEK_END, -3);
fputs("square", fp);
fseekmax(fp, 6, SEEK_CUR);
fputs(" but was a circle", fp);
fclose(fp);
print_test_file();
return EXIT_SUCCESS;
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
/*
* - int fseekmax(FILE *stream, intmax_t offset, int whence)
* - int fseekmax_limit(FILE *stream, intmax_t offset, int whence,
* const long limit)
* - int fseek(FILE* stream , long int offset , int whence);
*/
int (*fsm)(FILE * stream, intmax_t offset, int whence) = &fseekmax;
int (*fs)(FILE * stream, intmax_t offset, int whence) = &fseek;
printf("--- SAMPLE ---\n");
printf("- fseek\n");
sample(fs);
printf("- fseekmax\n");
sample(fsm);
printf("--- ANOTHER_SAMPLE ---\n");
printf("- fseek\n");
another_sample(fs);
printf("- fseekmax\n");
another_sample(fsm);
printf("--- FSEEKMAX_SAMPLE ---\n");
printf("- fseek\n");
fseekmax_sample(fs);
printf("- fseekmax\n");
fseekmax_sample(fsm);
printf("--- SAMPLE_EXTENDED ---\n");
printf("- fseekmax\n");
sample_extended();
printf("-------\n");
printf("nothing to do\n");
return EXIT_SUCCESS;
}
<file_sep>#include "clock.h"
#include <stdio.h>
/* rem is the int reminder of the division. */
int rem(int a, int b) { return a - (a / b) * b; }
/* mod is the modulo operation that implements this formula:
* (a/b) * b + a%b = a
* works correctly with negative numbers.
*/
int mod(int a, int b) {
int r = a % b;
return r < 0 ? r + b : r;
}
void clock(time_text_t time_text, int hour, int minute) {
int mm = mod(60 * hour + minute, MINS_IN_DAY);
snprintf(time_text, sizeof(char[MAX_STR_LEN]), "%02d:%02d", mm / 60, mm % 60);
}
/* using sscanf to parse the time_text:
* int
* sscanf(const char *restrict s, const char *restrict format, ...);
*/
void clock_add(time_text_t time_text, int minute_offset) {
int hour, minute;
int res = sscanf(time_text, "%02d:%02d", &hour, &minute);
if (res != 2) {
fprintf(stderr, "bad time_test_t format\n");
}
clock(time_text, hour, minute + minute_offset);
}
<file_sep>/*
* GNU Typist - interactive typing tutor program for UNIX systems
*
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
* <NAME> (<EMAIL>)
* Copyright (C) 2003, 2004, 2008, 2009, 2011, 2012
* GNU Typist Development Team <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* http://git.savannah.gnu.org/cgit/gtypist.git/ */
#include "config.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/time.h>
#if defined(HAVE_PDCURSES) || defined(OS_BSD)
#include <curses.h>
#else
#include <ncursesw/ncurses.h>
#endif
#include <time.h>
#include <errno.h>
#include <string.h>
#include <getopt.h>
#include <assert.h>
#include <locale.h>
#include <wctype.h>
#ifndef MINGW
#include <langinfo.h>
#endif
#include "cursmenu.h"
#include "script.h"
#include "error.h"
#include "gtypist.h"
#include "utf8.h"
#include "infoview.h"
#include "speedbox.h"
#include "cmdline.h"
#include "gettext.h"
#define _(String) gettext (String)
/* VERSION and PACKAGE defined in config.h */
char* locale_encoding; /* current locale's encoding */
int isUTF8Locale; /* does the current locale have a UTF-8 encoding? */
/* character to be display to represent "enter key" */
/* TODO: this requires beginner mode!
#define RETURN_CHARACTER 0x000023CE */
#define RETURN_CHARACTER 0x00000020
/* a definition of a boolean type */
#ifndef bool
#define bool int
#endif
/* mode indicator strings */
char *MODE_TUTORIAL;
char *MODE_QUERY;
char *MODE_DRILL;
char *MODE_SPEEDTEST;
/* yes/no responses and miscellanea */
#define QUERY_Y 'Y'
#define QUERY_N 'N'
#define DRILL_CH_ERR '^'
#define DRILL_NL_ERR '^'
char *WAIT_MESSAGE;
char *ERROR_TOO_HIGH_MSG;
char *SKIPBACK_VIA_F_MSG;
char *REPEAT_NEXT_EXIT_MSG;
char *REPEAT_EXIT_MSG;
char *CONFIRM_EXIT_LESSON_MSG;
char *NO_SKIP_MSG;
wchar_t *YN;
wchar_t *RNE;
#ifdef MINGW
#define DATADIR "lessons"
#else
#ifndef DATADIR
#define DATADIR "."
#endif
#endif
#define DEFAULT_SCRIPT "gtypist.typ"
#ifdef MINGW
#define BESTLOG_FILENAME "gtypist-bestlog"
#define CONFIG_FILENAME "gtypistrc"
#else
#define BESTLOG_FILENAME ".gtypist-bestlog"
#define CONFIG_FILENAME ".gtypistrc"
#endif
/* some colour definitions */
static short colour_array[] = {
COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE };
#define NUM_COLOURS (sizeof( colour_array ) / sizeof( short ))
#ifdef MINGW
#define MIN( a, b ) ( ( a ) < ( b )? ( a ) : ( b ) )
#define MAX( a, b ) ( ( a ) > ( b )? ( a ) : ( b ) )
#endif
/* command line and config file options */
static struct gengetopt_args_info cl_args; /* program options */
static int cl_fgcolour = 7; /* fg colour */
static int cl_bgcolour = 0; /* bg colour */
static int cl_banner_bg_colour = 0; /* banner bg colorr */
static int cl_banner_fg_colour = 6; /* banner fg colour */
static int cl_prog_name_colour = 5; /* program name colour */
static int cl_prog_version_colour = 1; /* program version colour */
/* a few global variables */
static bool global_resp_flag = TRUE;
static char global_prior_command = C_CONT;
static float global_error_max = -1.0;
static bool global_error_max_persistent = FALSE;
static struct label_entry *global_on_failure_label = NULL;
static bool global_on_failure_label_persistent = FALSE;
static char *global_script_filename = NULL;
static char *global_home_dir = NULL;
/* a global area for associating function keys with labels */
#define NFKEYS 12 /* num of function keys */
static char *fkey_bindings[ NFKEYS ] =
{ NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL };
/* table of pseudo-function keys, to allow ^Q to double as Fkey1, etc */
#define CTRL_OFFSET 0100 /* ctrl keys are 'X' - 0100 */
static char pfkeys[ NFKEYS ] =
{ 'Q'-CTRL_OFFSET, 'W'-CTRL_OFFSET, 'E'-CTRL_OFFSET, 'R'-CTRL_OFFSET,
'T'-CTRL_OFFSET, 'Y'-CTRL_OFFSET, 'U'-CTRL_OFFSET, 'I'-CTRL_OFFSET,
'O'-CTRL_OFFSET, 'P'-CTRL_OFFSET, 'A'-CTRL_OFFSET, 'S'-CTRL_OFFSET };
static bool user_is_always_sure = FALSE;
/* prototypes */
static int getch_fl( int cursor_char );
static bool wait_user (FILE *script, char *message, char *mode );
static void display_speed( int total_chars, double elapsed_time, int errcount );
static void do_keybind( FILE *script, char *line );
static void do_tutorial( FILE *script, char *line );
static void do_instruction( FILE *script, char *line );
static int is_error_too_high( int chars_typed, int errors );
static void do_drill( FILE *script, char *line );
static void do_speedtest( FILE *script, char *line );
static void do_clear( FILE *script, char *line );
static void do_goto( FILE *script, char *line, bool flag );
static char do_query_repeat( FILE *script, bool allow_next );
static bool do_query_simple( char *text );
static bool do_query( FILE *script, char *line );
static void do_error_max_set( FILE *script, char *line );
static void do_on_failure_label_set( FILE *script, char *line );
static void parse_file( FILE *script, char *label );
static void catcher( int signal );
static FILE *open_script( const char *filename );
static void do_bell();
static bool get_best_speed( const char *script_filename,
const char *excersise_label, double *adjusted_cpm );
static void put_best_speed( const char *script_filename,
const char *excersise_label, double adjusted_cpm );
const char *get_bestlog_filename();
void bind_F12 (const char *label)
{
if (!label)
return;
if (fkey_bindings [11])
free (fkey_bindings [11]);
fkey_bindings [11] = strdup (label);
if (! fkey_bindings [11])
{
perror ("strdup");
fatal_error (_("internal error: strdup"), label);
}
}
/*
getch() that does a flashing cursor; some xterms seem to be
unwilling to do A_BLINK, however, the program needs some
way to separate out the inverse char cursor from the inverse
char mistyping indications. And to complicate things, some
xterms seem not make the cursor invisible either.
*/
static int
getch_fl( int cursor_char )
{
int y, x; /* saved cursor posn */
int return_char; /* return value */
bool alternate = FALSE; /* flashes control */
/* save the cursor position - we're going to need it */
getyx( stdscr, y, x );
/* if no cursor then do our best not to show one */
if ( cursor_char == ASCII_NULL )
{
/* degrade to cursor-less getch */
curs_set( 0 ); refresh();
move( LINES - 1, COLS - 1 );
cbreak();
get_widech(&return_char);
move( y, x );
}
else
{
/* produce a flashing cursor, or not, as requested */
if ( !cl_args.term_cursor_flag ) {
/* go for the flashing block here */
wideaddch_rev(cursor_char);
curs_set( 0 ); refresh();
move( LINES - 1, COLS - 1 );
if ( ( cl_args.curs_flash_arg / 2 ) > 0 )
{
halfdelay( cl_args.curs_flash_arg / 2 );
while ( get_widech(&return_char) == ERR )
{
move( y, x );
if ( alternate )
wideaddch_rev(cursor_char);
else
wideaddch(cursor_char);
move( LINES - 1, COLS - 1 );
alternate = !alternate;
}
}
else
{
cbreak();
get_widech(&return_char);
}
move( y, x );
wideaddch(cursor_char);
move( y, x );
}
else
{
/* just use the terminal's cursor - this is easy */
curs_set( 1 ); refresh();
cbreak(); //return_char = getch();
get_widech(&return_char);
curs_set( 0 ); refresh();
}
}
/* return what key was pressed */
return ( return_char );
}
/*
wait for a nod from the user before continuing. In MODE_TUTORIAL only, TRUE is
returned if the user pressed escape to indicate that seek_label was called
*/
static bool wait_user (FILE *script, char *message, char *mode)
{
int resp; /* response character */
bool seek_done = FALSE; /* was seek_label called? */
/* move to the message line print a prompt */
move( MESSAGE_LINE, 0 ); clrtoeol();
move( MESSAGE_LINE, COLS - utf8len( mode ) - 2 );
wideaddstr_rev(mode);
move( MESSAGE_LINE, 0 );
wideaddstr_rev(message);
do {
resp = getch_fl (ASCII_NULL);
/* in tutorial mode only, escape has the special purpose that we exit to a
menu (or quit if there is none) */
if (resp == ASCII_ESC && mode == MODE_TUTORIAL)
{
// Return to the last F12-binded location
if( fkey_bindings[ 11 ] && *( fkey_bindings[ 11 ] ) )
{
seek_label( script, fkey_bindings[ 11 ], NULL );
seek_done = TRUE;
}
else
do_exit( script );
break;
}
} while (resp != ASCII_NL && resp != ASCII_SPACE && resp != ASCII_ESC);
/* clear the message line */
move( MESSAGE_LINE, 0 ); clrtoeol();
return seek_done;
}
/*
calculate and display speed and accuracy from a drill or speed test
*/
static void display_speed( int total_chars, double elapsed_time, int errcount ) {
double test_time; /* time in minutes */
double cpm, adjusted_cpm; /* speeds in CPM */
bool had_best_speed = FALSE; /* already had a p.best? */
bool new_best_speed = FALSE; /* have we beaten it? */
double best_cpm; /* personal best speed in CPM */
char *raw_speed_str, *adj_speed_str, *best_speed_str;
/* calculate the speeds */
test_time = elapsed_time / 60.0;
if( elapsed_time > 0 )
{
/* calculate speed values */
cpm = (double)total_chars / test_time;
adjusted_cpm = (double)( total_chars - ( errcount * 5 ) ) / test_time;
/* limit speed values */
cpm = MIN( cpm, 9999.99 );
adjusted_cpm = MAX( MIN( adjusted_cpm, 9999.99 ), 0 );
/* remove errors in adjusted speed */
if( adjusted_cpm < 0.01 )
adjusted_cpm = 0;
}
else
/* unmeasurable elapsed time - use big numbers */
cpm = adjusted_cpm = (double)9999.99;
/* obtain (and update?) a personal best speed */
if( cl_args.personal_best_flag )
{
had_best_speed =
get_best_speed( global_script_filename, __last_label, &best_cpm );
new_best_speed = ( !had_best_speed || adjusted_cpm > best_cpm ) &&
!is_error_too_high( total_chars, errcount );
if( new_best_speed )
put_best_speed( global_script_filename, __last_label, adjusted_cpm );
}
/* draw speed box */
do_speed_box( total_chars, errcount, cpm, adjusted_cpm,
cl_args.scoring_arg == scoring_arg_cpm? TRUE : FALSE,
had_best_speed, new_best_speed, best_cpm );
}
/*
bind a function key to a label
*/
static void
do_keybind( FILE *script, char *line ) {
int fkey; /* function key number */
char *label; /* associated label */
/* extract the fkey number and label string, and check
the syntax and correctness of the mappings */
label = (char*)malloc( strlen(SCR_DATA( line )) + 1 );
if ( sscanf( SCR_DATA( line ), "%d:%s", &fkey, label ) != 2 )
fatal_error( _("invalid key binding"), line );
if ( fkey < 1 || fkey > NFKEYS )
fatal_error( _("invalid function key number"), line );
/* free the previous binding malloced data */
if ( fkey_bindings[ fkey - 1 ] != NULL )
{
free( fkey_bindings[ fkey - 1 ] );
fkey_bindings[ fkey - 1 ] = NULL;
}
/* add the association to the array, or unbind the association
if the target is the special label "NULL" (ugh - hacky) */
if ( strcmp( label, "NULL" ) != 0 && strcmp( label, "null" ) != 0 )
fkey_bindings[ fkey - 1 ] = label;
else
free( label );
/* get the next command */
get_script_line( script, line );
global_prior_command = C_KEYBIND;
}
/*
print the given text onto the screen
*/
static void
do_tutorial( FILE *script, char *line ) {
int linenum; /* line counter */
bool seek_done = FALSE; /* was there a seek_label before exit? */
/* start at the top of the screen, and clear it */
linenum = T_TOP_LINE;
move( linenum, 0 ); clrtobot();
/* output this line, and each continuation line read */
do
{
if ( linenum >= LINES - 1 )
fatal_error( _("data exceeds screen length"), line );
move( linenum, 0 );
/* ADDSTR( SCR_DATA( line )); */
wideaddstr(SCR_DATA( line ));
get_script_line( script, line );
linenum++;
}
while ( SCR_COMMAND( line ) == C_CONT && ! feof( script ));
/* wait for a return, unless the next command is a query,
when we can skip it to save the user keystrokes */
if ( SCR_COMMAND( line ) != C_QUERY )
seek_done = wait_user (script, WAIT_MESSAGE, MODE_TUTORIAL);
global_prior_command = C_TUTORIAL;
/* if seek_label has been called (in wait_user) then we need to read in the
next line of the script in to `line` */
if (seek_done)
get_script_line( script, line );
}
/*
print up a line, at most two, usually followed by a drill or a speed test
*/
static void
do_instruction( FILE *script, char *line ) {
/* move to the instruction line and output the first bit */
move( I_TOP_LINE, 0 ); clrtobot();
ADDSTR( SCR_DATA( line ));
get_script_line( script, line );
/* if there is a second line then output that too */
if ( SCR_COMMAND( line ) == C_CONT && ! feof( script ))
{
move( I_TOP_LINE + 1, 0 );
ADDSTR( SCR_DATA( line ) );
get_script_line( script, line );
}
/* if there is a third line then complain */
if ( SCR_COMMAND( line ) == C_CONT && ! feof( script ))
fatal_error( _("instructions are limited to two lines"), line );
global_prior_command = C_INSTRUCTION;
}
/*
Calculate whether a drill's error rate is too high, keeping in mind
rounding of output to a single decimal place.
*/
static int
is_error_too_high( int chars_typed, int errors ) {
/* (double)100.0*(double)errcount / (double)total_chars ) */
double err_max, err;
char buf[BUFSIZ];
/* Calculate error rates */
err_max = (double)global_error_max;
err = (double)100.0*(double)errors / (double)chars_typed;
/* We need to use the same kind of rounding used by printf. */
sprintf(buf, "%.1f", err_max);
sscanf(buf, "%lf", &err_max);
sprintf(buf, "%.1f", err);
sscanf(buf, "%lf", &err);
return err > err_max;
}
/*
execute a typing drill
*/
static void
do_drill( FILE *script, char *line ) {
int errors = 0; /* error count */
int linenum; /* line counter */
char *data = NULL; /* data string */
int lines_count = 0; /* measures drill length */
int rc; /* curses char typed */
wchar_t *widep, *wideData;
double start_time=0, end_time; /* timing variables */
char message[MAX_WIN_LINE]; /* message buffer */
char drill_type; /* note of the drill type */
int chars_typed; /* count of chars typed */
int chars_in_the_line_typed;
bool seek_done = FALSE; /* was there a seek_label before exit? */
int error_sync; /* error resync state */
struct timeval tv;
/* note the drill type to see if we need to make the user repeat */
drill_type = SCR_COMMAND( line );
/* get the complete exercise into a single string */
data = buffer_command( script, line );
/* get the exercise as a wide string */
wideData = convertFromUTF8(data);
int numChars = wcslen(wideData);
/* count the lines in this exercise, and check the result
against the screen length */
for ( widep = wideData, lines_count = 0; *widep != ASCII_NULL; widep++ )
{
if ( *widep == ASCII_NL)
lines_count++;
}
if ( DP_TOP_LINE + lines_count * 2 > LINES )
fatal_error( _("data exceeds screen length"), line );
/* if the last command was a tutorial, ensure we have
the complete screen */
if ( global_prior_command == C_TUTORIAL )
{
move( T_TOP_LINE, 0 ); clrtobot();
}
while (1)
{
/* display drill pattern */
linenum = DP_TOP_LINE;
move( linenum, 0 ); clrtobot();
for ( widep = wideData; *widep != ASCII_NULL; widep++ )
{
if ( *widep != ASCII_NL )
wideaddch(*widep);
else
{
/* emit return character */
wideaddch(RETURN_CHARACTER);
/* newline - move down the screen */
linenum++; linenum++; /* alternate lines */
move( linenum, 0 );
}
}
move( MESSAGE_LINE, COLS - utf8len( MODE_DRILL ) - 2 );
ADDSTR_REV( MODE_DRILL );
/* run the drill */
linenum = DP_TOP_LINE + 1;
move( linenum, 0 );
for ( widep = wideData; *widep == ASCII_SPACE && *widep != ASCII_NULL; widep++ )
wideaddch(*widep);
for ( chars_typed = 0, errors = 0, error_sync = 0,
chars_in_the_line_typed = 0;
*widep != ASCII_NULL; widep++ )
{
do
{
rc = getch_fl (chars_in_the_line_typed >= COLS ? *(widep + 1) :
(*widep == ASCII_TAB ? ASCII_TAB : ASCII_SPACE));
}
while ( rc == GTYPIST_KEY_BACKSPACE || rc == ASCII_BS || rc == ASCII_DEL );
/* start timer on first char entered */
if ( chars_typed == 0 )
{
gettimeofday(&tv, NULL);
start_time = tv.tv_sec + tv.tv_usec / 1000000.0;
}
chars_typed++;
error_sync--;
/* ESC is "give up"; ESC at beginning of exercise is "skip lesson"
(this is handled outside the for loop) */
if ( rc == ASCII_ESC )
break;
/* check that the character was correct */
if ( rc == *widep || ( cl_args.word_processor_flag &&
rc == ASCII_SPACE && *widep == ASCII_NL ))
{
if (cl_args.word_processor_flag && rc == ASCII_SPACE &&
*widep == ASCII_NL)
chars_in_the_line_typed = 0;
else
{
if (rc != ASCII_NL)
{
wideaddch(rc);
chars_in_the_line_typed ++;
}
else
{
wideaddch(RETURN_CHARACTER);
chars_in_the_line_typed = 0;
}
}
}
else
{
/* try to sync with typist behind */
if ( error_sync >= 0 && widep > wideData && rc == *(widep-1) )
{
widep--;
continue;
}
if (chars_in_the_line_typed < COLS)
{
wideaddch_rev( *widep == ASCII_NL ? DRILL_NL_ERR :
(*widep == ASCII_TAB ?
ASCII_TAB : (cl_args.show_errors_flag ?
rc : DRILL_CH_ERR)));
chars_in_the_line_typed ++;
}
if (*widep == ASCII_NL)
chars_in_the_line_typed = 0;
if ( ! cl_args.silent_flag )
{
do_bell();
}
errors++;
error_sync = 1;
/* try to sync with typist ahead? */
if (cl_args.sync_ahead_flag)
{
if ( rc == *(widep+1) )
{
ungetch( rc );
error_sync++;
}
}
}
/* move screen location if newline */
if ( *widep == ASCII_NL )
{
linenum++; linenum++;
move( linenum, 0 );
}
/* perform any other word processor like adjustments */
if ( cl_args.word_processor_flag )
{
if ( rc == ASCII_SPACE )
{
while ( *(widep+1) == ASCII_SPACE
&& *(widep+1) != ASCII_NULL )
{
widep++;
wideaddch(*widep);
chars_in_the_line_typed ++;
}
}
else if ( rc == ASCII_NL )
{
while ( ( *(widep+1) == ASCII_SPACE
|| *(widep+1) == ASCII_NL )
&& *(widep+1) != ASCII_NULL )
{
widep++;
wideaddch(*widep);
chars_in_the_line_typed ++;
if ( *widep == ASCII_NL ) {
linenum++; linenum++;
move( linenum, 0 );
chars_in_the_line_typed = 0;
}
}
}
else if ( isalpha(*widep) && *(widep+1) == ASCII_DASH
&& *(widep+2) == ASCII_NL )
{
widep++;
wideaddch(*widep);
widep++;
wideaddch(*widep);
linenum++; linenum++;
move( linenum, 0 );
chars_in_the_line_typed = 0;
}
}
}
/* ESC not at the beginning of the lesson: "give up" */
if ( rc == ASCII_ESC && chars_typed != 1)
continue; /* repeat */
/* skip timings and don't check error-pct if exit was through ESC */
if ( rc != ASCII_ESC )
{
/* display timings */
gettimeofday(&tv, NULL);
end_time = tv.tv_sec + tv.tv_usec / 1000000.0;
if ( ! cl_args.notimer_flag )
{
display_speed( chars_typed, end_time - start_time,
errors );
}
/* check whether the error-percentage is too high (unless in d:) */
if (drill_type != C_DRILL_PRACTICE_ONLY &&
is_error_too_high(chars_typed, errors))
{
sprintf( message, ERROR_TOO_HIGH_MSG, global_error_max );
wait_user (script, message, MODE_DRILL);
/* check for F-command */
if (global_on_failure_label != NULL)
{
/* move to the label position in the file */
if (fseek(script, global_on_failure_label->offset, SEEK_SET )
== -1)
fatal_error( _("internal error: fseek"), NULL );
global_line_counter = global_on_failure_label->line_count;
/* tell the user about the misery :) */
sprintf(message,SKIPBACK_VIA_F_MSG,
global_on_failure_label->label);
/* reset value unless persistent */
if (!global_on_failure_label_persistent)
global_on_failure_label = NULL;
wait_user (script, message, MODE_DRILL);
seek_done = TRUE;
break;
}
continue;
}
}
/* ask the user whether he/she wants to repeat or exit */
if ( rc == ASCII_ESC && cl_args.no_skip_flag ) /* honor --no-skip */
rc = do_query_repeat (script, FALSE);
else
rc = do_query_repeat (script, TRUE);
if (rc == 'E') {
seek_done = TRUE;
break;
}
if (rc == 'N')
break;
}
/* free the malloced memory */
free( data );
free( wideData );
/* reset global_error_max */
if (!global_error_max_persistent)
global_error_max = cl_args.max_error_arg;
/* buffer_command takes care of advancing `script' (and setting
`line'), so we only do if seek_label had been called (in
do_query_repeat or due to a failure and an F: command) */
if (seek_done)
get_script_line( script, line );
global_prior_command = drill_type;
}
/*
execute a timed speed test
*/
static void
do_speedtest( FILE *script, char *line ) {
int errors = 0; /* error count */
int *errors_buf; /* error localization buffer */
int errors_pos; /* error localization position */
int err_idx; /* errors counter */
int linenum; /* line counter */
char *data = NULL; /* data string */
int lines_count = 0; /* measures exercise length */
int rc; /* curses char typed */
wchar_t *widep, *wideData;
double start_time=0, end_time; /* timing variables */
char message[MAX_WIN_LINE]; /* message buffer */
char drill_type; /* note of the drill type */
int chars_typed; /* count of chars typed */
bool seek_done = FALSE; /* was there a seek_label before exit? */
int error_sync; /* error resync state */
struct timeval tv;
/* note the drill type to see if we need to make the user repeat */
drill_type = SCR_COMMAND( line );
/* get the complete exercise into a single string */
data = buffer_command( script, line );
wideData = convertFromUTF8(data);
int numChars = wcslen(wideData);
/* allocate errors buffer to record error position */
errors_buf = (int*)malloc( numChars * sizeof(int));
if ( errors_buf == NULL )
fatal_error( _("internal error: malloc"), line );
/*
fprintf(F, "convresult=%d\n", convresult);
fprintf(F, "wideData='%ls'\n", wideData);
int i;
for (i = 0; i <= numChars; i++) {
fprintf(F, "wideData[%d]=%d\n", i, wideData[i]);
}
*/
/* count the lines in this exercise, and check the result
against the screen length */
for ( widep = wideData, lines_count = 0; *widep != ASCII_NULL; widep++ )
{
if ( *widep == ASCII_NL)
lines_count++;
}
if ( DP_TOP_LINE + lines_count > LINES )
fatal_error( _("data exceeds screen length"), line );
/* if the last command was a tutorial, ensure we have
the complete screen */
if ( global_prior_command == C_TUTORIAL )
{
move( T_TOP_LINE, 0 ); clrtobot();
}
while (1)
{
/* display speed test pattern */
linenum = DP_TOP_LINE;
move( linenum, 0 ); clrtobot();
for ( widep = wideData; *widep != ASCII_NULL; widep++ )
{
if ( *widep != ASCII_NL )
{
wideaddch(*widep);
}
else
{
/* emit return character */
wideaddch(RETURN_CHARACTER);
/* newline - move down the screen */
linenum++;
move( linenum, 0 );
}
}
move( MESSAGE_LINE, COLS - utf8len( MODE_SPEEDTEST ) - 2 );
ADDSTR_REV( MODE_SPEEDTEST );
/* run the data */
linenum = DP_TOP_LINE;
move( linenum, 0 );
for ( widep = wideData; *widep == ASCII_SPACE && *widep != ASCII_NULL; widep++ )
wideaddch(*widep);
for ( chars_typed = 0, errors_pos = 0, memset(errors_buf, 0, numChars * sizeof(int)), error_sync = 0;
*widep != ASCII_NULL; widep++, errors_pos++ )
{
rc = getch_fl( (*widep != ASCII_NL) ? *widep : RETURN_CHARACTER );
/* start timer on first char entered */
if ( chars_typed == 0 )
{
gettimeofday(&tv, NULL);
start_time = tv.tv_sec + tv.tv_usec / 1000000.0;
}
chars_typed++;
error_sync--;
/* check for delete keys if not at line start or
speed test start */
if ( rc == GTYPIST_KEY_BACKSPACE || rc == ASCII_BS || rc == ASCII_DEL )
{
/* just ignore deletes where it's impossible or hard */
if ( widep > wideData && *(widep-1) != ASCII_NL && *(widep-1) != ASCII_TAB ) {
/* back up one character */
ADDCH( ASCII_BS ); widep--;
/* Clear the error associated with the faulty character */
errors_buf[--errors_pos] = 0;
}
/* Do not account the backspace as a char typed as it could artificially lower the errors rate */
chars_typed--;
widep--; /* defeat widep++ coming up */
errors_pos--; /* defeat errors_pos++ coming up */
continue;
}
/* ESC is "give up"; ESC at beginning of exercise is "skip lesson"
(this is handled outside the for loop) */
if ( rc == ASCII_ESC )
break;
/* check that the character was correct */
if ( rc == *widep || ( cl_args.word_processor_flag &&
rc == ASCII_SPACE && *widep == ASCII_NL ))
{ /* character is correct */
if (*widep == ASCII_NL)
{
wideaddch(RETURN_CHARACTER);
}
else
{
wideaddch(rc);
}
}
else
{ /* character is incorrect */
/* try to sync with typist behind */
if ( error_sync >= 0 && widep > wideData && rc == *(widep-1) )
{
widep--;
errors_pos--;
continue;
}
wideaddch_rev(*widep == ASCII_NL ? RETURN_CHARACTER : *widep);
if ( ! cl_args.silent_flag ) {
do_bell();
}
errors_buf[errors_pos] = 1;
error_sync = 1;
/* try to sync with typist ahead */
if ( rc == *(widep+1) )
{
ungetch( rc );
error_sync++;
}
}
/* move screen location if newline */
if ( *widep == ASCII_NL )
{
linenum++;
move( linenum, 0 );
}
/* perform any other word processor like adjustments */
if ( cl_args.word_processor_flag )
{
if ( rc == ASCII_SPACE )
{
while ( *(widep+1) == ASCII_SPACE
&& *(widep+1) != ASCII_NULL )
{
widep++;
errors_pos++;
wideaddch(*widep);
}
}
else if ( rc == ASCII_NL )
{
while ( ( *(widep+1) == ASCII_SPACE
|| *(widep+1) == ASCII_NL )
&& *(widep+1) != ASCII_NULL )
{
widep++;
errors_pos++;
wideaddch(*widep);
if ( *widep == ASCII_NL )
{
linenum++;
move( linenum, 0 );
}
}
}
else if ( isalpha(*widep) && *(widep+1) == ASCII_DASH
&& *(widep+2) == ASCII_NL )
{
widep++;
errors_pos++;
wideaddch(*widep);
widep++;
errors_pos++;
wideaddch(*widep);
linenum++;
move( linenum, 0 );
}
}
}
/* ESC not at the beginning of the lesson: "give up" */
if ( rc == ASCII_ESC && chars_typed != 1)
continue; /* repeat */
/* skip timings and don't check error-pct if exit was through ESC */
if ( rc != ASCII_ESC )
{
/* Count all the errors made during the speed_test */
errors = 0;
for ( err_idx = 0; err_idx < numChars; err_idx++)
errors += errors_buf[err_idx];
/* display timings */
gettimeofday(&tv, NULL);
end_time = tv.tv_sec + tv.tv_usec / 1000000.0;
display_speed( chars_typed, end_time - start_time,
errors );
/* check whether the error-percentage is too high (unless in s:) */
if (drill_type != C_SPEEDTEST_PRACTICE_ONLY &&
is_error_too_high(chars_typed, errors))
{
sprintf( message, ERROR_TOO_HIGH_MSG, global_error_max );
wait_user (script, message, MODE_SPEEDTEST);
/* check for F-command */
if (global_on_failure_label != NULL)
{
/* move to the label position in the file */
if (fseek(script, global_on_failure_label->offset, SEEK_SET )
== -1)
fatal_error( _("internal error: fseek"), NULL );
global_line_counter = global_on_failure_label->line_count;
/* tell the user about the misery :) */
sprintf(message,SKIPBACK_VIA_F_MSG,
global_on_failure_label->label);
/* reset value unless persistent */
if (!global_on_failure_label_persistent)
global_on_failure_label = NULL;
wait_user (script, message, MODE_SPEEDTEST);
seek_done = TRUE;
break;
}
continue;
}
}
/* ask the user whether he/she wants to repeat or exit */
if ( rc == ASCII_ESC && cl_args.no_skip_flag ) /* honor --no-skip */
rc = do_query_repeat (script, FALSE);
else
rc = do_query_repeat (script, TRUE);
if (rc == 'E') {
seek_done = TRUE;
break;
}
if (rc == 'N')
break;
}
/* free the malloced memory */
free( data );
free( wideData );
free( errors_buf );
/* reset global_error_max */
if (!global_error_max_persistent)
global_error_max = cl_args.max_error_arg;
/* buffer_command takes care of advancing `script' (and setting
`line'), so we only do if seek_label had been called (in
do_query_repeat or due to a failure and an F: command) */
if (seek_done)
get_script_line( script, line );
global_prior_command = C_SPEEDTEST;
}
/*
* clear the complete screen, maybe leaving a header behind
*/
static void do_clear (FILE *script, char *line)
{
/* clear the complete screen */
move( B_TOP_LINE , 0 ); clrtobot();
banner (SCR_DATA (line));
/* finally, get the next script command */
get_script_line( script, line );
global_prior_command = C_CLEAR;
}
/*
go to a label - the flag is used to implement conditional goto's
*/
static void
do_goto( FILE *script, char *line, bool flag )
{
char *line_iterator;
/* reposition only if flag set - otherwise a noop */
if ( flag )
{
/* remove trailing whitespace from line */
line_iterator = line + strlen(line) - 1;
while (line_iterator != line && isspace(*line_iterator))
{
*line_iterator = '\0';
--line_iterator;
}
seek_label( script, SCR_DATA( line ), line );
}
get_script_line( script, line );
}
/*
Ask the user whether he/she wants to repeat, continue or exit
(this is used at the end of an exercise (drill/speedtest))
The second argument is FALSE if skipping a lesson isn't allowed (--no-skip).
*/
static char
do_query_repeat ( FILE *script, bool allow_next )
{
int resp;
/* display the prompt */
move( MESSAGE_LINE, 0 ); clrtoeol();
move( MESSAGE_LINE, COLS - utf8len( MODE_QUERY ) - 2 );
ADDSTR_REV( MODE_QUERY );
move( MESSAGE_LINE, 0 );
if (allow_next)
ADDSTR_REV( REPEAT_NEXT_EXIT_MSG );
else
ADDSTR_REV( REPEAT_EXIT_MSG );
/* wait for [RrNnEe] (or translation of these) */
while (TRUE)
{
resp = getch_fl( ASCII_NULL );
if (towideupper (resp) == 'R' ||
towideupper (resp) == RNE [0]) {
resp = 'R';
break;
}
if (allow_next && (towideupper (resp) == 'N' ||
towideupper (resp) == RNE [2])) {
resp = 'N';
break;
}
if (towideupper (resp) == 'E' || towideupper (resp) == RNE [4]) {
if (do_query_simple (CONFIRM_EXIT_LESSON_MSG))
{
seek_label (script, fkey_bindings [11], NULL);
resp = 'E';
break;
}
/* redisplay the prompt */
move( MESSAGE_LINE, 0 ); clrtoeol();
move( MESSAGE_LINE, COLS - utf8len( MODE_QUERY ) - 2 );
ADDSTR_REV( MODE_QUERY );
move( MESSAGE_LINE, 0 );
if (allow_next)
ADDSTR_REV( REPEAT_NEXT_EXIT_MSG );
else
ADDSTR_REV( REPEAT_EXIT_MSG );
}
}
/* clear out the message line */
move( MESSAGE_LINE, 0 ); clrtoeol();
return (char)resp;
}
/*
Same as do_query, but only used internally (doesn't set global_resp_flag,
returns the value instead) and doesn't accept Fkeys.
This is used to let the user confirm (E)xit.
*/
static bool
do_query_simple ( char *text )
{
int resp;
if (user_is_always_sure)
return TRUE;
/* display the prompt */
move( MESSAGE_LINE, 0 ); clrtoeol();
move( MESSAGE_LINE, COLS - strlen( MODE_QUERY ) - 2 );
ADDSTR_REV( MODE_QUERY );
move( MESSAGE_LINE, 0 );
ADDSTR_REV( text );
/* wait for Y/N or translation of Y/N */
do
{
resp = getch_fl( ASCII_NULL );
if (towideupper (resp) == 'Y' || towideupper (resp) == YN[0])
resp = 0;
else if (towideupper (resp) == 'N' || towideupper (resp) == YN[2])
resp = -1;
/* Some PDCURSES implementations return -1 when no key is pressed
for a second or so. So, unless resp is explicitly set to Y/N,
don't exit! */
else
resp = 2;
} while (resp != 0 && resp != -1);
/* clear out the message line */
move( MESSAGE_LINE, 0 ); clrtoeol();
return resp == 0 ? TRUE : FALSE;
}
/*
get a Y/N response from the user: returns true if we just got the
expected Y/N, false if exit was by a function key
*/
static bool
do_query( FILE *script, char *line )
{
int resp; /* response character */
int fkey; /* function key iterator */
bool ret_code;
/* display the prompt */
move( MESSAGE_LINE, 0 ); clrtoeol();
move( MESSAGE_LINE, COLS - strlen( MODE_QUERY ) - 2 );
ADDSTR_REV( MODE_QUERY );
move( MESSAGE_LINE, 0 );
ADDSTR_REV( SCR_DATA( line ) );
/* wait for a Y/N response, translation of Y/N or matching FKEY */
while ( TRUE )
{
resp = getch_fl( ASCII_NULL );
/* translate pseudo Fkeys into real ones if applicable
The pseudo keys are defined in array pfkeys and are also:
F1 - 1, F2 - 2, F3 - 3,.... F10 - 0, F11 - A, F12 - S */
for ( fkey = 1; fkey <= NFKEYS; fkey++ )
{
if ( resp == pfkeys[ fkey - 1 ] || (fkey<11 && resp == (fkey+'0'))
|| (fkey==10 && (resp =='0'))
|| (fkey==11 && (resp =='a' || resp=='A'))
|| (fkey==12 && (resp =='s' || resp=='S')))
{
resp = KEY_F( fkey );
break;
}
}
/* search the key bindings for a matching key */
for ( fkey = 1; fkey <= NFKEYS; fkey++ )
{
if ( resp == KEY_F( fkey )
&& fkey_bindings[ fkey - 1 ] != NULL )
{
seek_label( script, fkey_bindings[ fkey - 1 ],
NULL );
break;
}
}
if ( fkey <= NFKEYS ) {
ret_code = FALSE;
break;
}
/* no FKEY binding - check for Y or N */
if ( towideupper( resp ) == QUERY_Y ||
towideupper( resp ) == YN[0] )
{
ret_code = TRUE;
global_resp_flag = TRUE;
break;
}
if ( towideupper( resp ) == QUERY_N ||
towideupper( resp ) == YN[2] )
{
ret_code = TRUE;
global_resp_flag = FALSE;
break;
}
}
/* clear out the message line */
move( MESSAGE_LINE, 0 ); clrtoeol();
/* get the next command */
get_script_line( script, line );
/* tell the caller whether we got Y/N or a function key */
return ( ret_code );
}
/*
execute a E:-command: either "E: <value>%" (only applies to the next drill)
or "E: <value>%*" (applies until the next E:-command)
*/
static void
do_error_max_set( FILE *script, char *line )
{
char copy_of_line[MAX_SCR_LINE];
char *data;
bool star = FALSE;
char *tail;
double temp_value;
/* we need to make a copy for a potential error-message */
strcpy( copy_of_line, line );
/* hide whitespace (and '*') */
data = SCR_DATA( line ) + strlen( SCR_DATA( line ) ) - 1;
while (data != SCR_DATA(line) && !star && (isspace( *data ) || *data == '*'))
{
if (*data == '*')
star = TRUE;
*data = '\0';
--data;
}
data = SCR_DATA( line );
while (isspace( *data ))
++data;
/* set the state variables */
global_error_max_persistent = star;
if (strcmp( data, "default" ) == 0 || strcmp( data, "Default" ) == 0)
global_error_max = cl_args.max_error_arg;
else {
/* value is not a special keyword */
/* check for incorrect (not so readable) syntax */
data = data + strlen( data ) - 1;
if (*data != '%') {
/* find out what's wrong */
if (star && isspace( *data )) {
/* find out whether `line' contains '%' */
while (data != SCR_DATA( line ) && isspace( *data ))
{
*data = '\0';
--data;
}
if (*data == '%')
/* xgettext: no-c-format */
fatal_error( _("'*' must immediately follow '%'"), copy_of_line );
else
/* xgettext: no-c-format */
fatal_error( _("missing '%'"), copy_of_line );
} else
/* xgettext: no-c-format */
fatal_error( _("missing '%'"), copy_of_line );
}
if (isspace( *(data - 1) ))
/* xgettext: no-c-format */
fatal_error( _("'%' must immediately follow value"), copy_of_line );
/* remove '%' */
*data = '\0';
/* convert value: SCR_DATA(line) may contain whitespace at the
beginning, but strtod ignores this */
data = SCR_DATA( line );
errno = 0;
temp_value = (float)strtod( data, &tail );
if (errno)
fatal_error( _("overflow in do_error_max_set"), copy_of_line );
/* TODO: if line="E:-1.0%", then tail will be ".0 "...
if (*tail != '\0')
fatal_error( _("can't parse value"), tail );*/
/*
If --error-max is specified (but *not* if the default value is used),
an E:-command will only be applied if its level is more
difficult (smaller) than the one specified via --error-max/-e
*/
if (cl_args.max_error_given) {
if (temp_value < cl_args.max_error_arg)
global_error_max = temp_value;
else
global_error_max = cl_args.max_error_arg;
} else
global_error_max = temp_value;
}
/* sanity checks */
if (global_error_max < 0.0 || global_error_max > 100.0)
fatal_error( _("Invalid value for \"E:\" (out of range)"), copy_of_line );
/* get the next command */
get_script_line( script, line );
}
/*
*/
static void
do_on_failure_label_set( FILE *script, char *line )
{
char copy_of_line[MAX_SCR_LINE];
char *line_iterator;
bool star = FALSE;
int i;
char message[MAX_SCR_LINE];
/* we need to make a copy for a potential error-message */
strcpy( copy_of_line, line );
/* remove trailing whitespace (and '*') */
line_iterator = line + strlen( line ) - 1;
while (line_iterator != line && !star &&
(isspace( *line_iterator ) || *line_iterator == '*'))
{
if (*line_iterator == '*')
star = TRUE;
*line_iterator = '\0';
--line_iterator;
}
global_on_failure_label_persistent = star;
/* check for special value "NULL" */
if (strcmp(SCR_DATA(line), "NULL") == 0)
global_on_failure_label = NULL;
else
{
/* find the right hash list for the label */
i = hash_label( SCR_DATA(line) );
/* search the linked list for the label */
for ( global_on_failure_label = global_label_list[i];
global_on_failure_label != NULL;
global_on_failure_label = global_on_failure_label->next )
{
/* see if this is our label */
if ( strcmp( global_on_failure_label->label, SCR_DATA(line) ) == 0 )
break;
}
/* see if the label was not found in the file */
if ( global_on_failure_label == NULL )
{
sprintf( message, _("label '%s' not found"), SCR_DATA(line) );
fatal_error( message, copy_of_line );
}
}
/* get the next command */
get_script_line( script, line );
}
/*
execute the directives in the script file
*/
static void
parse_file( FILE *script, char *label ) {
char line[MAX_SCR_LINE]; /* line buffer */
char command; /* current command */
/* if label given then start running there */
if ( label != NULL )
{
/* find the label we want to start at */
seek_label( script, label, NULL );
}
else
{
/* start at the very beginning (a very good place to start) */
rewind( script );
global_line_counter = 0;
}
get_script_line( script, line );
/* just handle lines until the end of the file */
while( ! feof( script ))
{
command = SCR_COMMAND( line );
switch( command )
{
case C_TUTORIAL:
do_tutorial( script, line ); break;
case C_INSTRUCTION:
do_instruction( script, line ); break;
case C_CLEAR: do_clear( script, line ); break;
case C_GOTO: do_goto( script, line, TRUE ); break;
case C_EXIT: do_exit( script ); break;
case C_QUERY: do_query( script, line ); break;
case C_YGOTO: do_goto( script, line, global_resp_flag );
break;
case C_NGOTO: do_goto( script, line, !global_resp_flag );
break;
case C_DRILL:
case C_DRILL_PRACTICE_ONLY:
do_drill( script, line ); break;
case C_SPEEDTEST:
case C_SPEEDTEST_PRACTICE_ONLY:
do_speedtest( script, line ); break;
case C_KEYBIND: do_keybind( script, line ); break;
case C_LABEL:
__update_last_label (SCR_DATA (line));
get_script_line (script, line);
break;
case C_ERROR_MAX_SET: do_error_max_set( script, line ); break;
case C_ON_FAILURE_SET: do_on_failure_label_set( script, line ); break;
case C_MENU: do_menu (script, line); break;
default:
fatal_error( _("unknown command"), line );
break;
}
}
}
/*
Parse command line arguments and config file
*/
static void
parse_cmdline_and_config( int argc, char **argv )
{
// parse command line
if( cmdline_parser( argc, argv, &cl_args ) != 0 )
exit( 1 );
// check for existance of config file
const char *filename = get_config_filename();
FILE *cfile = fopen( filename, "r" );
if( cfile != NULL ) {
fclose( cfile );
// parse config file
struct cmdline_parser_params params;
cmdline_parser_params_init( ¶ms );
params.initialize = 0;
params.check_required = 0;
if( cmdline_parser_config_file( filename, &cl_args, ¶ms ) != 0 )
exit( 1 );
}
// check there is at most one script specified
if( cl_args.inputs_num > 1 ) {
fprintf( stderr, _( "Try '%s --help' for more information.\n" ), argv0 );
exit( 1 );
}
// check max-error is valid
if( cl_args.max_error_arg <= 0 || cl_args.max_error_arg > 100 ) {
fprintf( stderr, _( "%s: invalid error-max value\n" ), argv0 );
exit( 1 );
}
// check curs-flash is valid
if( cl_args.curs_flash_arg < 0 || cl_args.curs_flash_arg > 512 ) {
fprintf( stderr, _( "%s: invalid curs-flash value\n" ), argv0 );
exit( 1 );
}
// parse and check colours
if( sscanf( cl_args.colours_arg, "%d,%d",
&cl_fgcolour, &cl_bgcolour ) != 2 ||
cl_fgcolour < 0 || cl_fgcolour >= NUM_COLOURS ||
cl_bgcolour < 0 || cl_bgcolour >= NUM_COLOURS )
{
fprintf( stderr, _( "%s: invalid colours value\n" ), argv0 );
exit( 1 );
}
// parse and check banner-colors
if( sscanf( cl_args.banner_colors_arg, "%d,%d,%d,%d",
&cl_banner_fg_colour, &cl_banner_bg_colour,
&cl_prog_name_colour, &cl_prog_version_colour) != 4 ||
cl_banner_bg_colour < 0 || cl_banner_bg_colour >= NUM_COLOURS ||
cl_banner_fg_colour < 0 || cl_banner_bg_colour >= NUM_COLOURS ||
cl_prog_version_colour < 0 || cl_prog_version_colour >= NUM_COLOURS ||
cl_prog_name_colour < 0 || cl_prog_name_colour >= NUM_COLOURS )
{
fprintf( stderr, _( "%s: invalid banner-colours value\n" ), optarg );
exit( 1 );
}
}
/*
signal handler to stop curses stuff on intr
*/
static void
catcher( int signal ) {
/* unravel colours and curses, clean up and exit */
if ( cl_args.colours_given && has_colors() )
wbkgdset( stdscr, 0 );
clear(); refresh(); endwin();
printf("\n");
exit( 1 );
}
/*
open a script file
*/
FILE *open_script( const char *filename )
{
FILE *script;
#ifdef MINGW
/* MinGW's ftell doesn't work properly for absolute file positions in
text mode, so open in binary mode instead. */
script = fopen( filename, "rb" );
#else
script = fopen( filename, "r" );
#endif
/* record script filename */
if( script != NULL )
global_script_filename = strdup( filename );
return script;
}
/*
main routine
*/
int main( int argc, char **argv )
{
WINDOW *scr; /* curses window */
FILE *script; /* script file handle */
char *p, filepath[FILENAME_MAX]; /* file paths */
char script_file[FILENAME_MAX]; /* more file paths */
/* get our program name */
argv0 = argv[0] + strlen( argv[0] );
while ( argv0 > argv[0] && *argv0 != '/' )
argv0--;
if ( *argv0 == '/' ) argv0++;
/* Internationalization */
#if defined(LC_ALL)
setlocale (LC_ALL, "");
#endif
#if defined(ENABLE_NLS) && defined(LC_ALL)
bindtextdomain (PACKAGE, LOCALEDIR);
/* make gettext always return strings as UTF-8
=> this makes programming easier because now _all_ strings
(from gettext and from script file) are encoded as UTF8!
*/
bind_textdomain_codeset(PACKAGE, "utf-8");
textdomain (PACKAGE);
#endif
#ifdef MINGW
locale_encoding = "UTF-8";
#else
locale_encoding = nl_langinfo(CODESET);
#endif
isUTF8Locale = strcasecmp(locale_encoding, "UTF-8") == 0 ||
strcasecmp(locale_encoding, "UTF8") == 0;
/* printf("encoding is %s, UTF8=%d\n", locale_encoding, isUTF8Locale); */
/* this string is displayed in the mode-line when in a tutorial */
MODE_TUTORIAL=_(" Tutorial ");
/* this string is displayed in the mode-line when in a query */
MODE_QUERY=_(" Query ");
/* this string is displayed in the mode-line when running a drill */
MODE_DRILL=_(" Drill ");
/* this string is displayed in the mode-line when running a speedtest */
MODE_SPEEDTEST=_("Speed test");
WAIT_MESSAGE=
_(" Press RETURN or SPACE to continue, ESC to return to the menu ");
/* this message is displayed when the user has failed in a [DS]: drill */
ERROR_TOO_HIGH_MSG=
_(" Your error-rate is too high. You have to achieve %.1f%%. ");
/* this message is displayed when the user has failed in a [DS]: drill,
and an F:<LABEL> ("on failure label") is in effect */
SKIPBACK_VIA_F_MSG=
_(" You failed this test, so you need to go back to %s. ");
/* this is used for repeat-queries. you can translate the keys as well
(if you translate msgid "R/N/E" accordingly) */
REPEAT_NEXT_EXIT_MSG=
_(" Press R to repeat, N for next exercise or E to exit ");
/* this is used for repeat-queries with --no-skip. you can translate
the keys as well (if you translate msgid "R/N/E" accordingly) */
REPEAT_EXIT_MSG=
_(" Press R to repeat or E to exit ");
/* This is used make the user confirm (E)xit in REPEAT_NEXT_EXIT_MSG */
CONFIRM_EXIT_LESSON_MSG=
_(" Are you sure you want to exit this lesson? [Y/N] ");
/* This message is displayed if the user tries to skip a lesson
(ESC ESC) and --no-skip is specified */
NO_SKIP_MSG=
_(" Sorry, gtypist is configured to forbid skipping exercises. ");
/* this is used to translate the keys for Y/N-queries. Must be two
uppercase letters separated by '/'. Y/N will still be accepted as
well. Note that the messages (prompts) themselves cannot be
translated because they are read from the script-file. */
YN = convertFromUTF8(_("Y/N"));
if (wcslen(YN) != 3 || YN[1] != '/' || !iswideupper(YN[0]) || !iswideupper(YN[2]))
{
fprintf( stderr,
"%s: i18n problem: invalid value for msgid \"Y/N\" (3 uppercase UTF-8 chars?): %ls\n",
argv0, YN );
exit( 1 );
}
/* this is used to translate the keys for Repeat/Next/Exit
queries. Must be three uppercase letters separated by slashes. */
RNE = convertFromUTF8(_("R/N/E"));
if (wcslen(RNE) != 5 ||
!iswideupper(RNE[0]) || RNE[1] != '/' ||
!iswideupper(RNE[2]) || RNE[3] != '/' ||
!iswideupper(RNE[4]))
{
fprintf( stderr,
"%s: i18n problem: invalid value for msgid \"R/N/E\" (5 uppercase UTF-8 chars?): %ls\n",
argv0, RNE );
exit( 1 );
}
/* check for user home directory */
#ifdef MINGW
char *home_env = "APPDATA";
#else
char *home_env = "HOME";
#endif
global_home_dir = getenv( home_env );
if( !global_home_dir || !strlen( global_home_dir ) )
{
fprintf( stderr, _("%s: %s environment variable not set\n"), \
argv0, home_env );
exit( 1 );
}
/* parse command line argments and config file */
parse_cmdline_and_config( argc, argv );
/* figure out what script file to use */
if ( cl_args.inputs_num == 1 )
{
/* try and open scipr file from command line */
strcpy( script_file, cl_args.inputs[ 0 ] );
script = open_script( script_file );
/* we failed, so check for script in GTYPIST_PATH */
if( !script && getenv( "GTYPIST_PATH" ) )
{
for( p = strtok( getenv( "GTYPIST_PATH" ), ":" );
p != NULL; p = strtok( NULL, ":" ) )
{
strcpy( filepath, p );
strcat( filepath, "/" );
strcat( filepath, script_file );
script = open_script( filepath );
if( script )
break;
}
}
/* we failed, so try to find script in DATADIR */
if( !script )
{
strcpy( filepath, DATADIR );
strcat( filepath, "/" );
strcat( filepath, script_file );
script = open_script( filepath );
}
}
else
{
/* open default script */
sprintf( script_file, "%s/%s", DATADIR, DEFAULT_SCRIPT );
script = open_script( script_file );
}
/* check to make sure we open a script */
if( !script )
{
fprintf( stderr, "%s: %s %s\n",
argv0, _("can't find or open file"), script_file );
exit( 1 );
}
/* reset global_error_max */
global_error_max = cl_args.max_error_arg;
/* prepare for curses stuff, and set up a signal handler
to undo curses if we get interrupted */
scr = initscr();
signal( SIGINT, catcher );
signal( SIGTERM, catcher );
#ifndef MINGW
signal( SIGHUP, catcher );
signal( SIGQUIT, catcher );
#ifndef DJGPP
signal( SIGCHLD, catcher );
#endif
signal( SIGPIPE, catcher );
#endif
clear(); refresh(); typeahead( -1 );
keypad( scr, TRUE ); noecho(); curs_set( 0 ); raw();
// Quick hack to get rid of the escape delays
#ifdef __NCURSES_H
ESCDELAY = 1;
#endif
/* set up colour pairs if possible */
if (has_colors ())
{
start_color ();
init_pair (C_NORMAL,
colour_array [cl_fgcolour],
colour_array [cl_bgcolour]);
wbkgdset (stdscr, COLOR_PAIR (C_NORMAL));
init_pair (C_BANNER,
colour_array [cl_banner_fg_colour],
colour_array [cl_banner_bg_colour]);
init_pair (C_PROG_NAME,
colour_array [cl_banner_fg_colour],
colour_array [cl_prog_name_colour]);
init_pair (C_PROG_VERSION,
colour_array [cl_banner_fg_colour],
colour_array [cl_prog_version_colour]);
init_pair (C_MENU_TITLE,
colour_array [cl_fgcolour],
colour_array [cl_bgcolour]);
}
/* put up the top line banner */
clear();
banner (_("Loading the script..."));
if (!cl_args.no_welcome_screen_flag)
{
if (!do_beginner_infoview())
{
do_exit(script);
return 0;
}
}
check_script_file_with_current_encoding(script);
/* index all the labels in the file */
build_label_index( script );
/* run the input file */
parse_file( script, cl_args.start_label_arg );
do_exit( script );
/* for lint... */
return( 0 );
}
void do_bell() {
#ifndef MINGW
putchar( ASCII_BELL );
fflush( stdout );
#endif
}
bool get_best_speed( const char *script_filename,
const char *excersise_label, double *adjusted_cpm )
{
FILE *blfile; /* bestlog file */
char *search; /* string to match in bestlog */
char line[FILENAME_MAX]; /* single line from bestlog */
int search_len; /* length of search string */
bool found = FALSE; /* did we find it? */
int a;
char *fixed_script_filename; /* fixed-up script filename */
char *p;
/* open best speeds file */
blfile = fopen( get_bestlog_filename(), "r" );
if( blfile == NULL )
{
return FALSE;
}
/* fix-up script filename */
fixed_script_filename = strdup( script_filename );
if( fixed_script_filename == NULL )
{
perror( "malloc" );
fatal_error( _( "internal error: malloc" ), NULL );
}
p = fixed_script_filename;
while( *p != '\0' )
{
if( *p == ' ' )
*p = '+';
p++;
}
/* construct search string */
search_len = strlen( script_filename ) + strlen( excersise_label ) + 3;
search = (char *)malloc( search_len + 1 );
if( search == NULL )
{
perror( "malloc" );
fatal_error( _( "internal error: malloc" ), NULL );
}
sprintf( search, " %s:%s ", fixed_script_filename, excersise_label );
/* search for lines that match and use data from the last one */
while( fgets( line, FILENAME_MAX, blfile ) )
{
/* check that there are at least 19 chars (yyyy-mm-dd hh:mm:ss) */
for( a = 0; a < 19; a++ )
if( line[ a ] == '\0' )
continue;
/* look for search string and try to obtain a speed */
if( !strncmp( search, line + 19, search_len ) &&
sscanf( line + 19 + search_len, "%lg", adjusted_cpm ) == 1 )
{
found = TRUE;
}
}
/* cleanup and return */
free( search );
free( fixed_script_filename );
fclose( blfile );
return found;
}
void put_best_speed( const char *script_filename,
const char *excersise_label, double adjusted_cpm )
{
FILE *blfile; /* bestlog file */
char *fixed_script_filename; /* fixed-up script filename */
char *p;
/* open best speeds files */
blfile = fopen( get_bestlog_filename(), "a" );
if( blfile == NULL )
{
perror( "fopen" );
fatal_error( _("internal error: fopen" ), NULL );
}
/* fix-up script filename */
fixed_script_filename = strdup( script_filename );
if( fixed_script_filename == NULL )
{
perror( "malloc" );
fatal_error( _( "internal error: malloc" ), NULL );
}
p = fixed_script_filename;
while( *p != '\0' )
{
if( *p == ' ' )
*p = '+';
p++;
}
/* get time */
time_t nowts = time( NULL );
struct tm *now = localtime( &nowts );
/* append new score */
fprintf( blfile, "%04d-%02d-%02d %02d:%02d:%02d %s:%s %g\n",
now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour,
now->tm_min, now->tm_sec, fixed_script_filename, excersise_label,
adjusted_cpm );
/* cleanup */
free( fixed_script_filename );
fclose( blfile );
}
const char *get_config_filename()
{
static char *filename = NULL;
if( filename == NULL )
{
// calculate file name
filename = (char *)malloc(
strlen( global_home_dir ) + strlen( CONFIG_FILENAME ) + 2 );
if( filename == NULL )
{
perror( "malloc" );
fatal_error( _( "internal error: malloc" ), NULL );
}
sprintf( filename, "%s/%s", global_home_dir, CONFIG_FILENAME );
}
return filename;
}
const char *get_bestlog_filename()
{
static char *filename = NULL;
if( filename == NULL )
{
// calculate file name
filename = (char *)malloc(
strlen( global_home_dir ) + strlen( BESTLOG_FILENAME ) + 2 );
if( filename == NULL )
{
perror( "malloc" );
fatal_error( _( "internal error: malloc" ), NULL );
}
sprintf( filename, "%s/%s", global_home_dir, BESTLOG_FILENAME );
}
return filename;
}
/*
Local Variables:
tab-width: 8
End:
*/
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
* Using the GNU Compiler Collection (GCC)
* https://gcc.gnu.org/onlinedocs/gcc/index.html
* https://gcc.gnu.org
*
* https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
* https://www.cs.cmu.edu/~gilpin/tutorial/
* https://www.cs.umd.edu/~srhuang/teaching/cmsc212/gdb-tutorial-handout.pdf
* https://cseweb.ucsd.edu/classes/wi11/cse141/tutorial_gcc_gdb.html
*/
/*
* https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Optimize-Options.html#Optimize-Options
* https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Debugging-Options.html#Debugging-Options
* gcc -ggdb -Og -o pebbles garbage.c
*/
int main(int argc, char **argv) {
if (argc < 3) {
printf("%s\nUsage:\t<num> <num>\n", argv[0]);
return EXIT_FAILURE;
}
int a, b;
float c;
a = atoi(argv[1]);
b = atoi(argv[2]);
c = a / b;
printf("%d/%d = %f\n", a, b, c);
return EXIT_SUCCESS;
}
<file_sep>/*------------------- bubble7.c ------------------*/
/* Program bubble_7.c from PTRTUT10.HTM 6/10/97 */
#include <stdio.h>
#include <string.h>
#define MAX_BUF 256
long arr[10] = {3, 6, 1, 2, 3, 8, 4, 1, 7, 2};
char arr2[5][20] = {"<NAME>", "<NAME>", "<NAME>", "Goofy",
"<NAME>"};
void bubble(void *p, int width, int N, int (*fptr)(const void *, const void *));
int compare_string(const void *m, const void *n);
int compare_long(const void *m, const void *n);
int main(void) {
int i;
puts("\nBefore Sorting:\n");
for (i = 0; i < 10; i++) {
printf("%ld ", arr[i]);
}
puts("\n");
for (i = 0; i < 5; i++) {
printf("%s\n", arr2[i]);
}
bubble(arr, 4, 10, compare_long);
bubble(arr2, 20, 5, compare_string);
puts("\n\nAfter Sorting:\n");
for (i = 0; i < 10; i++) {
printf("%ld", arr[i]);
}
puts("\n");
for (i = 0; i < 5; i++) {
printf("%s\n", arr2[i]);
}
return 0;
}
void bubble(void *p, int width, int N,
int (*fptr)(const void *, const void *)) {
int i, j, k;
unsigned char buf[MAX_BUF];
unsigned char *bp = p;
for (i = N - 1; i >= 0; i--) {
for (j = 1; j <= i; j++) {
k = fptr((void *)(bp + width * (j - 1)), (void *)(bp + j * width));
if (k > 0) {
memcpy(buf, bp + width * (j - 1), width);
memcpy(bp + width * (j - 1), bp + j * width, width);
memcpy(bp + j * width, buf, width);
}
}
}
}
int compare_string(const void *m, const void *n) {
char *m1 = (char *)m;
char *n1 = (char *)n;
return (strcmp(m1, n1));
}
int compare_long(const void *m, const void *n) {
long *m1, *n1;
m1 = (long *)m;
n1 = (long *)n;
return (*m1 > *n1);
}
/*----------------- end of bubble7.c -----------------*/
<file_sep>/*
* https://raw.githubusercontent.com/bsouther/jsonf/master/README.md
* jsonf/src/jsonf.c
*
* https://raw.githubusercontent.com/bsouther/jsonf/master/src/jsonf.c
*/
#include <stdio.h>
int padLine(int level) {
int i;
printf("\n");
for (i = 0; i < level; i++)
printf(" ");
}
void process_fp(FILE *fp) {
int level = 0;
int last = -1;
int c;
int instr = 0;
int inesc = 0;
while ((c = fgetc(fp)) != EOF) {
if (instr && c == '\\') { /* escape */
inesc = !inesc;
} else if (inesc) {
inesc = 0;
if ('"' == c) {
printf("\"");
last = '1';
continue;
}
} else {
if (last == '"')
instr = !instr; /* quote */
if (!instr && last == ':')
printf(" ");
if (!instr) {
if (last == '{' || last == '[')
padLine(++level);
else if (last == ',')
padLine(level);
if (c == '}' || c == ']') {
if (level > 0)
level--;
padLine(level);
} else if (c == '{' || c == '[') {
if (last != ',' && last != '[' && last != '{')
padLine(level);
}
}
}
last = c;
if (instr || !(' ' == c || '\t' == c || '\r' == c || '\n' == c)) {
printf("%c", c);
}
/* Should the end of the JSON document. Flush stdout */
if (level <= 0 && (c == '}' || c == ']')) {
fflush(stdout);
}
}
}
int main(int argc, char *argv[]) {
FILE *fp = stdin;
if (2 == argc) { /* Work from a file */
fp = fopen(argv[1], "r");
if (!fp) {
fprintf(stderr, "Unable to open file: %s\n", argv[1]);
return 1;
}
}
process_fp(fp);
if (fp != stdin)
fclose(fp);
printf("\n");
return 0;
}
<file_sep>#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*
*
* 25.2 Parsing program options using getopt
* https://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt
* https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
*
* 25.2.2 Example of Parsing Arguments with getopt
*
* Here is an example showing how getopt is typically used. The key points to
* notice are:
*
* Normally, getopt is called in a loop. When getopt returns -1, indicating no
* more options are present, the loop terminates. A switch statement is used to
* dispatch on the return value from getopt. In typical use, each case just sets
* a variable that is used later in the program. A second loop is used to
* process the remaining non-option arguments.
*
* https://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Options.html#Getopt-Long-Options
* https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt
*/
int main(int argc, char **argv) {
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "abc:")) != -1)
switch (c) {
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
abort();
}
printf("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue);
for (index = optind; index < argc; index++)
printf("Non-option argument %s\n", argv[index]);
return 0;
}
/*
* output:
* % testopt
* aflag = 0, bflag = 0, cvalue = (null)
*
* % testopt -a -b
* aflag = 1, bflag = 1, cvalue = (null)
*
* % testopt -ab
* aflag = 1, bflag = 1, cvalue = (null)
*
* % testopt -c foo
* aflag = 0, bflag = 0, cvalue = foo
*
* % testopt -cfoo
* aflag = 0, bflag = 0, cvalue = foo
*
* % testopt arg1
* aflag = 0, bflag = 0, cvalue = (null)
* Non-option argument arg1
*
* % testopt -a arg1
* aflag = 1, bflag = 0, cvalue = (null)
* Non-option argument arg1
*
* % testopt -c foo arg1
* aflag = 0, bflag = 0, cvalue = foo
* Non-option argument arg1
*
* % testopt -a -- -b
* aflag = 1, bflag = 0, cvalue = (null)
* Non-option argument -b
*
* % testopt -a -
* aflag = 1, bflag = 0, cvalue = (null)
* Non-option argument -
*
*/
<file_sep>#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#define WIDTH 60
#define HEIGHT 20
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
#if defined(__APPLE__)
#define COMMON_DIGEST_FOR_OPENSSL
#include <CommonCrypto/CommonDigest.h>
#define SHA1 CC_SHA1
#else
#include <openssl/md5.h>
#endif
/* https://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c
*/
/* https://stackoverflow.com/questions/20007364/c-warning-about-visibility-of-a-struct
*/
/* ---------------------- addressbook.h ------------------------------------- */
struct node {
char key[128]; /* key[OUTPUT_SIZE]; */
char instance[128];
char dns_name[128];
char ip_prv[16];
char ip_pub[16];
struct node *next;
};
struct table {
int size;
struct node **list;
};
void init_buf(char *buf, size_t size);
void init_buf_unsigned(unsigned char *buf, size_t size);
void print_buf(char *buf, size_t buf_size);
void print_buf_unsigned(unsigned char *buf, size_t buf_size);
char *str2md5(const char *str, int length);
struct table *table_allocate(int size);
struct table *table_create();
void table_destroy(struct table *t);
int table_hash(char *output, char *key);
void table_insert(struct table *t, char *key, char *dns_name, char *ip_prv,
char *ip_pub);
void table_keys(struct table *t, char **keys);
void table_print_keys(struct table *t);
char *table_lookup(struct table *t, char *key);
void table_get(struct table *t, char *key, struct node *n);
int table_n_choices(struct table *choices);
char **table_choices(struct table *t);
void print_menu(WINDOW *menu_win, int highlight, struct table *t);
/* void table_list_increase(struct node **list); */
/* char *table_node_to_string(struct node *n); */
/* ---------------------- addressbook.h ------------------------------------- */
/*
* size_t DIGEST_SIZE = 16;
* size_t OUTPUT_SIZE = DIGEST_SIZE * sizeof(0x1);
* size_t OUTPUT_SIZE = 16 * 8;
*/
size_t DIGEST_SIZE = 16;
size_t OUTPUT_SIZE = 128;
/*
* Addressbook
*
* - [ ]: to_do_0
* - [ ]: to_do_1
*
* http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html
*
* The implementation of the lookup table is just stupid.
*/
void init_buf(char *buf, size_t size) {
init_buf_unsigned((unsigned char *)buf, size);
}
void init_buf_unsigned(unsigned char *buf, size_t size) {
size_t i;
for (i = 0; i < size; i++) {
buf[i] = i + '0'; // int to char conversion
}
}
void print_buf(char *buf, size_t buf_size) {
print_buf_unsigned((unsigned char *)buf, buf_size);
}
void print_buf_unsigned(unsigned char *buf, size_t buf_size) {
size_t i;
unsigned char c;
for (i = 0; i < buf_size; i++) {
c = buf[i];
if (c == '\0') {
printf("\\0");
} else {
printf("%c", buf[i]);
}
}
printf("\n");
}
char *str2md5(const char *str, int length) {
MD5_CTX c;
unsigned char *digest = (unsigned char *)malloc(DIGEST_SIZE);
if (digest == NULL) {
printf("cannot allocate memory for MD5 digest\n");
return NULL;
} else {
init_buf_unsigned(digest, DIGEST_SIZE);
DEBUG_PRINT(("digest initialized\n"));
}
char *output = (char *)malloc(OUTPUT_SIZE);
if (output == NULL) {
printf("cannot allocate memory for MD5 output\n");
return NULL;
} else {
init_buf(output, OUTPUT_SIZE);
DEBUG_PRINT(("output initialized\n"));
}
MD5_Init(&c);
DEBUG_PRINT(("MD5 CTX initialised\n"));
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
DEBUG_PRINT(("MD5 CTX finalised\n"));
/* print_buf(output, OUTPUT_SIZE); */
/* print_buf_unsigned(digest, DIGEST_SIZE); */
/*
* output will have 16 slots and each slot must contain sizeof("%02x")
* that is 8.
*
* printf("- sizeof (size_t)10: %lu\n", sizeof((size_t)10));
* printf("- sizeof (int)10: %lu\n", sizeof((int)10));
* printf("- sizeof (hex)0x10: %lu\n", sizeof(0x10));
* printf("- sizeof (unsigned char)'a': %lu\n", sizeof((unsigned char)'a'));
* printf("- sizeof (char *)\"10\": %lu\n", sizeof((char *)"10"));
* char *foo = (char *)malloc(10);
* sprintf(foo, "%02x", (unsigned int)digest[5]);
* printf("- sizeof (char *)\"%s\": %lu\n", foo, sizeof(foo));
* sprintf(foo, "%02x", 0x58);
* printf("- sizeof (char *)\"%s\": %lu\n", foo, sizeof(foo));
* sprintf(foo, "%c", 0x58);
* printf("- sizeof (char *)\"%2s\": %lu\n", foo, sizeof(foo));
* free(foo);
*
* Output:
* - sizeof (size_t)10: 8
* - sizeof (int)10: 4
* - sizeof (hex)0x10: 4
* - sizeof (unsigned char)'a': 1
* - sizeof (char *)"10": 8
* - sizeof (char *)"58": 8
* - sizeof (char *)"58": 8
* - sizeof (char *)" X": 8
*
*/
size_t n;
int b;
for (n = 0; n < DIGEST_SIZE; n++) {
char *s = &(output[n * 2]);
/*
* The snprintf() and vsnprintf() functions will write at most size-1 of the
* characters printed into the output string (the size'th character then
* gets the terminating `\0'); if the return value is greater than or equal
* to the size argument, the string was too short and some of the printed
* characters were discarded. The output is always null-terminated,
* unless size is 0.
*
* These functions return the number of characters printed (not including
* the trailing `\0' used to end output to strings), except for snprintf()
* and vsnprintf(), which return the number of characters that would have
* been printed if the size were unlimited (again, not including the final
* `\0'). These functions return a negative value if an error occurs.
*
* printf(
* "for n:%02lu characters that would have been printed:%02d\n", n, b);
*/
b = snprintf(s, 8, "%02x", (unsigned int)digest[n]);
}
DEBUG_PRINT(("MD5 output: %s", output));
return output;
}
struct table *table_allocate(int size) {
struct table *t = (struct table *)malloc(sizeof(struct table));
t->size = size;
t->list = (struct node **)malloc(sizeof(struct node *) * size);
int i;
for (i = 0; i < size; i++) {
DEBUG_PRINT(("creating...\n"));
t->list[i] = NULL;
}
DEBUG_PRINT(("there are %02d slots after creation\n", t->size));
return t;
}
/*
* sizeof struct table: 16
* printf("sizeof struct table: %lu\n", sizeof(struct table));
*
*/
struct table *table_create() {
struct table *t = (struct table *)malloc(1 * sizeof(struct table));
t->size = 0;
DEBUG_PRINT(("there are %02d slots after creation\n", t->size));
return t;
}
void table_destroy(struct table *t) {
if (t->size) {
struct node *temp = t->list[0];
while (temp) {
/* realloc(temp->key, 0); */
free(temp->key);
temp = temp->next;
}
free(t);
}
}
int table_hash(char *output, char *key) {
char *out = str2md5(key, strlen(key));
strcpy(output, out);
free(out);
return strlen(output);
}
void table_list_increase(struct node **list) {
if (!list) {
DEBUG_PRINT(("allocating list... "));
} else {
DEBUG_PRINT(("reallocating list... "));
}
*list = (struct node *)realloc(*list, sizeof(list) + sizeof(struct node));
DEBUG_PRINT(("done\n"));
}
void table_insert(struct table *t, char *key, char *dns_name, char *ip_prv,
char *ip_pub) {
char *output = (char *)malloc(OUTPUT_SIZE);
int pos = table_hash(output, key);
if (pos == 0) {
printf("cannot hash %s\n", key);
return;
} else {
DEBUG_PRINT(("hash length: %02d\n", pos));
}
struct node *new_node = (struct node *)malloc(sizeof(struct node));
if (new_node) {
DEBUG_PRINT(("new node allocated\n"));
} else {
DEBUG_PRINT(("not enough memory for a new node\n"));
return;
}
/*
* printf("list %p NULL? %s\n", list, (list == NULL ? "true" : "false"));
*/
DEBUG_PRINT(("created %s...\n", output));
strcpy(new_node->key, output);
strcpy(new_node->instance, key);
strcpy(new_node->dns_name, dns_name);
strcpy(new_node->ip_prv, ip_prv);
strcpy(new_node->ip_pub, ip_pub);
DEBUG_PRINT(("starting... "));
if (t->size) {
struct node **list = t->list;
struct node *temp = list[0];
DEBUG_PRINT(("first is %s:%s\n", temp->key, temp->val));
while (temp) {
DEBUG_PRINT(("browsing...\n"));
if (strcmp(temp->key, output) == 0) {
DEBUG_PRINT(("updating...\n"));
strcpy(new_node->instance, key);
strcpy(new_node->dns_name, dns_name);
strcpy(new_node->ip_prv, ip_prv);
strcpy(new_node->ip_pub, ip_pub);
return;
}
if (temp->next) {
temp = temp->next;
} else {
temp->next = new_node;
break;
}
}
table_list_increase(list);
DEBUG_PRINT(("adding at %d...\n", t->size));
t->list[t->size] = new_node;
} else {
DEBUG_PRINT(("new list...\n"));
t->list = (struct node **)malloc(sizeof(struct node *));
DEBUG_PRINT(("creating...\n"));
t->list[0] = new_node;
/* struct node *list_nodes[] = {new_node}; */
DEBUG_PRINT(("new list of nodes (%lu bytes)\n", sizeof(t->list)));
}
t->size++;
DEBUG_PRINT(("there are now %02d elements\n", t->size));
}
void table_keys(struct table *t, char **keys) {
if (t->size) {
int i = 0;
struct node *temp = t->list[0];
while (temp) {
keys[i] = temp->key;
temp = temp->next;
i++;
}
}
}
void table_print_keys(struct table *t) {
if (t->size) {
char **keys = (char **)malloc(sizeof(char *) * (t->size));
table_keys(t, keys);
int i = 0;
struct node *temp = t->list[0];
while (temp) {
printf("- %02d: %s\n", i, temp->key);
temp = temp->next;
i++;
}
} else {
printf("table is empty\n");
}
}
/* this resource must be free-ed. */
char *table_node_to_string(struct node *n) {
/* safe printing */
char *buf;
size_t sz;
sz = snprintf(NULL, 0, "[%s] %s: %s (%s)", n->instance, n->dns_name,
n->ip_pub, n->ip_prv);
buf = (char *)malloc(sz + 1);
if (buf == NULL) {
printf("cannot allocate memory for output\n");
exit(EXIT_FAILURE);
}
snprintf(buf, sz + 1, "%s: %s (%s)", n->dns_name, n->ip_pub, n->ip_prv);
return buf;
}
char *table_lookup(struct table *t, char *key) {
struct node *n = (struct node *)malloc(sizeof(struct node));
if (n == NULL) {
printf("cannot allocate memory to store the lookup result\n");
return NULL;
}
table_get(t, key, n);
if (n == NULL) {
printf("there is no node for the key: %s\n", key);
return NULL;
}
char *buf = table_node_to_string(n);
return buf;
}
void table_get(struct table *t, char *key, struct node *n) {
DEBUG_PRINT(("table size: %02d\n", t->size));
char *target = (char *)malloc(OUTPUT_SIZE);
int pos = table_hash(target, key);
free(target);
if (pos == 0) {
printf("cannot hash %s\n", key);
exit(EXIT_FAILURE);
} else {
DEBUG_PRINT(("looking for key: %s\n", target));
}
struct node *list = t->list[0];
struct node *temp = list;
while (temp) {
DEBUG_PRINT(("searching... %s ? %s\n", temp->key, target));
if (strcmp(temp->key, target) == 0) {
/* If you want to copy data then you copy using "data pointed to by pointers" */
*n = *temp;
return;
}
temp = temp->next;
}
n = NULL;
}
/* TODO: destroy and cleanup */
int startx = 0;
int starty = 0;
/*
* Instance:
* i-0ec73da0494f3d749 (bastion-labrador-vpc-production-1)
* Public DNS:
* ec2-34-244-194-18.eu-west-1.compute.amazonaws.com
*
* Instance:
* i-00ad8d6d61a0300b2 (bastion-labrador-vpc-global-1)
* Public DNS:
* ec2-34-245-144-59.eu-west-1.compute.amazonaws.com
*
* Instance:
* i-0d480d1d76b4c9a45 (bastion-labrador-vpc-yellow-1)
* Public DNS:
* ec2-34-242-199-165.eu-west-1.compute.amazonaws.com
*
* Instance:
* i-0586b93956ee04f6b (bastion-labrador-vpc-staging-1)
* Public DNS:
* ec2-54-171-161-63.eu-west-1.compute.amazonaws.com
*/
int table_n_choices(struct table *t) { return t->size; }
char **table_choices(struct table *t) {
char **c = (char **)malloc(sizeof(char *) * t->size);
struct node *temp = t->list[0];
for (int i = 0; i < t->size; i++) {
if ((c[i] = malloc(sizeof(char) * 128)) == NULL) {
printf("unable to allocate memory \n");
return NULL;
}
strcpy(c[i], temp->instance);
temp = temp->next;
}
return c;
}
void print_menu(WINDOW *menu_win, int highlight, struct table *t) {
int x, y, i;
x = 2; /* left padding */
y = 2; /* top padding */
box(menu_win, 0, 0);
char **choices = table_choices(t);
int st = table_n_choices(t);
choices = realloc(choices, sizeof(char *) * st + (sizeof(char) * 5));
choices[st] = "Exit";
st++;
for (i = 0; i < st; ++i) {
if (highlight == i + 1) { /* High light the present choice */
wattron(menu_win, A_REVERSE);
mvwprintw(menu_win, y, x, "%s", choices[i]);
wattroff(menu_win, A_REVERSE);
} else {
mvwprintw(menu_win, y, x, "%s", choices[i]);
}
++y; /* print the next line below */
}
wrefresh(menu_win);
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
WINDOW *menu_win;
int highlight = 1; /* highlight the first choice */
int choice = 0;
int c;
int n_choices = 0;
struct table *t = table_create();
table_insert(t, "i-0ec73da0494f3d749", "bastion-labrador-vpc-production-1",
"10.71.101.139", "192.168.3.11");
table_insert(t, "i-00ad8d6d61a0300b2", "bastion-labrador-vpc-global-1",
"10.85.101.66", "192.168.3.11");
table_insert(t, "i-0d480d1d76b4c9a45", "bastion-labrador-vpc-yellow-1",
"10.76.101.168", "192.168.3.11");
table_insert(t, "i-0586b93956ee04f6b", "bastion-labrador-vpc-staging-1",
"10.80.101.77", "192.168.3.11");
n_choices = table_n_choices(t);
char **choices = table_choices(t);
for (int jj = 0; jj < n_choices; jj++) {
DEBUG_PRINT(
("- instance: %s %s\n", choices[jj], table_lookup(t, choices[jj])));
}
initscr();
clear();
noecho();
cbreak(); /* Line buffering disabled. pass on everything */
startx = (80 - WIDTH) / 2;
starty = (24 - HEIGHT) / 2;
curs_set(0);
menu_win = newwin(HEIGHT, WIDTH, starty, startx);
keypad(menu_win, TRUE);
mvprintw(0, 0,
"Use arrow keys to go up and down, Press enter to select a choice");
refresh();
print_menu(menu_win, highlight, t);
n_choices++; /* because we added the "exit" option */
/*
* printw(string); / Print on stdscr at present cursor position /
* mvprintw(y, x, string);/ Move to (y, x) then print string /
* wprintw(win, string); / Print on window win at present cursor position /
* / in the window /
* mvwprintw(win, y, x, string); / Move to (y, x) relative to window /
* / co-ordinates and then print /
*
* int y, x; // to store where you are
* getyx(stdscr, y, x); // save current pos
* move(y, 0); // move to begining of line
* clrtoeol(); // clear line
* move(y, x); // move back to where you were
*/
while (1) {
/* clear the line that contains the debug test */
move(24, 0);
clrtoeol();
c = wgetch(menu_win);
switch (c) {
case KEY_UP:
move(28, 0);
clrtoeol();
/* if the key up is pressed when on the first choice already, the
* highlight goes to the last element (+1 because we have to consider the
* "exit" option).
*/
if (highlight == 1) {
highlight = n_choices;
} else {
--highlight;
}
mvprintw(24, 0, "up");
refresh();
break;
case KEY_DOWN:
move(28, 0);
clrtoeol();
if (highlight == n_choices)
highlight = 1;
else
++highlight;
mvprintw(24, 0, "down");
refresh();
break;
case 10:
choice = highlight;
move(24, 0);
clrtoeol();
mvprintw(24, 0, "10 (enter) is pressed on the choice %d/%d\n", choice,
n_choices);
clrtoeol();
if (choice == n_choices) {
move(28, 0);
clrtoeol();
mvprintw(28, 0, "eventually you are on the exit\n");
refresh();
break;
} else {
char *lur = table_lookup(t, choices[choice - 1]);
move(28, 0);
clrtoeol();
mvprintw(28, 0, "%s: %s", choices[choice - 1], lur);
move(29, 0);
clrtoeol();
struct node *res = (struct node *)malloc(sizeof(struct node));
table_get(t, choices[choice - 1], res);
mvprintw(29, 0, "ssh ec2-user@%s -A", res->ip_pub);
free(res);
free(lur);
}
refresh();
break;
default:
mvprintw(24, 0,
"Character pressed is = %3d Hopefully it can be printed as '%c'",
c, c);
refresh();
break;
}
print_menu(menu_win, highlight, t);
if (choice == n_choices) {
break;
}
}
move(29, 0);
clrtoeol();
if (choice == n_choices) {
mvprintw(23, 0, "bye");
} else {
mvprintw(29, 0, "You chose choice %d with choice string %s\n", choice,
choices[choice - 1]);
}
refresh();
clear();
refresh();
endwin();
return EXIT_SUCCESS;
}
<file_sep>/* source:
* https://raw.githubusercontent.com/lastland/Tricks-Museum/c32c1d2d266671ac9438463723026ccc95d5c4c1/FindFrequency2/FindFrequency2.c
*/
#include <stdio.h>
/*
* This is a method to find the only number that appears twice among other
* numbers appear three times. It uses bit computation method to record
* all bits that appear once and twice, so it can be used to find the number
* appears once as well.
* The code is simple and elegant.
* This method was found in Zhihu: http://www.zhihu.com/question/19659409
*/
unsigned long FindFrequency2(unsigned long *lst, unsigned long length) {
unsigned long *num;
unsigned long ones = 0, twos = 0, not_threes;
for (num = lst; num < lst + length; num++) {
twos |= ones & *num; // Record all bits appear twice
ones ^= *num; // Record all bits appear once
/*
* If a number appears three times, all bits of it are in both ones
* and twos. So we wipe out all bits in both of them from them.
*/
not_threes = ~(ones & twos);
ones &= not_threes;
twos &= not_threes;
}
return twos; // Return ones if you want the number appears once
}
int main() {
unsigned long lst[] = {1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4};
printf("%lu\n", FindFrequency2(lst, 11));
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
* Exercises
*
* - [Exs 00]:
*
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>/*
* http://www.cs.yale.edu/homes/aspnes/pinewiki/attachments/C(2f)FloatingPoint/float.c
*/
/* prints a lot of information about floating-point numbers */
#include <math.h>
#include <stdio.h>
#include <values.h>
/* endianness testing */
const int EndianTest = 0x04030201;
#define LITTLE_ENDIAN() (*((const char *)&EndianTest) == 0x01)
/* extract nth LSB from object stored in lvalue x */
#define GET_BIT(x, n) \
((((const char *)&x)[LITTLE_ENDIAN() ? (n) / CHARBITS \
: sizeof(x) - (n) / CHARBITS - 1] >> \
((n) % CHARBITS)) & \
0x01)
#define PUT_BIT(x, n) (putchar(GET_BIT((x), (n)) ? '1' : '0'))
void print_float_bits(float f) {
int i;
i = FLOATBITS - 1;
PUT_BIT(f, i);
putchar(' ');
for (i--; i >= 23; i--) {
PUT_BIT(f, i);
}
putchar(' ');
for (; i >= 0; i--) {
PUT_BIT(f, i);
}
}
int main(int argc, char **argv) {
float f;
while (scanf("%f", &f) == 1) {
printf("%10g = %24.17g = ", f, f);
print_float_bits(f);
putchar('\n');
}
return 0;
}
<file_sep>
/**
** @brief Call a three-parameter function with default arguments
** set to 0
**/
#define ZERO_DEFAULT3(...) ZERO_DEFAULT3_0(__VA_ARGS__, 0, 0, )
#define ZERO_DEFAULT3_0(FUNC, _0, _1, _2, ...) FUNC(_0, _1, _2)
#define strtoul(...) ZERO_DEFAULT3(strtoul, __VA_ARGS__)
#define strtoull(...) ZERO_DEFAULT3(strtoull, __VA_ARGS__)
#define strtol(...) ZERO_DEFAULT3(strtol, __VA_ARGS__)
/*
* Here, the macro ZERO_DEFAULT3 works by subsequent addition and removal of
* argu- ments. It is supposed to receive a function name and at least one first
* argument that is to be passed to that function. First, a set of 0 is appended
* to the argument list and then, if this results in more than three combined
* arguments, the excess is omitted. So for a call with just one argument the
* sequence of replacements looks as follows:
*/
/* strtoul(argv[1])
* // ...
* ZERO_DEFAULT3(strtoul, argv[1])
* // ...
* ZERO_DEFAULT3_0(strtoul, argv[1], 0, 0, )
* // FUNC , _0 ,_1,_2,...
* strtoul(argv[1], 0, 0)
*/
/* Because of the special rule that inhibits recursion in macro expansion,
* the final function call to strtoul will not be expanded further
* and passed on to the next
* compilation phases.If instead we call strtoul with three arguments
*/
/*
* strtoul(argv[1], ptr, 10)
* //
* ZERO_DEFAULT3(strtoul, argv[1], ptr, 10)
* //
* ZERO_DEFAULT3_0(strtoul, argv[1], ptr, 10, 0, 0, 0);
* // (FUNC , _0 , _1 , _2. ...
* strtoul(argv[1], ptr, ptr, 10)
*/
/* the sequence of replacements effectively results in exactly the same tokens
* with which we started.
*/
<file_sep>/*
* URLr - based on libcURL
* https://curl.haxx.se/libcurl/
* https://curl.haxx.se/libcurl/c/
*
* http://xmlsoft.org/index.html
* https://github.com/GNOME/libxml2
* https://github.com/curl/curl/raw/master/docs/examples/
*
* For compilers to find libxml2 you may need to set:
* export LDFLAGS="-L/usr/local/opt/libxml2/lib"
* export CPPFLAGS="-I/usr/local/opt/libxml2/include"
*
* For pkg-config to find libxml2 you may need to set:
* export PKG_CONFIG_PATH="/usr/local/opt/libxml2/lib/pkgconfig"
*
* PKGC_FLAGS = $(shell pkg-config --cflags --libs libcurl)
*
* LXML_FLAGS = ${shell /usr/local/opt/libxml2/bin/xml2-config --cflags --libs}
* $ /usr/local/opt/libxml2/bin/xml2-config --cflags
* -I/usr/local/Cellar/libxml2/2.9.7/include/libxml2
* $ /usr/local/opt/libxml2/bin/xml2-config --libs
* -L/usr/local/Cellar/libxml2/2.9.7/lib -lxml2 -lz -lpthread -liconv -lm
*
*/
#include <ctype.h>
#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libxml/HTMLparser.h>
#include <libxml/uri.h>
#include <libxml/xpath.h>
/* curl write callback
*
* CURLOPT_WRITEFUNCTION explained
* CURLOPT_WRITEFUNCTION - set callback for writing received data
*
* SYNOPSIS
* #include <curl/curl.h>
*
* size_t write_callback(char *ptr, size_t size, size_t nmemb, void
* *userdata);
*
* CURLcode curl_easy_setopt(CURL *handle, CURLOPT_WRITEFUNCTION,
* write_callback);
*
* DESCRIPTION
* Pass a pointer to your callback function, which should match the
* prototype shown above.
*
* This callback function gets called by libcurl as soon as there is
* data received that needs to be saved. ptr points to the delivered
* data, and the size of that data is nmemb; size is always 1.
*
* The callback function will be passed as much data as possible in all
* invokes, but you must not make any assumptions.
*
*/
uint write_callback(char *in, uint size, uint nmemb, void *out) {
size_t written = fwrite(in, size, nmemb, out);
return written;
}
/* resizable buffer */
typedef struct {
char *buf;
size_t size;
} memory;
size_t grow_buffer(void *contents, size_t sz, size_t nmemb, void *ctx) {
size_t realsize = sz * nmemb;
memory *mem = (memory *)ctx;
char *ptr = realloc(mem->buf, mem->size + realsize);
if (!ptr) {
/* out of memory */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->buf = ptr;
memcpy(&(mem->buf[mem->size]), contents, realsize);
mem->size += realsize;
return realsize;
}
int parse(char *url) {
CURL *curl;
int curl_err = 0;
curl = curl_easy_init();
if (!curl) {
fprintf(stderr, "cannot create a cURL handler\n");
return EXIT_FAILURE;
}
curl_easy_setopt(curl, CURLOPT_URL, url);
/* curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, parse_callback); */
/* curl_easy_setopt(curl, CURLOPT_WRITEDATA, hsp); */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/*
* curl_easy_perform - perform a blocking file transfer
*
* https://curl.haxx.se/libcurl/c/curl_easy_perform.html
*
* #include <curl/curl.h>
* CURLcode curl_easy_perform(CURL * easy_handle );
*
* Invoke this function after curl_easy_init and all the curl_easy_setopt
* calls are made, and will perform the transfer as described in the options.
* It must be called with the same easy_handle as input as the curl_easy_init
* call returned.
*
* curl_easy_perform performs the entire request in a blocking manner and
* returns when done, or if it failed. For non-blocking behavior, see
* curl_multi_perform.
*
* You can do any amount of calls to curl_easy_perform while using the same
* easy_handle. If you intend to transfer more than one file, you are even
* encouraged to do so. libcurl will then attempt to re-use the same
* connection for the following transfers, thus making the operations faster,
* less CPU intense and using less network resources. Just note that you will
* have to use curl_easy_setopt between the invokes to set options for the
* following curl_easy_perform.
*
* You must never call this function simultaneously from two places using the
* same easy_handle. Let the function return first before invoking it another
* time. If you want parallel transfers, you must use several curl
* easy_handles.
*
* While the easy_handle is added to a multi handle, it cannot be used by
* curl_easy_perform.
*
* Return value
* CURLE_OK (0) means everything was ok, non-zero means an error occurred as
* <curl/curl.h> defines - see libcurl-errors. If the CURLOPT_ERRORBUFFER was
* set with curl_easy_setopt there will be a readable error message in the
* error buffer when non-zero is returned.
*/
curl_err = curl_easy_perform(curl);
/* Check for errors */
if (curl_err != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(curl_err));
} else {
/* https://curl.haxx.se/libcurl/c/libcurl-errors.html */
fprintf(stdout, "curl_easy_perform() success: %d\n", curl_err);
}
curl_easy_cleanup(curl);
/* html_parser_cleanup(hsp); */
return curl_err;
}
int main(int argc, char **argv) {
int aflag = 0;
int tflag = 0;
char *url = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "atu:")) != -1)
switch (c) {
case 'a':
aflag = 1;
break;
case 't':
tflag = 1;
break;
case 'u':
url = optarg;
break;
case '?':
if (optopt == 'u')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
abort();
}
printf("aflag = %d, tflag = %d, URL = %s\n", aflag, tflag, url);
for (index = optind; index < argc; index++) {
printf("Non-option argument %s\n", argv[index]);
}
if (url == NULL) {
url = "https://www.example.org";
}
int ret = 0;
ret = parse(url);
printf("quitting with %d\n", ret);
return ret;
}
<file_sep>#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#ifndef LIFE_H
#define LIFE_H
/* C's mutex lock interface */
int mtx_lock(mtx_t *);
int mtx_unlock(mtx_t *);
int mtx_trylock(mtx_t *);
int mtx_timedlock(mtx_t *restrict, const struct timespec *restrict);
int mtx_init(mtx_t *, int);
void mtx_destroy(mtx_t *);
/* life_h
* Parameters that will dynamically be changed by different threads
*/
typedef struct {
size_t _Atomic constellations; //< constellations visited
size_t _Atomic x0; //< cursor position , row
size_t _Atomic x1; //< cursor position , column
size_t _Atomic frames; //< FPS for display
bool _Atomic finished; //< this game is finished
mtx_t mtx; //< mutex that protects Mv
/*
* This member mtx has the special type mtx_t type for mutual exclusion that
* also comes with threads.h. It is meant to protect the critical data, namely
* Mv, while it is accessed in a well identified part of the code, a so-called
* critical section. The most simple use case for this mutex is in the center
* of the drawing thread, where two calls, mtx_lock and mtx_unlock, protect
* the access to the life data structure L.
*/
/* Its main ingredient is a call to cnd_timedwait that takes a so-called
* condition variable of type cnd_t, a mutex and an absolute time bound. Such
* condition variables are used to identify a condition for which a thread
* might want to wait.
*
* The conditions in each of these loops reflects the cases when there is work
* to do for either of these tasks.
*/
cnd_t draw; //< cnd that controls drawing
cnd_t acco; //< cnd that controls accounting
cnd_t upda; //< cnd that controls updating
/* The basic idea of restrict is relatively simple: it tells the compiler that
* the pointer in question is the only access to the object it points to. Thus
* the compiler can make the assumption that changes to the object can only
* occur through that same pointer, and the object cannot change
* inadvertently. In other words, with restrict we are telling the compiler
* that the object does not alias with any other object that the compiler
* handles in this part of code.
*/
void *restrict Mv; //< bool M[n0][n1];
bool (*visited)[life_maxit]; //< hashing constellations
/*
* This member mtx has the special type mtx_t type for mutual exclusion that
* also comes with threads.h. It is meant to protect the critical data, namely
* Mv, while it is accessed in a well identified part of the code, a so-called
* critical section. The most simple use case for this mutex is in the center
* of the drawing thread, where two calls, mtx_lock and mtx_unlock, protect
* the access to the life data structure L.
*/
} life;
/* Its main ingredient is a call to cnd_timedwait that takes a so-called
* condition variable of type cnd_t, a mutex and an absolute time bound. */
int life_wait(cnd_t *cnd, mtx_t *mtx) {
struct timespec now;
timespec_get(&now, TIME_UTC);
now.tv_sec += 1;
return cnd_timedwait(cnd, mtx, &now);
}
#endif
/*
* https://en.cppreference.com/w/c/thread
* #include <threads.h>
*/
#ifdef __STDC_NO_THREADS__
/* https://computing.llnl.gov/tutorials/pthreads/ */
#include <pthread.h>
#endif
/*
* #include <threads.h>
* typedef int (*thrd_start_t)(void*);
* int thrd_create(thrd_t*, thrd_start_t , void*);
* int thrd_join(thrd_t , int *);
*/
/* why there is no <threads.h> on MacOS?
*
* http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
* The `gcc` document [C11 status](http://gcc.gnu.org/wiki/C11Status) indicates
* that it does not support threading, it says:
*
* > Threading [Optional] | Library issue (not implemented)
*
* As the document indicates this is not really a `gcc` or `clang` issue
* but `glibc` issue. ...
* [there may be work under way soon]
* (https://sourceware.org/ml/libc-alpha/2014-03/msg00451.html) to get
* support for this into `glibc` but that won't help you now. You can use
* [this][1] in the meantime.
*
* [1]: https://github.com/jtsiomb/c11threads/blob/master/c11threads.h
*
* ### Fixed for glibc 2.28 ###
*
* According the
* [Bug 14092 - Support C11 threads]
* (https://sourceware.org/bugzilla/show_bug.cgi?id=14092#c10) this will
* be fixed in glibc 2.8:
*
* > Implemented upstream by:
* > 9d0a979 Add manual documentation for threads.h
* > 0a07288 nptl: Add test cases for ISO C11 threads
* > c6dd669 nptl: Add abilist symbols for C11 threads
* > 78d4013 nptl: Add C11 threads tss_* functions
* > 918311a nptl: Add C11 threads cnd_* functions
* > 3c20a67 nptl: Add C11 threads call_once functions
* > 18d59c1 nptl: Add C11 threads mtx_* functions
* > ce7528f nptl: Add C11 threads thrd_* functions
* >
* > It will be included in 2.28.
*
* https://stackoverflow.com/a/22875599
* https://sourceware.org/bugzilla/show_bug.cgi?id=14092
*/
/* Threading rules
* Rule 3.19.2.1 Pass thread specific data through function arguments.
* Rule 3.19.2.2 Keep thread specific state in local variables.
* Rule 3.19.2.3 Use thread_local if initialization can be determined at
* compile time.
* Rule 3.19.3.1 Every mutex must be initialized with mtx_init.
* The second parameter of mtx_init specifies the “type” of the
* mutex. It must be one of four different values, mtx_plain,
* mtx_timed, mtx_plain|mtx_recursive, or mtx_timed|mtx_recursive.
* Rule 3.19.3.2 A thread that holds a non-recursive mutex must not call any
* of the mutex lock function for it.
* Rule 3.19.3.3 A recursive mutex is only released after the holding thread
* issues as many calls to mtx_unlock as it has acquired locks.
* Rule 3.19.3.4 A locked mutex must be released before the termination of the
* thread.
* Rule 3.19.3.5 A thread must only call mtx_unlock on a mutex that it holds.
* Rule 3.19.3.6 Each successful mutex lock corresponds to exactly one call
* to mtx_unlock.
* Rule 3.19.3.7 A mutex must be destroyed at the end of its lifetime.
* Rule 3.19.4.1 On return from a cnd_t wait, the expression must be checked,
* again.
* Rule 3.19.4.2 A condition variable can only be used simultaneously with
* one mutex.
* Rule 3.19.4.3 A cnd_t must be initialized dynamically.
* Rule 3.19.4.4 A cnd_t must be destroyed at the end of its lifetime.
* Rule 3.19.5.1 Returning from main or calling exit terminates all threads.
* Rule 3.19.5.2 While blocking on mtx_t or cnd_t a thread frees processing
* resources.
*/
/*
* If a storage class specifier is not sufficient because you have to do dynamic
* initialization and destruction, we can use thread specific storage, tss_t.
* It abstracts the identifica- tion of thread specific data into an opaque id,
* referred to as key, and accessor function to set or get the data:
*
* The function that is called at
* the end of a thread to destroy the thread specific data is specified as a
* function pointer of type tss_dtor_t when the key is created.
*/
/* in threads.h
* typedef void (*tss_dtor_t)(void *); // pointer to destructor
* int tss_create(tss_t *key, tss_dtor_t dtor); // returns error indication
* void tss_delete(tss_t key);
* void *tss_get(tss_t key); // returns pointer to object int tss_set(tss_t key,
* // void *val); // returns error indication
* int tss_set(tss_t key, void *val); // returns error indication
*/
/*
* Threads in C are dealt through two principal function interfaces that can be
* used to start a new thread and then to wait for the termination of such a
* thread. Here the second argument of thrd_create is a function pointer of type
* thrd_start_t. This function is executed at the start of the new thread. As we
* can see from the typedef the function receives a void* pointer and returns an
* int. The type thrd_t is an opaque type, that will identify the newly created
* thread.
*/
typedef int (*thrd_start_t)(void *);
int thrd_create(thrd_t *, thrd_start_t, void *);
int thrd_join(thrd_t, int *);
static int update_thread(void *);
static int draw_thread(void *);
static int input_thread(void *);
static int account_thread(void *);
/* the implementation of the account_thread */
static int account_thread(void *Lv) {
life *restrict L = Lv;
while (!L->finished) {
// block until there is work
mtx_lock(&L->mtx);
/* a conditional loop that can only be left once either
* - the game is finished, or
* - another thread has advanced an iteration count.
* The body of this loop is a call to life_wait, a function that suspends
* the calling thread for one second or until a specific event occurs: */
while (!L->finished && (L->accounted == L->iteration)) {
life_wait(&L->acco, &L->mtx);
}
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
life_account(L);
/* the condition for termination is if the game had previously entered the
* same sequence of repetition game configurations. */
if ((L->last + repetition) < L->accounted) {
L->finished = true;
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cnd_signal(&L->upda);
mtx_unlock(&L->mtx)
}
return 0;
}
/* the implementation of the draw_thread */
static int draw_thread(void *Lv) {
life *restrict L = Lv;
while (!L->finished && (L->iteration <= L->drawn) && (x0 == L->x0) &&
(x1 == L->x1))
life_wait(&L->draw, &L->mtx);
while (!L->finished) {
if (L->n0 <= 30)
life_draw(L);
else
life_draw4(L);
L->drawn++;
}
return 0;
}
/* clang-format off */
static int input_thread(void *Lv) {
termin_unbuffered();
life *restrict L = Lv;
enum {
len = 32,
};
char command[len];
do {
int c = getchar();
command[0] = c;
switch (c) {
case GO_LEFT: life_advance(L, 0, -1); break;
case GO_RIGHT: life_advance(L, 0, +1); break;
case GO_UP: life_advance(L, -1, 0); break;
case GO_DOWN: life_advance(L, +1, 0); break;
case GO_HOME: L->x0 = 1; L->x1 = 1; break;
case ESCAPE:
ungetc(termin_translate(termin_read_esc(len, command)), stdin);
continue;
case '+':
if (L->frames < 128) L->frames++;
continue;
case '-':
if (L->frames > 1) L->frames--;
continue;
case ' ':
case 'b':
case 'B':
mtx_lock(&L->mtx);
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
life_birth9(L);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
mtx_unlock(&L->mtx);
break;
case 'q':
case 'Q':
case EOF: goto FINISH;
}
cnd_signal(&L->draw);
} while (!(L->finished || feof(stdin)));
FINISH:
L->finished = true;
return 0;
}
/* clang-format on */
static int update_thread(void *Lv) {
life *restrict L = Lv;
while (!L->finished) {
/* ... */
}
return 0;
}
life L = LIFE_INITIALIZER;
void B9_atexit(void) {
/* Put the board in a nice final picture. */ L.iteration = L.last;
life_draw(&L);
life_destroy(&L);
}
int update_thread(void *Lv) {
/* Nobody should ever wait for this thread. */
thrd_detach(thrd_current());
/* Delegate part of our job to an auxiliary thread. */
thrd_create(&(thrd_t){0}, account_thread, Lv);
}
int main(int argc, char *argv[argc + 1]) {
/* Use commandline arguments for the size of the board. */
size_t n0 = 30;
size_t n1 = 80;
if (argc > 1)
n0 = strtoull(argv[1], 0, 0);
if (argc > 2)
n1 = strtoull(argv[2], 0, 0);
/* Create an object that holds the game’s data. */
life_init(&L, n0, n1, M);
atexit(B9_atexit);
/* Create four threads that operate all on that same object and
* discard their ids.
*/
thrd_create(&(thrd_t){0}, update_thread, &L);
thrd_create(&(thrd_t){0}, draw_thread, &L);
thrd_create(&(thrd_t){0}, input_thread, &L);
/* End this thread nicely and let the threads go on
nicely. */
thrd_exit(0);
}
<file_sep>#include "queen_attack.h"
int abs(int n) {
if (n < 0) {
return -n;
}
return n;
}
int valid(position_t p) {
if (p.row < 0 || p.column < 0 || p.row > 7 || p.column > 7) {
return 0;
}
return 1;
}
int valid_black(position_t p) {
if (p.row < 0 || p.column > 7) {
return 0;
}
return 1;
}
int overlap(position_t a, position_t b) {
if (a.row == b.row && a.column == b.column) {
return 1;
}
return 0;
}
attack_status_t can_attack(position_t queen_1, position_t queen_2) {
if (overlap(queen_1, queen_2)) {
return INVALID_POSITION;
}
if (!valid(queen_1) || !valid(queen_2)) {
return INVALID_POSITION;
}
if ((queen_1.row == queen_2.row) || (queen_1.column == queen_2.column)) {
return CAN_ATTACK;
}
if (abs(queen_1.row - queen_2.row) == abs(queen_1.column - queen_2.column)) {
return CAN_ATTACK;
}
return CAN_NOT_ATTACK;
}
<file_sep>#ifndef BINARY_H
#define BINARY_H
#define INVALID -1
int convert(char *s);
#endif
<file_sep>#include "binary_search.h"
int *binary_search(int x, int *list, size_t l) {
if (!l)
return NULL;
if (!list)
return NULL;
/* the simple (a + b) / 2 could overflow */
int a = 0;
int b = l - 1;
while (a <= b) {
int m = a + (b - a) / 2;
if (x == list[m])
return &list[m];
if (x > list[m])
a = m + 1;
if (x < list[m])
b = m - 1;
}
return NULL;
}
<file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
enum {
buf_max = 32,
};
int main(int argc, char *argv[argc + 1]) {
int ret = EXIT_FAILURE;
char buffer[buf_max] = {0};
for (int i = 1; i < argc; ++i) {
// process args
FILE *instream = fopen(argv[i], " r "); // as file names
if (instream) {
while (fgets(buffer, buf_max, instream)) {
fputs(buffer, stdout);
}
fclose(instream);
ret = EXIT_SUCCESS;
} else {
/* Provide some error diagnostic . */
fprintf(stderr, " Could not open %s: ", argv[i]);
perror(0);
errno = 0;
// reset error code
}
}
return ret;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/* Aggregate data types
To deal with char arrays and strings, there are a bunch of functions in
the standard library that come with the header string.h. Those that just
suppose an array start their names with "mem" and those that in addition
suppose that their arguments are strings start with "str".
Functions that operate on char-arrays:
- memcpy(target, source, len) can be use to copy one array to another. These
have to be known to be distinct arrays. The number of char to be copied must
be given as a third argument len.
- memcmp(s0, s1, len) compares two arrays in the lexicographic ordering. That
is it first scans initial parts of the two arrays that happen to be
equal and then returns the difference between the two first characters
that are distinct. If no differing elements are found up to len, 0 is
returned.
- memchr(s, c, len) searches array s for the appearance of character c.
String functions:
- strlen(s) returns the length of the string s. This is simply the
position of the first 0-character and not the length of the array. It is
your duty to ensure that s is indeed a string, that is that it is
0-terminated.
- strcpy(target, source) works similar to memcpy. It only copies up to
the string length of the source, and therefore it doesn’t need a len
parameter. Again, source must be 0-terminated. Also, target must be big
enough to hold the copy.
- strcmp(s0, s1) compares two arrays in the lexicographic ordering
similar to memcmp, but may not take some language specialties into
account. The comparison stops at the first 0-character that is
encountered in either s0 or s1. Again, both parameters have to be
0-terminated.
- strcoll(s0, s1) compares two arrays in the lexicographic ordering
respecting language specific environment settings.
- strchr(s, c) is similar to memchr, only that the string s must be
0-terminated.
- strspn(s0, s1) returns the number of initial characters in s0 that
also appear in s1.
- strcspn(s0, s1) returns the number of initial characters in s0 that do
not appear in s1.
** Exercises
- [Exs 31]: Use memchr and memcmp to implement a bounds checking
version of strcmp.
*/
typedef enum { RANDOM, IMMEDIATE, SEARCH } strategy_type;
typedef enum { LT, GT, EQ, CONTINUE } cmp_type;
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
/* memchr
const void * memchr ( const void * ptr, int value, size_t num );
void * memchr ( void * ptr, int value, size_t num );
Locate character in block of memory
Searches within the first num bytes of the block of memory pointed by
ptr for the first occurrence of value (interpreted as an unsigned
char), and returns a pointer to it.
Both value and each of the bytes checked on the the ptr array are
interpreted as unsigned char for the comparison.
*/
static void test_memchr(void **state) {
(void)state;
/* http://www.cplusplus.com/reference/cstring/memchr/ */
char *pch;
char str[] = "example string";
pch = (char *)memchr(str, 'p', strlen(str));
if (pch != NULL)
// printf("'p' found at position %lu.\n", pch - str + 1);
(void)state;
else
printf("'p' not found.\n");
char strg[] = "abcde";
assert_int_equal(NULL, memchr(strg, 'z', strlen(strg)));
char *p0 = (char *)memchr(strg, 'e', strlen(strg));
int pos0 = p0 - strg + 1;
assert_int_equal(5, pos0);
char *a1 = "ccaaaa";
char *b1 = "ccbbbb";
char *p1 = (char *)memchr(a1, (char)b1[0], strlen(a1));
int pos1 = p1 - a1;
DEBUG_PRINT(("P1 is: %p (%c) at position %d\n", p1, *p1, pos1));
assert_int_equal(0, pos1);
assert_int_equal(NULL, memchr(a1, 'z', strlen(a1)));
char *a2 = "ccaaaa";
char *b2 = "aa";
char *p2 = (char *)memchr(a2, (char)b2[0], strlen(a2));
int pos2 = p2 - a2;
DEBUG_PRINT(("P2 is: %p (%c) at position %d\n", p2, *p2, pos2));
assert_int_equal(2, pos2);
assert_int_equal(NULL, memchr(a2, 'z', strlen(a2)));
char *a3 = "ccbaaaa";
char *b3 = "ab";
char *p3 = (char *)memchr(a3, (char)b3[0], strlen(a3));
int pos3 = p3 - a3;
DEBUG_PRINT(("P3 is: %p (%c) at position %d\n", p3, *p3, pos3));
assert_int_equal(3, pos3);
assert_int_equal(NULL, memchr(a3, 'z', strlen(a3)));
}
/* memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
Compare two blocks of memory
Compares the first num bytes of the block of memory pointed by ptr1
to the first num bytes pointed by ptr2, returning zero if they all
match or a value different from zero representing which is greater if
they do not.
Notice that, unlike strcmp, the function does not stop comparing
after finding a null character.
*/
static void test_memcmp(void **state) {
(void)state;
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n = memcmp(buffer1, buffer2, sizeof(buffer1));
if (n > 0) {
/* printf("'%s' is greater than '%s'.\n", buffer1, buffer2); */
(void)n;
} else if (n < 0) {
printf("'%s' is less than '%s'.\n", buffer1, buffer2);
} else {
printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
}
/* DWgAOtp12Df0 is greater than DWGAOTP12DF0 because the first non-matching
character in both words are 'g' and 'G' respectively, and 'g' (103)
evaluates as greater than 'G' (71).
*/
assert_true(n > 0);
}
/* strncmp
int strncmp ( const char * str1, const char * str2, size_t num );
Compare characters of two strings
Compares up to num characters of the C string str1 to those of the C
string str2. This function starts comparing the first character of
each string. If they are equal to each other, it continues with the
following pairs until the characters differ, until a terminating
null-character is reached, or until num characters match in both
strings, whichever happens first.
*/
static void test_strncmp(void **state) {
(void)state;
char str[][5] = {"R2D2", "C3PO", "R2A6"};
int n;
int found = 0;
for (n = 0; n < 3; n++) {
if (strncmp(str[n], "R2xx", 2) == 0) {
/* printf("found %s\n", str[n]); */
found += 1;
break;
}
}
assert_true(found);
}
/* http://www.jbox.dk/sanos/source/lib/string.c.html */
int strncmp_original(const char *s1, const char *s2, size_t n) {
if (!n) {
return 0;
}
while (--n && *s1 && *s1 == *s2) {
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
int strcmp_original(const char *s1, const char *s2) {
int ret = 0;
while (!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2)
++s1, ++s2;
if (ret < 0) {
ret = -1;
} else if (ret > 0) {
ret = 1;
}
return ret;
}
static void test_is_not_string(void **state) {
(void)state;
char *f = NULL;
char a[] = "aaa";
char v[1] = {'\0'};
assert_true(a);
assert_true(v);
assert_false(f);
assert_int_equal(3, strlen(a));
assert_int_equal(0, strlen(v));
assert_null(v[0]);
}
/* strlen
const char *ptr = "stackoverflow"
size_t length = strlen(ptr);
const char *ptr = "stackoverflow"
The length of a C string is determined by the terminating
null-character: A C string is as long as the number of characters
between the beginning of the string and the terminating null
character (without including the terminating null character itself).
*/
cmp_type short_cmp(const char *s1, const char *s2) {
if (!s1 && s2) {
return LT;
} else if (s1 && !s2) {
return GT;
} else if (!s1 && !s2) {
return EQ;
}
return CONTINUE;
}
int strcmp_with_memchr(const char *s1, const char *s2) {
switch ((cmp_type)short_cmp(s1, s2)) {
case LT:
return -1;
case EQ:
return 0;
case GT:
return 1;
case CONTINUE:
break;
}
char *pch;
int n;
n = strlen(s1);
pch = (char *)memchr(s1, (char)s2[0], n);
if (pch == NULL) {
while (--n && *s1 && *s1 == *s2) {
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
int pos = pch - s1;
DEBUG_PRINT(("comparing %s and %s with PCH", s1, s2));
DEBUG_PRINT(("\nS1 at %p, PCH at %p (%c) POS: %d\n", s1, pch, *pch, pos));
if (pch == s1) {
DEBUG_PRINT((" and PCH starts on s1\n"));
} else {
DEBUG_PRINT((" and s2 starts on s1 from %d\n", pos));
}
while (--pos && *s1 && *s1 == *s2) {
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
int strcmp_with_memcmp(const char *s1, const char *s2) {
switch ((cmp_type)short_cmp(s1, s2)) {
case LT:
return -1;
case EQ:
return 0;
case GT:
return 1;
case CONTINUE:
break;
}
int n = strlen(s1) < strlen(s2) ? strlen(s1) : strlen(s2);
return memcmp(s1, s2, n);
}
static void test_short_cmp(void **state) {
(void)state;
char *a = "aaa";
char *b = "bbb";
assert_true(CONTINUE == short_cmp(a, b));
assert_true(CONTINUE == short_cmp(b, a));
assert_true(GT == short_cmp(a, NULL));
assert_true(LT == short_cmp(NULL, a));
assert_true(EQ == short_cmp(NULL, NULL));
}
/* Function Pointers
int addInt(int n, int m) {
return n+m;
}
int (*functionPtr)(int,int);
functionPtr = &addInt;
int sum = (*functionPtr)(2, 3); // sum == 5
Passing the pointer to another function is basically the same:
int add2to3(int (*functionPtr)(int, int)) {
return (*functionPtr)(2, 3);
}
We can use function pointers in return values as well (try to keep up, it
gets messy):
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
But it's much nicer to use a typedef:
typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef
myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}
*/
typedef int (*comparer_type)(const char *, const char *);
static void test_strcmp_with(comparer_type comparer, void **state) {
(void)state;
int a = 0;
int b = 0;
assert_int_equal(a, b);
char *a_s = "aaaa";
char *b_s = "bbbb";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "a";
b_s = "bbbb";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "aaaa";
b_s = "b";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "b";
b_s = "aaaa";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "bbbb";
b_s = "a";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "ccaaaa";
b_s = "ccbbbb";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
/* printf("%s ? %s : %d|%d\n", a_s, b_s, a, b); */
assert_int_equal(a, b);
a_s = "cca";
b_s = "ccbbbb";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "ccaaaa";
b_s = "ccb";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "ccb";
b_s = "ccaaaa";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
a_s = "ccbbbb";
b_s = "cca";
a = strcmp(a_s, b_s);
b = (*comparer)(a_s, b_s);
assert_int_equal(a, b);
}
static void test_strcmp_with_memcmp(void **state) {
comparer_type comparer;
comparer = (comparer_type)strcmp_with_memcmp;
test_strcmp_with(comparer, state);
}
static void test_strcmp_with_memchr(void **state) {
comparer_type comparer;
comparer = (comparer_type)strcmp_with_memchr;
test_strcmp_with(comparer, state);
}
/*
- [Exs 31]: Use memchr and memcmp to implement a bounds checking
version of strcmp.
- memchr(s, c, len) searches array s for the appearance of character c.
- memcmp(s0, s1, len) compares two arrays in the lexicographic ordering. That
is it first scans initial parts of the two arrays that happen to be
equal and then returns the difference between the two first characters
that are distinct. If no differing elements are found up to len, 0 is
returned.
- strcmp(s0, s1) compares two arrays in the lexicographic ordering
similar to memcmp, but may not take some language specialties into
account. The comparison stops at the first 0-character that is
encountered in either s0 or s1. Again, both parameters have to be
0-terminated.
*/
static void test_exs_31(void **state) { (void)state; }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_memchr),
cmocka_unit_test(test_memcmp),
cmocka_unit_test(test_strncmp),
cmocka_unit_test(test_is_not_string),
cmocka_unit_test(test_short_cmp),
cmocka_unit_test(test_strcmp_with_memcmp),
cmocka_unit_test(test_strcmp_with_memchr),
cmocka_unit_test(test_exs_31),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>/* http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/float.h.html */
#include <float.h>
/* http://www.cplusplus.com/reference/cmath/ */
#include <math.h>
/* typedef enum { false, true } bool; */
/* (C99) */
#include <stdbool.h>
int nearly_equal(double a, double b, double epsilon);
/*
* using limits.h:
* http://www.cplusplus.com/reference/climits/
* using float.h
* http://www.cplusplus.com/reference/cfloat/
* using math.h
* http://www.cplusplus.com/reference/cmath/
*
* fabs:
* http://www.cplusplus.com/reference/cmath/fabs/
* double fabs (double x);
*
* fmin:
* http://www.cplusplus.com/reference/cmath/fmin/
* double fmin (double x, double y);
*
* ceil:
* http://www.cplusplus.com/reference/cmath/ceil/
* double ceil (double x);
*
* source:
* http://www.floating-point-gui.de/errors/comparison/
*/
int nearly_equal(double a, double b, double epsilon) {
double absA = fabs(a);
double absB = fabs(b);
double diff = fabs(a - b);
if (a == b) { /* shortcut, handles infinities */
return 1;
} else if (a == 0 || b == 0 || diff < DBL_MIN) {
/*
* a or b is zero or both are extremely close to it;
* relative error is less meaningful here.
*/
return diff < (epsilon * DBL_MIN);
} else { /* use relative error */
return diff / fmin((absA + absB), DBL_MAX) < epsilon;
}
}
<file_sep>/*
* 04_keyboard.c - Get the keyboard input, and print it on console.
* Here is the document of all the key code https://wiki.libsdl.org/SDL_Keycode
*
* https://github.com/seudut/SDL-study
* https://github.com/seudut/SDL-study/blob/master/src/04_keyboard.c
*/
#include <stdio.h>
//#include "04_keyboard.h"
#include <SDL2/SDL.h>
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;
const char *WINDOW_TITLE = "SDL Keyboard";
int main(int argc, char *argv[]) {
SDL_Window *window = NULL;
SDL_Event windowEvent;
unsigned char quit = 0;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH,
WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("Could not create window: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
while (!quit) {
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT)
quit = 1;
else if (windowEvent.type == SDL_KEYDOWN) {
switch (windowEvent.key.keysym.sym) {
case SDLK_UP:
printf("UP is pressed\n");
break;
case SDLK_DOWN:
printf("DOWN is pressed\n");
break;
case SDLK_LEFT:
printf("LEFT is pressed\n");
break;
case SDLK_RIGHT:
printf("RIGHT is pressed\n");
break;
case SDLK_SPACE:
printf("SPACE is pressed\n");
break;
case SDLK_q:
printf("q is pressed, will quit\n");
quit = 1;
break;
default:
printf("Others key is pressed\n");
break;
}
}
}
}
// Destory window
SDL_DestroyWindow(window);
// Quit SDL substems
SDL_Quit();
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#define VBAR "\u2502" /**< a vertical bar character */
#define HBAR "\u2500" /**< a horizontal bar character*/
#define TOPLEFT "\u250c" /**< topleft corner character*/
#define TOPRIGHT "\u2510" /**< topright corner character*/
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
* Exercises
*
* - [Exs 00]:
*
*/
void draw_sep(char const start[static 1], char const end[static 1]) {
fputs(start, stdout);
size_t slen = mbsrlen(start, 0);
size_t elen = 90 - mbsrlen(end, 0);
for (size_t i = slen; i < elen; ++i)
fputs(HBAR, stdout);
fputs(end, stdout);
fputc('\n', stdout);
}
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
setlocale(LC_ALL, "");
/* Multibyte character printing only works after the
* locale
* has been switched. */
draw_sep(TOPLEFT "␣©␣2014␣jεnz␣ " gυz,tεt␣", TOPRIGHT);
printf("nothing to do\n");
return EXIT_SUCCESS;
}
<file_sep>/**
** @brief A simple version of the macro that just does ** a @c fprintf or
** nothing.
**/
#if ANDEBUG
#define TRACE_PRINT0(F, X) \
do { /* nothing */ \
} while (false)
#else
#define TRACE_PRINT0(F, X) fprintf(stderr, F, X)
#endif
/**
** we can enforce the use of a string literal.
**/
/**
** @brief A simple version of the macro that ensures that the @c
** fprintf format is a string literal.
**
** As an extra, it also adds a newline to the print out, so
** the user doesn’t has to specify it each time.
**/
/**
** Now, F must receive a string literal and the compiler then can do the work
** and warn us about a mismatch.
**/
#if BNDEBUG
#define TRACE_PRINT1(F, X) \
do { /* nothing */ \
} while (alse)
#else
#define TRACE_PRINT1(F, X) fprintf(stderr, "" F "\n", X)
#endif
/**
** The macro TRACE_PRINT1 still has a weak point. If it is used with DEBUG
** unset, the arguments are ignored and thus not checked for consistency.
** This can have the long term effect that a mismatch remains undetected
** for a long time and all of a sudden appears when debugging.
**/
/**
** @brief A macro that resolves to @c 0 or @c 1 according to @c
** NDEBUG being set.
**/
#ifdef NDEBUG
#define TRACE_ON 0
#else
#define TRACE_ON 1
#endif
/**
** In contrast to the NDEBUG macro, which could be set to any value by
** the programmer, this new macro is then guaranteed to hold either 1 or 0.
** Secondly, TRACE_PRINT2 is defined with a regular if conditional.
**/
/**
** Whenever its argument is 0, any modern compiler should be able to
** optimize the call to fprintf out. What it shouldn’t omit is the
** argument check for parameters F and X. So regardless whether or
** not we are debugging, the arguments to the macro must always be
** matching as fprintf expects it.
**/
/**
** @brief A simple version of the macro that ensures that the @c
** fprintf call is always evaluated.
**/
#define TRACE_PRINT2(F, X) \
do { \
if (TRACE_ON) \
fprintf(stderr, "" F "\n", X); \
} while (false)
/**
**
** Similar to the use of the empty string literal "" above, there are
** other tricks to force a macro argument to be of a particular type.
** One of these tricks consists in adding an appropriate 0: +0 would
** force the argument to be any arithmetic type (integer, float or
** pointer), something like +0.0F promotes to a floating type.
** E.g if we want to have a simpler variant to just print a value
** for debugging, without keeping track of the type of the value,
** this could be sufficient to our needs:
**/
/**
** @brief Trace a value without having to specify a format.
**/
#define TRACE_VALUE0(HEAD, X) TRACE_PRINT2(HEAD " %Lg", (X) + 0.0L)
/**
** It works for any value X that is either an integer or a
** floating point. The format "%Lg" for a long double ensures
** that any value is presented in a suitable way.
**/
/**
** Then, compound literals can be a convenient way to check if the value
** of a parameter X is assignment compatible to a type T.
**/
/**
** @brief Trace a pointer without having to specify a format.
**
** @warning Uses a cast of @a X to @c void*.
**/
#define TRACE_PTR0(HEAD, X) TRACE_PRINT2(HEAD "␣%p", (void *)(X))
/**
** It tries to print a pointer value with a "%p" format, which
** expects a generic pointer of type void*. Therefore the macro uses
** a cast to convert the value and type of X to void*. As most casts,
** cast here can go wrong if X isn’t a pointer: because the cast tells
** the compiler that we know what we are doing all type checks are
** actually switched off.
** This can be avoided by assigning X first to an object of type void*.
** Assignment only allows a restricted set of implicit conversions,
** namely here the conversion of any pointer to an object type to void*.
**/
/**
** @brief Trace a pointer without specifying a format.
**/
#define TRACE_PTR1(HEAD, X) TRACE_PRINT2(HEAD "␣%p", ((void *){0} = (X)))
/**
** @brief Add the current line number to the trace.
**/
#define TRACE_PRINT3(F, X) \
do { \
if (TRACE_ON) \
fprintf(stderr, "%lu: " F "\n", __LINE__ + 0UL, X); \
} while (false)
/**
** @brief Add the name of the current function to the trace.
**/
#define TRACE_PRINT4(F, X) \
do { \
if (TRACE_ON) \
fprintf(stderr, "%s:%lu: " F "\n", __func__, __LINE__ + 0UL, X); \
} while (false)
/* https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html#Stringizing */
/*
* In view of the potential problems with __LINE__ mentioned above, we also
* would like to convert the line number directly into a string. This has a
* double advantage: it avoids the type problem and stringification is done
* entirely at compile time. As said, the # operator only applies to macro
* arguments, so a simple use as # __LINE__ does not have the desired effect.
* Now consider the following macro definition:
*/
#define STRINGIFY(X) #X
/*
* Stringification kicks in before argument replacement, and the result of STRINGIFY( __LINE__) is "__LINE__", the macro __LINE__ is not expanded. So this macro still is not sufficient for our need.
*/
#define STRGY(X) STRINGIFY(X)
#define TRACE_PRINT5(F, X) \
do { \
if (TRACE_ON) \
fprintf(stderr, "%s:" STRGY(__LINE__) ":(" #X "): " F "\n", __func__, \
X); \
} while (false)
#import <stdio.h>
#import <stdlib.h>
/* http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#import <stdbool.h>
int main(void) {
/*
* This looks harmless and efficient, but has a pitfall: the argument
* F can be any pointer to char, in particular it could be a format
* string that sits in a modifiable memory region. This may have the
* effect that an erroneous or malicious modification of that string
* leads to an invalid format, and thus to a crash of the program or
* could divulge secrets.
*/
double n = 0.1;
double m = 0.2;
TRACE_PRINT0("my favourite variable: %g\n", n);
TRACE_PRINT4("my favourite variable: %g", n);
/* main:165: my favourite variable: 0.1 */
TRACE_PRINT5("my favourite variable: %g", n);
TRACE_PRINT5("a good expression: %g", n * m);
return EXIT_SUCCESS;
}
<file_sep>#include <stdint.h>
#include <stdlib.h>
#define MAXFACTORS 100
size_t find_factors(uint64_t base, uint64_t factors[]);
<file_sep>#include <stdio.h> /* printf, scanf, puts */
#include <stdlib.h> /* realloc, free, exit, NULL */
#include <string.h>
/* http://www.cplusplus.com/reference/cstdlib/realloc/ */
int main_0() {
int input, n;
int count = 0;
int *numbers = NULL;
int *more_numbers = NULL;
do {
printf("Enter an integer value (0 to end): ");
scanf("%d", &input);
count++;
more_numbers = (int *)realloc(numbers, count * sizeof(int));
if (more_numbers != NULL) {
numbers = more_numbers;
numbers[count - 1] = input;
} else {
free(numbers);
puts("Error (re)allocating memory");
exit(1);
}
} while (input != 0);
printf("Numbers entered: ");
for (n = 0; n < count; n++)
printf("%d ", numbers[n]);
free(numbers);
return 0;
}
int main_1() {
char *str;
/* Initial memory allocation */
str = (char *)malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %p\n", str, str);
/* Reallocating memory */
str = (char *)realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %p\n", str, str);
free(str);
return (0);
}
/* https://en.cppreference.com/w/c/memory/realloc */
int main_2(void) {
int *pa = malloc(10 * sizeof *pa); // allocate an array of 10 int
if (pa) {
printf("%zu bytes allocated. Storing ints: ", 10 * sizeof(int));
for (int n = 0; n < 10; ++n)
printf("%d ", pa[n] = n);
}
int *pb =
realloc(pa, 1000000 * sizeof *pb); // reallocate array to a larger size
if (pb) {
printf("\n%zu bytes allocated, first 10 ints are: ", 1000000 * sizeof(int));
for (int n = 0; n < 10; ++n)
printf("%d ", pb[n]); // show the array
free(pb);
} else { // if realloc failed, the original pointer needs to be freed
free(pa);
}
return 0;
}
int main(void) {
return main_0();
}
<file_sep>/*
* 05_play_audio.c - Play Music using SDL2_mixer
* Documentation -
* https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_toc.html Functions:
* Mix_Init ()
* Mix_OpenAudio ()
* Mix_LoadMUS ()
* Mix_PlayMusic ()
* Mix_PauseMusic ()
* Mix_ResumeMusic ()
* Mix_FreeMusic ()
* Mix_CloseAudio ()
*
* In this sample, press <SPACE> to start/stop the music playing.
* https://github.com/seudut/SDL-study
* https://github.com/seudut/SDL-study/blob/master/src/05_play_audio.c
*/
#include <stdio.h>
#include <assert.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;
const char *WINDOW_TITLE = "SDL Window - playing music";
/* static const char *MUSIC_FILE = "../res/test.wav"; */
int main(int argc, char *argv[]) {
assert(argc > 1);
SDL_Window *window;
// start SDL with audio support
if (SDL_Init(SDL_INIT_AUDIO) == -1) {
printf("SDL_Init: %s\n", SDL_GetError());
exit(1);
}
window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH,
WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
{
// 1. sdl2_mixer init
// load support for the OGG and MOD , MP3 sample/music formats
int flags = MIX_INIT_OGG | MIX_INIT_MOD | MIX_INIT_MP3;
if (!Mix_Init(flags)) {
printf("Mix_Init: %s\n", Mix_GetError());
}
}
{
// 2. open audio device
// open 44.1KHz, signed 16bit, system byte order,
// stereo audio, using 1024 byte chunks
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
printf("Mix_OpenAudio: %s\n", Mix_GetError());
exit(2);
}
}
// 3. Load music file
// Load the MP3 file to play as music
Mix_Music *music;
music = Mix_LoadMUS(argv[1]);
if (!music) {
printf("Mix_LoadMUS music.mp3: %s\n", Mix_GetError());
}
printf(" Load Music success. Press <SPACE> to start/stop music playing.\n ");
SDL_Event event;
unsigned char quit = 0;
while (!quit) {
if (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = 1;
} else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_SPACE:
// Play the music
if (!Mix_PlayingMusic()) {
if (Mix_PlayMusic(music, -1) == -1) {
printf("Mix_PlayMusic: %s\n", Mix_GetError());
}
} else {
Mix_PausedMusic() ? Mix_ResumeMusic() : Mix_PauseMusic();
}
break;
case SDLK_q:
printf("q is pressed, will quit\n");
quit = 1;
break;
default:
printf("Others key is pressed\n");
break;
}
}
}
}
Mix_FreeMusic(music); // Mix_LoadMUS()
Mix_CloseAudio(); // Mix_OpenAudio ()
// Destory window
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<file_sep>#include "etl.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
/* char_to_upper converts a character to its uppercase version.
* 'a':97 ... 'z':122;
* 'A':65 ... 'Z':90
*/
int char_to_upper(char c) { return (c >= 'a' && c <= 'z') ? c - 32 : c; }
/* char_to_lower converts a character to its lowercase version.
* one approach : (*c - 'A') + 'a'
*/
int to_lower(char c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
/*
* do {
* char k = char_to_lower(*c);
* int idx = (int)k - 97;
* } while (*(++c));
*/
char *str_to_lower(char *t) {
char *start = t;
do {
*t = to_lower(*t);
} while (*(++t));
return start;
}
/* output = malloc(sizeof(new_map *) * r);
* output = (new_map **)realloc(output, len * sizeof(new_map *));
* output = (new_map *)realloc(output, len * sizeof(new_map));
* memcpy(output, tmp, sizeof(new_map *)*r);
*/
int convert(legacy_map *input, int input_len, new_map **output) {
*output = (new_map *)malloc(sizeof(new_map) * ('z' - 'a'));
int r = 0;
int i, j;
for (i = 0; i < input_len; i++) {
for (char *c = input[i].value; *c; c++) {
(*output)[r].key = to_lower(*c);
(*output)[r].value = input[i].key;
r++;
}
}
for (i = 0; i < r - 1; ++i) {
for (j = i + 1; j < r; ++j) {
if ((*output)[i].key > (*output)[j].key) {
new_map tmp = (*output)[i];
(*output)[i] = (*output)[j];
(*output)[j] = tmp;
}
}
}
return r;
}
<file_sep>#include "perfect_numbers.h"
/* rem is the int reminder of the division. */
int rem(int a, int b) { return a - (a / b) * b; }
int aliquot_sum(int n) {
int as = 0;
for (int i = 1; i < n; ++i) {
if (!rem(n, i))
as+=i;
}
return as;
}
kind classify_number(int n) {
if (n <= 0)
return ERROR;
int as = aliquot_sum(n);
if (as == n)
return PERFECT_NUMBER;
else if (as < n)
return DEFICIENT_NUMBER;
return ABUNDANT_NUMBER;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Exs 3.7
*/
/*
https://linux.die.net/man/3/strtol
*/
int digit_to_int(char d) {
char str[2];
str[0] = d;
str[1] = '\0';
return (int)strtol(str, NULL, 10);
}
int main(int argc, char *argv[argc + 1]) {
printf("running as %s\n", argv[0]);
if (argc == 1) {
printf("pass me something\n");
}
for (int i = 1; i < argc; ++i) {
char *word = argv[i];
printf("as word: %s\n", word);
char const arg = *argv[i];
printf("processing arg: %c (%d)\n", arg, arg);
switch (arg) {
case 'm':
printf("this is a magpie\n");
break;
case 'r':
printf("this is a raven\n");
break;
case 'j':
printf("this is a jay\n");
break;
case 'c':
printf("this is a chough\n");
break;
default:
printf("this is an unknown corvid\n");
}
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
int n;
printf("Please input an integer value: ");
scanf("%d", &n);
printf("You entered: %d\n", n);
float pi = 3.141592;
int truncated_pi = (int)pi; // truncated_pi == 3
printf("truncated PI: %d\n", truncated_pi);
char some_char = 'A';
int some_int = (int)some_char; // On machines which use ASCII as the character
// set, my_int == 65
printf("some_char to some_int: %d\n", some_int);
}
<file_sep>#ifndef RAINDROPS_H
#define RAINDROPS_H
#define BUFFER_LENGTH 16
void convert(char *result, int drops);
#endif
<file_sep>/*
* Longest Increasing Substring
*
* Given a list of positive integers, write code that finds the length of
* longest contiguous sub-list that is increasing (not strictly). That is the
* longest sublist such that each element is greater than or equal to the last.
*
* For example if the input was:
*
* [1,1,2,1,1,4,5,3,2,1,1]
*
* The longest increasing sub-list would be [1,1,4,5]
*
* , so you would output 4.
*
* Your answer will be scored by taking its source as a list of bytes and then
* finding the length of the longest increasing sub-list of that list. A lower
* score is the goal. Ties are broken in favor of programs with fewer overall
* bytes.
*
* https://codegolf.stackexchange.com/q/173586
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
int max(unsigned int count, int values[]) {
assert(count > 0);
unsigned int i;
int m = values[0];
for (i = 1; i < count; ++i) {
m = values[i] > m ? values[i] : m;
}
return m;
}
int longest_increasing_substring(unsigned int count, int values[]) {
assert(count > 0);
unsigned int i;
unsigned int l = 1;
unsigned int m = 1;
for (i = 1; i < count; ++i) {
l = values[i] > values[i - 1] ? l + 1 : 1;
m = l > m ? l : m;
}
return m;
}
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_max(void **state) {
(void)state;
int expected = 9;
int values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = sizeof(values) / sizeof(int);
int result = max(count, values);
assert_int_equal(expected, result);
}
static void test_longest_increasing_substring_0(void **state) {
(void)state;
int expected = 10;
int values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = sizeof(values) / sizeof(int);
int result = longest_increasing_substring(count, values);
assert_int_equal(expected, result);
}
static void test_longest_increasing_substring_1(void **state) {
(void)state;
int expected = 1;
int values[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int count = sizeof(values) / sizeof(int);
int result = longest_increasing_substring(count, values);
assert_int_equal(expected, result);
}
static void test_longest_increasing_substring_2(void **state) {
(void)state;
int expected = 4;
int values[] = {9, 8, 7, 6, 1, 2, 3, 5, 4, 3, 2, 1, 0};
int count = sizeof(values) / sizeof(int);
int result = longest_increasing_substring(count, values);
assert_int_equal(expected, result);
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_max),
cmocka_unit_test(test_longest_increasing_substring_0),
cmocka_unit_test(test_longest_increasing_substring_1),
cmocka_unit_test(test_longest_increasing_substring_2),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
printf("\nrunning the test suite\n");
return test();
}
<file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
enum {
buf_max = 8,
};
/*
Scanf
scanf ("%[^\n]%*c", name);
The [] is the scanset character. [^\n] tells that while the input is not a
newline ('\n') take input. Then with the %*c it reads the newline character from
the input buffer (which is not read), and the * indicates that this read in
input is discarded (assignment suppression), as you do not need it, and this
newline in the buffer does not create any problem for next inputs that you might
take.
Note you can also use gets but ....
Never use gets(). Because it is impossible to tell without knowing the data in
advance how many characters gets() will read, and because gets() will continue
to store characters past the end of the buffer, it is extremely dangerous to
use. It has been used to break computer security. Use fgets() instead.
http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html
*/
/*
Strtok
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need
more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose
first character is used as the starting location to scan for tokens. In
subsequent calls, the function expects a null pointer and uses the position
right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all
subsequent calls to this function (with a null pointer as the first argument)
return a null pointer.
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller
strings (tokens). Alternativelly [sic], a null pointer may be specified, in
which case the function continues scanning where a previous successful call to
the function ended.
delimiters
C string containing the delimiter characters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string. A null pointer is returned if
there are no tokens left to retrieve.
*/
#include <stdio.h>
#include <string.h>
int strtok_sample() {
char str[] = "- This, a sample string.";
char sep[] = " ,.-";
char *pch;
printf("Splitting string \"%s\" into tokens:\n", str);
pch = strtok(str, sep);
while (pch != NULL) {
printf("%s\n", pch);
pch = strtok(NULL, sep);
}
return 0;
}
char **file_names_or_ask_and_malloc(int argc, char *argv[argc + 1]) {
if (argc < 2) {
char names[255];
fprintf(stdout, "your files:\n");
scanf("%[^\n]%*c", names);
return NULL;
} else {
int cnt = argc - 1;
printf("there are %d filenames in the given argument\n", cnt);
char **sub_str = malloc(cnt * sizeof(char *));
for (int i = 0; i < cnt; ++i) {
sub_str[i] = malloc(20 * sizeof(char));
}
for (int i = 1; i < argc; ++i) {
sub_str[i] = argv[i];
}
return sub_str;
}
}
enum _bool { false = 0, true = 1 };
typedef enum _bool bool;
void file_names_or_ask_ptr(char *argv[], char **fnames, size_t cnt, bool ask) {
if (ask == true) {
char names[255];
fprintf(stdout, "your files:\n");
scanf("%[^\n]%*c", names);
char sep[] = " ";
char *pch;
printf("splitting string \"%s\" into tokens:\n", names);
size_t i = 0;
pch = strtok(names, sep);
while (pch != NULL) {
if (i == cnt) {
break;
}
strcpy(fnames[++i], pch);
printf("token: %s\n", pch);
pch = strtok(NULL, sep);
}
} else {
printf("there are %lu filenames in the given argument\n", cnt);
for (size_t i = 0; i < cnt; ++i) {
printf("- i: %lu : %s\n", i, argv[i + 1]);
fnames[i] = argv[i + 1];
}
}
}
int cat(int argc, char *argv[argc + 1]) {
/* return value */
int ret = EXIT_FAILURE;
/* reading buffer */
char buffer[buf_max] = {0};
bool ask = false;
bool linum = false;
size_t cnt = argc - 1;
const size_t MAX_FILES = 5;
if (cnt > 0 && strcmp(argv[1], "-n") == 0) {
argv[1] = NULL;
linum = true;
}
if (!cnt) {
printf("setting cnt to the limit (%lu)\n", MAX_FILES);
cnt = MAX_FILES;
ask = true;
}
char **fnames = (char **)malloc(cnt * sizeof(char *));
size_t i = 0;
for (i = 0; i < cnt; i++) {
fnames[i] = (char *)malloc(50 * sizeof(char));
}
file_names_or_ask_ptr(argv, fnames, cnt, ask);
for (size_t i = 0; i < cnt; ++i) {
if (fnames == NULL || fnames[i] == NULL || fnames[i][0] == '\0') {
continue;
}
printf("\n-------%s-------\n", fnames[i]);
FILE *instream = fopen(fnames[i], "r");
if (instream) {
int fgets_count = 0;
size_t ln = 0;
if (linum == true) {
printf("%lu: ", ln++);
}
char *c;
do {
// http://en.cppreference.com/w/c/io/fgets
// https://www.freebsd.org/cgi/man.cgi?query=strcspn&sektion=3
// if (buffer[strcspn(buffer, "\n")] == 0)
/* c = fgets(buffer, buf_max, instream); */
/* if (c == NULL || feof(instream)) { */
/* printf("break for null\n"); */
/* break; */
/* } */
fgets_count++;
fputs(buffer, stdout);
if (linum == true && buffer[(strlen(buffer) - 1)] == '\n') {
if (c == NULL || feof(instream)) {
printf("break for FEOF\n");
break;
}
printf("%lu: ", ln++);
}
c = fgets(buffer, buf_max, instream);
/* long int pos = ftell(instream); */
/* printf("DONE??\n"); */
/* fputs((pos == EOF) ? "true" : "false", stdout); */
/*
Rule 1.8.2.10 fgetc returns int to be capable to encode a
special error status, EOF, in addition to all valid
characters.
Also, the detection of a return of EOF alone is not
sufficient to conclude that the end of the stream has been
reached. We have to call feof to test if a stream’s position
has reached its end-of-file marker.
Rule 1.8.2.11 End of file can only be detected after a failed
read.
*/
} while (c);
printf("we got %s with %d hit of fgets (buf_max: %d)\n", fnames[i],
fgets_count, buf_max);
fclose(instream);
ret = EXIT_SUCCESS;
} else {
/* Provide some error diagnostic . */
fprintf(stderr, "Could not open %s: ", fnames[i]);
/*
The perror() function produces a message on standard error
describing the last error encountered during a call to a system or
library function.
*/
perror(0);
errno = 0;
// reset error code
}
}
return ret;
}
/*
feof example: byte counter
#include <stdio.h>
*/
int feof_example() {
FILE *pFile;
int n = 0;
pFile = fopen("text.txt", "rb");
if (pFile == NULL)
perror("Error opening file");
else {
while (fgetc(pFile) != EOF) {
++n;
}
if (feof(pFile)) {
puts("End-of-File reached.");
printf("Total number of bytes read: %d\n", n);
} else
puts("End-of-File was not reached.");
fclose(pFile);
}
return 0;
}
/*
Exercises
- [Exs 43] Under what circumstances this program finishes with success or
failure return codes?
- no arguments given;
- all arguments cannot be open;
- [Exs 44] Surprisingly this program even works for files with lines that have
more than 31 characters. Why?
The while loop runs until fgets has results.
- [Exs 45] Have the program read from stdin if no command line argument is
given.
- [Exs 46] Have the program precedes all output lines with line numbers if the
first command line argument is "-n".
- [Exs 47] But remember that consecutive string literals are concatenated, see
Rule 1.5.2.1.
Rule 1.5.2.1: Consecutive string literals are concatenated.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(int argc, char *argv[argc + 1]) {
#if defined(TEST)
printf("\nrunning the test suite\n");
int err = test();
if (!err) {
printf("test passed, running `cat` is what you probably want...\n");
return EXIT_SUCCESS;
}
return err;
#endif
(void)argv;
printf("running `cat`\n");
return cat(argc, argv);
}
<file_sep>#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
size_t gcd2(size_t a, size_t b) {
assert(a <= b);
if (!a)
return b;
size_t rem = b % a;
return gcd2(rem, a);
}
size_t gcd(size_t a, size_t b) {
assert(a);
assert(b);
if (a < b)
return gcd2(a, b);
else
return gcd2(b, a);
}
size_t fib(size_t n) {
if (n < 3) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
pthread_mutex_t count_mutex;
pthread_mutex_t leaves_mutex;
long long count;
size_t leaves;
void increment_count() {
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
void increment_leaves() {
pthread_mutex_lock(&leaves_mutex);
leaves = leaves + 1;
pthread_mutex_unlock(&leaves_mutex);
}
size_t fib_c(size_t n) {
increment_count();
if (n == 0) {
increment_leaves();
return 1;
} else if (n < 3) {
return fib_c(0);
} else {
return fib_c(n - 1) + fib_c(n - 2);
}
}
size_t fib_counter(size_t n) {
count = 0;
leaves = 0;
size_t res = fib_c(n);
DEBUG_PRINT(("counter is %llu ", count));
DEBUG_PRINT(("leaves are %lu\n", leaves));
assert(res == leaves);
return res;
}
/* Compute Fibonacci number n with help of a cache that may hold previously
* computed values.
*/
size_t fibCacheRec(size_t n, size_t cache[n]) {
if (!cache[n - 1]) {
cache[n - 1] = fibCacheRec(n - 1, cache) + fibCacheRec(n - 2, cache);
}
return cache[n - 1];
}
size_t fibCache(size_t n) {
if (n + 1 <= 3) {
return 1;
}
/* Set up a VLA to cache the values . */
size_t cache[n];
/* A VLA must be initialized by assignment . */
cache[0] = 1;
cache[1] = 1;
for (size_t i = 2; i < n; ++i) {
cache[i] = 0;
}
/* Call the recursive function . */
return fibCacheRec(n, cache);
}
void fib2rec(size_t n, size_t buf[2]) {
if (n > 2) {
size_t res = buf[0] + buf[1];
buf[1] = buf[0];
buf[0] = res;
fib2rec(n - 1, buf);
}
}
size_t fib2(size_t n) {
size_t res[2] = {
1, 1,
};
fib2rec(n, res);
return res[0];
}
size_t fib2iter(size_t n) {
size_t i;
size_t f1 = 0;
size_t f2 = 1;
size_t fi;
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
for (i = 2; i <= n; i++) {
fi = f1 + f2;
f1 = f2;
f2 = fi;
}
return fi;
}
/*
* Exercises
*
* - [Exs 34]: Show that a call fib(n) induces Fn leaf calls.
* - [Exs 39]: Use an iteration statement to transform fib2rec into a
* non-recursive function fib2iter.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
static void test_fibonacci(void **state) {
(void)state;
assert_int_equal(1, fib(0));
assert_int_equal(55, fib(10));
}
static void test_fibonacci_counter(void **state) {
(void)state;
assert_int_equal(2, fib_counter(3));
assert_int_equal(3, fib_counter(4));
assert_int_equal(5, fib_counter(5));
assert_int_equal(8, fib_counter(6));
assert_int_equal(13, fib_counter(7));
assert_int_equal(21, fib_counter(8));
assert_int_equal(55, fib_counter(10));
}
static void test_fibonacci_cached(void **state) {
(void)state;
assert_int_equal(2, fib2(3));
assert_int_equal(3, fib2(4));
assert_int_equal(5, fib2(5));
assert_int_equal(8, fib2(6));
assert_int_equal(13, fib2(7));
assert_int_equal(21, fib2(8));
assert_int_equal(55, fib2(10));
}
static void test_fibonacci_iter(void **state) {
(void)state;
assert_int_equal(2, fib2iter(3));
assert_int_equal(3, fib2iter(4));
assert_int_equal(5, fib2iter(5));
assert_int_equal(8, fib2iter(6));
assert_int_equal(13, fib2iter(7));
assert_int_equal(21, fib2iter(8));
assert_int_equal(55, fib2iter(10));
}
static void test_gcd(void **state) {
(void)state;
assert_int_equal(1, gcd(1, 1));
assert_int_equal(4, gcd(8, 20));
assert_int_equal(1, gcd(8, 3));
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_fibonacci),
cmocka_unit_test(test_fibonacci_counter),
cmocka_unit_test(test_fibonacci_cached),
cmocka_unit_test(test_fibonacci_iter),
cmocka_unit_test(test_gcd),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
<file_sep>#include "triangle.h"
/* https://en.wikipedia.org/wiki/Triangle_inequality */
int is_not_inequal(triangle_t sides) {
return (sides.a + sides.b >= sides.c) && (sides.c + sides.a >= sides.b) &&
(sides.b + sides.c >= sides.a);
}
int is_not_zero(triangle_t sides) { return (sides.a + sides.b + sides.c) > 0; }
int compare(triangle_t sides) {
return (sides.a == sides.b) + (sides.a == sides.c) + (sides.b == sides.c);
}
int is_equilateral(triangle_t sides) {
return is_not_inequal(sides) && is_not_zero(sides) && compare(sides) == 3;
}
int is_isosceles(triangle_t sides) {
return is_not_inequal(sides) && compare(sides) >= 1;
}
int is_scalene(triangle_t sides) {
return is_not_inequal(sides) && compare(sides) == 0;
}
<file_sep>#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define TEST_LENGTH 6
int binary_conversion(int num) {
if (num == 0) {
return 0;
} else {
return (num % 2) + 10 * binary_conversion(num / 2);
}
}
int sample() {
unsigned int byte, bit, mask;
char *bitfield;
if (!(bitfield = calloc(UINT_MAX / 8, 1)))
err(1, "calloc");
/* we flip the bit for the number '0' as "seen" */
bitfield[0] = 1;
int targets[TEST_LENGTH] = {1, 2, 4, 5, 6, 2};
for (int i = 0; i < 10; ++i) {
byte = (unsigned)i / 8;
bit = 1 << ((unsigned)i % 8);
printf("- target: %d", (unsigned)i);
printf(" bucket: %03d", byte);
printf(" bit: %08d (%03d)", binary_conversion(bit), bit);
printf("\n");
}
for (int i = 0; i < TEST_LENGTH; ++i) {
int target = targets[i];
/* the bucket in the bitfield.
* each bucket will contain up to 8 numbers. */
byte = (unsigned)target / 8;
/* this is the most significan bit to represent the current target within
* the bucket that we assigned.
* for each number in the bucket we will flip to '1' the corresponding bit
* in its position of the bucket.
* for instance:
*
* target: 0 bucket: 000 bit: 00000001 (001)
* target: 1 bucket: 000 bit: 00000010 (002)
* target: 2 bucket: 000 bit: 00000100 (004)
* target: 3 bucket: 000 bit: 00001000 (008)
* target: 4 bucket: 000 bit: 00010000 (016)
* target: 5 bucket: 000 bit: 00100000 (032)
* target: 6 bucket: 000 bit: 01000000 (064)
* target: 7 bucket: 000 bit: 10000000 (128)
* target: 8 bucket: 001 bit: 00000001 (001)
* target: 9 bucket: 001 bit: 00000010 (002)
*
* so, if we "see" the number '3' we will flip the 4th bit in the bucket 0.
*/
bit = 1 << ((unsigned)target % 8);
printf("----\n");
printf("target: %03d, byte: %02d\n", (unsigned)target, byte);
printf("bit:\t%03d : %08d\n", bit, binary_conversion(bit));
printf("bf[%d]:\t%03d : %08d\n", byte, (unsigned)bitfield[byte],
binary_conversion(bitfield[byte]));
printf("check (&) : %08d\n", (binary_conversion(bitfield[byte] & bit)));
/* the check is with the AND operator, if the bit corresponding to the
* target number is flipped on in the bitfield, the result will be
* greater than 0 and the search completes. */
unsigned int flipped_on = bitfield[byte] & bit;
if (flipped_on) {
printf("found %03d: flipped %08d\n", target,
binary_conversion(bitfield[byte] & bit));
free(bitfield);
return 1;
}
/* the 'mask' is going to be the list of flipped bits within the selected
* bucket.
* for instance, if we saw the number '3' and '4' (and '0' by default) the
* bit mask is
*
* mask: (|) : 00011001
*
* because this is the mask for 1:
* 00000001
* when we add '4':
* 00010001
* and when we add '3':
* 00011001
*
* so, if we see '4' again, its bit is '16 : 00010000' and the check will
* find the corresponding bit flipped on:
* 16 : 00010000 AND
* msk: 00011001
* ---: 00010000 found!
*/
mask = bitfield[byte] | bit;
printf("new mask : %08d\n", binary_conversion(mask));
bitfield[byte] = mask;
}
free(bitfield);
return 0;
}
int main() { sample(); }
<file_sep>#include "raindrops.h"
#include <string.h>
#include <stdio.h>
/* STRCAT(3)
*
* NAME
* strcat, strncat -- concatenate strings
*
* LIBRARY
* Standard C Library (libc, -lc)
*
* SYNOPSIS
* #include <string.h>
* char *
* strncat(char *restrict s1, const char *restrict s2, size_t n);
*
* DESCRIPTION
* The strcat() and strncat() functions append a copy of the
* null-terminated string s2 to the end of the null-terminated string s1, then
* add a terminating `\0'. The string s1 must have sufficient space to hold the
* result.
* The strncat() function appends not more than n characters from s2, and
* then adds a terminating `\0'.
* The source and destination strings should not overlap, as the behavior
* is undefined.
*
* RETURN VALUES
* The strcat() and strncat() functions return the pointer s1.
*/
void concat(char *sound, char s[6]) {
strncat(sound, s, strlen(s));
}
void convert(char *sound, int drops) {
sound[0] = '\0';
if (drops % 3 == 0) {
concat(sound, "Pling");
}
if (drops % 5 == 0) {
concat(sound, "Plang");
}
if (drops % 7 == 0) {
concat(sound, "Plong");
}
if (sound[0] == '\0') {
sprintf(sound, "%d", drops);
}
}
<file_sep>#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* typedef enum { false, true } bool; */
/* (C99) */
#include <stdbool.h>
/* CMocka deps */
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
/* CMocka */
#include <cmocka.h>
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x) \
do { \
} while (0)
#endif
/*
http://en.cppreference.com/w/c/string/byte/strerror
- char* strerror( int errnum );
Returns a pointer to the textual description of the system error code
errnum, identical to the description that would be printed by perror().
- errno_t strerror_s( char *buf, rsize_t bufsz, errno_t errnum );
- size_t strerrorlen_s( errno_t errnum );
*/
/*
The following function hexatridecimal uses some of the functions from above to
provide a numerical value for all alphanumerical characters base 36. This is
analogous to hexadecimal constants, only that all other letters give a value in
base 36, too.
*/
/* Supposes that lower case characters are contiguous. */
_Static_assert('z' - 'a' == 25, "alphabetic characters not contiguous");
_Static_assert('Z' - 'A' == 25, "alphabetic characters not contiguous");
/* convert an alphanumeric digit to an unsigned */
/* ’0’...’9’ => 0.. 9u */
/* ’A’...’Z’ => 10..35u */
/* ’a’...’z’ => 10..35u */
/* other values => greater */
unsigned hexatridecimal(int a) {
if (isdigit(a)) {
/* This is guaranteed to work, decimal digits
are consecutive and isdigit is not
locale dependent.
*/
/* since in the ASCII Table https://en.wikipedia.org/wiki/ASCII
the char '0' has a value of 48 and the numbers are consecutive, any
character from '0' to '9' has a value x of 'n' - 48.
*/
return a - '0';
} else {
/* leaves a unchanged if it is not lower case */
a = toupper(a);
/* from here the int a cointains a value that goes from 65 ('A') to
90 ('Z') for characters.
This allows the same pattern described above to give a numerical value
to digits, that is using the "first" value ('A' in this case) as anchor
and from there get the corresponding value.
Since we want to put this contiguous to the digit, we just add 10.
*/
/* Returns value >= 36 if not latin upper case */
return (isupper(a)) ? 10 + (a - 'A') : -1;
}
}
/* skips an eventual 0 or 0x prefix... or the given str.
Note that Clang uses int array[static 1] in function argument
position as an idiom to mean “non-NULL pointer” and will warn if you
pass NULL to the function.
The static there is an indication (a hint — but not more than a hint)
to the optimizer that it may assume there is a minimum of the
appropriate number (in the example, 5) elements in the array (and
therefore that the array pointer is not null too). It is also a
directive to the programmer using the function that they must pass a
big enough array to the function to avoid undefined behaviour.
ISO/IEC 9899:2011
§6.7.6.2 Array declarators
§6.7.6.3 Function declarators (including prototypes)
*/
/* strspn
size_t strspn ( const char * str1, const char * str2 );
Get span of character set in string
Returns the length of the initial portion of str1 which consists only of
characters that are part of str2.
The search does not include the terminating null-characters of either
strings, but ends there.
Parameters
str1: C string to be scanned.
str2: C string containing the characters to match.
Return value
The length of the initial portion of str1 containing only characters
that appear in str2.
Therefore, if all of the characters in str1 are in str2, the function
returns the length of the entire str1 string, and if the first
character in str1 is not in str2, the function returns zero.
size_t is an unsigned integral type.
*/
int try_strspn() {
int i;
char strtext[] = "129th";
char cset[] = "1234567890";
i = strspn(strtext, cset);
printf("The initial number has %d digits.\n", i);
return 0;
}
// return strncmp(s, str, strlen(s)) == 0;
size_t find_prefix(char const s[static 1], size_t i, char const str[]) {
char const *p;
p = &s[i];
while (*str) {
if (*p++ != *str++)
return 0;
}
return 1;
}
unsigned long Strtoul_inner(char const s[static 1], size_t i, unsigned base) {
unsigned long ret = 0;
while (s[i]) {
unsigned c = hexatridecimal(s[i]);
if (c >= base)
break;
/* maximal representable value for 64 bit is
3w5e11264sgsf in base 36 */
if (ULONG_MAX / base < ret) {
ret = ULONG_MAX;
errno = ERANGE;
break;
}
ret *= base;
ret += c;
++i;
}
return ret;
}
unsigned long Strtoul(char const s[static 1], unsigned base) {
/* test if base extends specification */
if (base > 36U) {
errno = EINVAL;
return ULONG_MAX;
}
/* skip spaces */
size_t i = strspn(s, " \f\n\r\t\v");
/* look for a sign */
bool switchsign = false;
switch (s[i]) {
case '-':
switchsign = true;
case '+':
++i;
}
if (!base || base == 16) {
/* adjust the base */
size_t adj = find_prefix(s, i, "0x");
if (!base)
base = (unsigned[]){
10,
8,
16,
}[adj];
i += adj;
}
/* now, start the real conversion */
unsigned long ret = Strtoul_inner(s, i, base);
return (switchsign) ? -ret : ret;
}
/* Exercises:
- [Exs 48]: The second return of hexatridecimal makes an assumption about the
relation between a and 'A'. Which?
- [Exs 49]: Describe an error scenario in case that this assumption is not
fulfilled.
- [Exs 50]: Fix this bug.
- [Exs 51]: Implement a function find_prefix as needed by Strtoul.
*/
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) { (void)state; /* unused */ }
/* Dec Hex Oct Html Char
0 0 000 NUL
48 30 060 0 0
49 31 061 1 1
50 32 062 2 2
51 33 063 3 3
52 34 064 4 4
53 35 065 5 5
54 36 066 6 6
55 37 067 7 7
56 38 070 8 8
57 39 071 9 9
...
65 41 101 A A
66 42 102 B B
67 43 103 C C
90 5A 132 Z Z
...
97 61 141 a a
98 62 142 b b
99 63 143 c c
122 7A 172 z z
*/
static void test_hexatridecimal(void **state) {
(void)state;
assert_true(hexatridecimal('0') == 0U);
assert_true(hexatridecimal('1') == 1U);
assert_true(hexatridecimal('9') == 9U);
assert_true(hexatridecimal('a') == 10U);
assert_true(hexatridecimal('z') == 35U);
assert_true(hexatridecimal('A') == 10U);
assert_true(hexatridecimal('_') == UINT_MAX);
assert_true(hexatridecimal('@') == UINT_MAX);
assert_true(hexatridecimal(' ') == UINT_MAX);
}
static void test_find_prefix(void **state) {
(void)state;
assert_true(find_prefix("0foobar", 0, "0"));
assert_false(find_prefix("foo0bar", 0, "0"));
assert_false(find_prefix("foobar0", 0, "0"));
assert_false(find_prefix("0foobar", 0, "0x"));
assert_true(find_prefix("0xfoobar", 0, "0"));
assert_true(find_prefix("0xfoobar", 0, "0x"));
assert_false(find_prefix("foo0xbar", 0, "0x"));
assert_false(find_prefix("foobar0x", 0, "0x"));
}
int test(void) {
const struct CMUnitTest tests[] = {
// clang-format off
cmocka_unit_test(null_test_success),
cmocka_unit_test(test_hexatridecimal),
cmocka_unit_test(test_find_prefix),
// clang-format on
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
int main(void) {
#if defined(TEST)
printf("\nrunning the test suite\n");
return test();
#endif
printf("nothing to do");
return EXIT_SUCCESS;
}
/*
1 EPERM Operation not permitted
2 ENOENT No such file or directory
3 ESRCH No such process
4 EINTR Interrupted system call
5 EIO Input/output error
6 ENXIO No such device or address
7 E2BIG Argument list too long
8 ENOEXEC Exec format error
9 EBADF Bad file descriptor
10 ECHILD No child processes
11 EAGAIN Resource temporarily unavailable
11 EWOULDBLOCK Resource temporarily unavailable
12 ENOMEM Cannot allocate memory
13 EACCES Permission denied
14 EFAULT Bad address
15 ENOTBLK Block device required
16 EBUSY Device or resource busy
17 EEXIST File exists
18 EXDEV Invalid cross-device link
19 ENODEV No such device
20 ENOTDIR Not a directory
21 EISDIR Is a directory
22 EINVAL Invalid argument
23 ENFILE Too many open files in system
24 EMFILE Too many open files
25 ENOTTY Inappropriate ioctl for device
26 ETXTBSY Text file busy
27 EFBIG File too large
28 ENOSPC No space left on device
29 ESPIPE Illegal seek
30 EROFS Read-only file system
31 EMLINK Too many links
32 EPIPE Broken pipe
33 EDOM Numerical argument out of domain
34 ERANGE Numerical result out of range
35 EDEADLK Resource deadlock avoided
35 EDEADLOCK Resource deadlock avoided
36 ENAMETOOLONG File name too long
37 ENOLCK No locks available
38 ENOSYS Function not implemented
39 ENOTEMPTY Directory not empty
40 ELOOP Too many levels of symbolic links
42 ENOMSG No message of desired type
43 EIDRM Identifier removed
44 ECHRNG Channel number out of range
45 EL2NSYNC Level 2 not synchronized
46 EL3HLT Level 3 halted
47 EL3RST Level 3 reset
48 ELNRNG Link number out of range
49 EUNATCH Protocol driver not attached
50 ENOCSI No CSI structure available
51 EL2HLT Level 2 halted
52 EBADE Invalid exchange
53 EBADR Invalid request descriptor
54 EXFULL Exchange full
55 ENOANO No anode
56 EBADRQC Invalid request code
57 EBADSLT Invalid slot
59 EBFONT Bad font file format
60 ENOSTR Device not a stream
61 ENODATA No data available
62 ETIME Timer expired
63 ENOSR Out of streams resources
64 ENONET Machine is not on the network
65 ENOPKG Package not installed
66 EREMOTE Object is remote
67 ENOLINK Link has been severed
68 EADV Advertise error
69 ESRMNT Srmount error
70 ECOMM Communication error on send
71 EPROTO Protocol error
72 EMULTIHOP Multihop attempted
73 EDOTDOT RFS specific error
74 EBADMSG Bad message
75 EOVERFLOW Value too large for defined data type
76 ENOTUNIQ Name not unique on network
77 EBADFD File descriptor in bad state
78 EREMCHG Remote address changed
79 ELIBACC Can not access a needed shared library
80 ELIBBAD Accessing a corrupted shared library
81 ELIBSCN .lib section in a.out corrupted
82 ELIBMAX Attempting to link in too many shared libraries
83 ELIBEXEC Cannot exec a shared library directly
84 EILSEQ Invalid or incomplete multibyte or wide character
85 ERESTART Interrupted system call should be restarted
86 ESTRPIPE Streams pipe error
87 EUSERS Too many users
88 ENOTSOCK Socket operation on non-socket
89 EDESTADDRREQ Destination address required
90 EMSGSIZE Message too long
91 EPROTOTYPE Protocol wrong type for socket
92 ENOPROTOOPT Protocol not available
93 EPROTONOSUPPORT Protocol not supported
94 ESOCKTNOSUPPORT Socket type not supported
95 ENOTSUP Operation not supported
95 EOPNOTSUPP Operation not supported
96 EPFNOSUPPORT Protocol family not supported
97 EAFNOSUPPORT Address family not supported by protocol
98 EADDRINUSE Address already in use
99 EADDRNOTAVAIL Cannot assign requested address
100 ENETDOWN Network is down
101 ENETUNREACH Network is unreachable
102 ENETRESET Network dropped connection on reset
103 ECONNABORTED Software caused connection abort
104 ECONNRESET Connection reset by peer
105 ENOBUFS No buffer space available
106 EISCONN Transport endpoint is already connected
107 ENOTCONN Transport endpoint is not connected
108 ESHUTDOWN Cannot send after transport endpoint shutdown
109 ETOOMANYREFS Too many references: cannot splice
110 ETIMEDOUT Connection timed out
111 ECONNREFUSED Connection refused
112 EHOSTDOWN Host is down
113 EHOSTUNREACH No route to host
114 EALREADY Operation already in progress
115 EINPROGRESS Operation now in progress
116 ESTALE Stale file handle
117 EUCLEAN Structure needs cleaning
118 ENOTNAM Not a XENIX named type file
119 ENAVAIL No XENIX semaphores available
120 EISNAM Is a named type file
121 EREMOTEIO Remote I/O error
122 EDQUOT Disk quota exceeded
123 ENOMEDIUM No medium found
124 EMEDIUMTYPE Wrong medium type
125 ECANCELED Operation canceled
126 ENOKEY Required key not available
127 EKEYEXPIRED Key has expired
128 EKEYREVOKED Key has been revoked
129 EKEYREJECTED Key was rejected by service
130 EOWNERDEAD Owner died
131 ENOTRECOVERABLE State not recoverable
132 ERFKILL Operation not possible due to RF-kill
133 EHWPOISON Memory page has hardware error
*/
<file_sep>#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#define MAX_LEN 512
char *teens[] = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen" };
char *tens[] = { "", "ten", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninty" };
char *ones[] = { "", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine" };
char *powers[] = { "", " thousand", " million", " billion", " trillion" };
char *thousands(long digits) {
char *tmp = calloc(sizeof(char), MAX_LEN);
long one = digits % 10;
long ten = (digits % 100) / 10;
long hundered = (digits % 1000) / 100;
if(hundered != 0 && ten == 0 && one == 0)
sprintf(tmp, "%s hundred", ones[hundered]);
else if(hundered != 0 && ten == 1)
sprintf(tmp, "%s hundred %s", ones[hundered], teens[one]);
else if(hundered != 0 && ten > 1 && one == 0)
sprintf(tmp, "%s hundred %s", ones[hundered], tens[one]);
else if(hundered != 0 && ten > 1 && one != 0)
sprintf(tmp, "%s hundred %s-%s", ones[hundered], tens[ten], ones[one]);
else if(hundered == 0 && ten == 1)
sprintf(tmp, "%s", teens[one]);
else if(hundered == 0 && ten > 1 && one != 0)
sprintf(tmp, "%s-%s", tens[ten], ones[one]);
else if(hundered == 0 && ten > 1 && one == 0)
sprintf(tmp, "%s", tens[ten]);
else if(hundered == 0 && ten == 0 && one != 0)
sprintf(tmp, "%s", ones[one]);
return tmp;
}
void strpre(char *dst, char *src) {
char *tmp = calloc(sizeof(char), strlen(dst)+ strlen(src));
strcpy(tmp, src);
strcat(tmp, dst);
strcpy(dst, tmp);
}
int say(long number, char **buffer) {
*buffer = strdup("zero");
if(number == 0) return 0;
else if(number < 0 || 999999999999 < number) return -1;
*buffer = calloc(sizeof(char), MAX_LEN);
for(int p = 0; number > 0; number /= 1000, p++) {
char *res = thousands(number % 1000);
if(strlen(res) > 0) {
strcat(res, powers[p]);
if(strlen(*buffer) > 0)
strcat(res, " ");
strpre(*buffer, res);
}
}
return 0;
}
<file_sep>#include "prime_factors.h"
size_t find_factors(uint64_t base, uint64_t factors[]) {
uint64_t divisor = 2;
size_t f = 0;
while (base > 1) {
if (base % divisor == 0) {
factors[f++] = divisor;
base /= divisor;
} else
divisor += divisor == 2 ? 1 : 2;
}
return f;
}
|
92d4507e0be8d5316c3a7824bc6de1da3d8cda42
|
[
"C",
"Makefile"
] | 129
|
C
|
zeroed/pebbles
|
becb02c21d7e2338a82ab3a6c72e72d69fec5b6f
|
7fc449cbff8cfd55a8efdcca5e60069952b3804b
|
refs/heads/master
|
<file_sep>\name{distlist}
\alias{distlist}
\title{Compute distance lists on the CShapes dataset}
\description{
This function computes a distance list for the given date.
It selects all the active CShapes polygons, determines their distances and
outputs a distance list. A distance list is a list of dyads of countries and the distances between them.
This list is returned as a data frame with three columns:
\enumerate{
\item ccode1 -- country 1's code in the coding system specified by the \code{useGW} parameter
\item ccode2 -- country 2's code in the coding system specified by the \code{useGW} parameter
\item {capdist, centdist, mindist} -- distance between country 1 and country 2 in km, where distance can be
either capital distance, centroid distance or minimum distance, as specified by the \code{type} parameter.
The latter computation is very expensive if polygons have many nodes. For that reason, the function
simplifies the country polygons according to the Douglas-Peucker algorithm (\url{http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm}),
which eliminates points from the polygons and speeds up computation. The \code{tolerance} parameter specifies the tolerance for the simplification; a value of 0 disables it.
}
Note that the function returns directed dyads. For example, if there is a country with code 1 and a country with code 2, the
resulting data frame contains the dyads (1,2), (2,1), (1,1) and (2,2). It is easy to extract the directed dyads from this data frame (see example below).
}
\usage{
distlist(date, type="mindist", tolerance=0.1, useGW=T)
}
\arguments{
\item{date}{The date for which the distance list should be computed.
This argument must be of type Date and must be in the range 1/1/1946 - end of the dataset.}
\item{type}{Specifies the type of distance list: \code{capdist} for capital distances, \code{centdist} for centroid distances, and \code{mindist} for minimum distances.}
\item{useGW}{Boolean argument specifying the system membership coding. TRUE (Default): Gleditsch and Ward (1999). FALSE: Correlates of War.}
\item{tolerance}{Tolerance for polygon simplification according the the Douglas-Peucker algorithm. Only used for mindist computation (type="mindist").}
}
\value{
A distance list with three columns, the first two of which contain the identifiers for the
two countries in the dyad, and the third one containing the distance between the two countries.
}
\examples{
# Compute a list of minimum distances
# for the international system on 1/1/1946
# using the Correlates of War list and the default accuracy
\dontrun{dl <- distlist(as.Date("1946-1-1"), type="capdist", tolerance=0.5, useGW=FALSE)}
# we eliminate duplicate dyads
\dontrun{dl <- subset(dl, ccode1 < ccode2)}
}
\author{<NAME>}<file_sep>distmatrix <- function(date, type="mindist", tolerance=0.1, useGW=T) {
# check input
if (!inherits(date, "Date")) {
stop("date is not of type Date")
}
if (date < as.Date("1946-1-1") | date > as.Date("2016-6-30")) {
stop("Specified date is out of range")
}
if (!(type %in% c("mindist", "capdist", "centdist"))) {
stop("Wrong type argument. Possible values: mindist, capdist, centdist")
}
if (tolerance<0) {
stop("Tolerance must be >=0")
}
# where to look for the dataset
path <- paste(system.file(package = "cshapes"), "shp/cshapes.shp", sep="/")
# load the dataset
cshp.full <- readShapePoly(path, proj4string=CRS("+proj=longlat +ellps=WGS84"), IDvar="FEATUREID")
# select all relevant polygons
if (useGW) {
cshp.full <- cshp.full[cshp.full$GWCODE>=0,]
startdate <- as.Date(paste(cshp.full$GWSYEAR, cshp.full$GWSMONTH, cshp.full$GWSDAY, sep="-"))
enddate <- as.Date(paste(cshp.full$GWEYEAR, cshp.full$GWEMONTH, cshp.full$GWEDAY, sep="-"))
} else {
cshp.full <- cshp.full[cshp.full$COWCODE>=0,]
startdate <- as.Date(paste(cshp.full$COWSYEAR, cshp.full$COWSMONTH, cshp.full$COWSDAY, sep="-"))
enddate <- as.Date(paste(cshp.full$COWEYEAR, cshp.full$COWEMONTH, cshp.full$COWEDAY, sep="-"))
}
cshp.full <- cshp.full[!is.na(startdate) & !is.na(enddate),]
startdate <- startdate[!is.na(startdate)]
enddate <- enddate[!is.na(enddate)]
cshp.part <- cshp.full[startdate <= date & enddate >= date,]
# compute pairwise distances
if (useGW) {
cshp.part <- cshp.part[order(cshp.part$GWCODE),]
ccodes <- cshp.part$GWCODE
} else {
cshp.simple <- cshp.part[order(cshp.part$COWCODE),]
ccodes <- cshp.part$COWCODE
}
resultmatrix <- matrix(0, nrow=length(ccodes), ncol=length(ccodes))
colnames(resultmatrix) <- ccodes
rownames(resultmatrix) <- ccodes
if (type=="mindist") {
# simplify the polygons
cshp.simple <- thinnedSpatialPoly(cshp.part, tolerance, minarea=0, avoidGEOS=T)
for (c1 in 1:(length(ccodes)-1)) {
for (c2 in (c1+1):length(ccodes)) {
# compute distance
dist <- cshp.mindist(cshp.simple[c1,], cshp.simple[c2,])
resultmatrix[c1,c2] <- dist
resultmatrix[c2,c1] <- dist
}
}
} else {
for (c1 in 1:(length(ccodes)-1)) {
for (c2 in (c1+1):length(ccodes)) {
if (type=="capdist") {
dist <- cshp.capdist(cshp.part[c1,], cshp.part[c2,])
}
if (type=="centdist") {
dist <- cshp.centdist(cshp.part[c1,], cshp.part[c2,])
}
resultmatrix[c1,c2] <- dist
resultmatrix[c2,c1] <- dist
}
}
}
resultmatrix
}
cshp.mindist <- function(polygon1, polygon2) {
# create matrices containing all points of the polygons
p1 <- ldply(polygon1@polygons[[1]]@Polygons, function(y) {y@coords})
p2 <- ldply(polygon2@polygons[[1]]@Polygons, function(y) {y@coords})
# use spDists function to compute distances between all pairs of points
min(spDists(as.matrix(p1), as.matrix(p2), longlat=T))
}
cshp.centdist <- function(polygon1, polygon2) {
# use spDists function to compute distances between centroids
spDistsN1(coordinates(polygon1), coordinates(polygon2), longlat=T)
}
cshp.capdist <- function(polygon1, polygon2) {
# use spDists function to compute distances between centroids
spDistsN1(matrix(c(polygon1$CAPLONG, polygon1$CAPLAT), ncol=2), matrix(c(polygon2$CAPLONG, polygon2$CAPLAT), ncol=2), longlat=T)
}
<file_sep>\name{cshp}
\alias{cshp}
\title{Access the CShapes dataset in R}
\description{
The \code{cshp} function makes the cshapes dataset available for usage in R. If no date is given, it returns a \code{SpatialPolygonsDataFrame} with the complete CShapes dataset. If specified, the date is used to create a snapshot of the dataset, containing all cshapes polygons active at the given date.
}
\usage{
cshp(date=NA, useGW=TRUE, simplify=FALSE, tolerance=0.05)
}
\arguments{
\item{date}{The date for which the cshapes polygons should be extracted.
This argument must be of type Date and must be in the range 1/1/1946 - end of the dataset. If omitted, the complete dataset is returned.}
\item{useGW}{Boolean argument specifying the system membership coding. TRUE (Default): Gleditsch and Ward (1999). FALSE: Correlates of War.}
\item{simplify}{Boolean argument specifying whether the shapefile should be simplified by removing vertices, defaults to \code{FALSE}.}
\item{tolerance}{Numeric value for tolerance parameter used when \code{simplify == TRUE}, defaults to 0.05.}
}
\value{
A class \code{sf} \code{data.frame}, containing the complete CShapes dataset, or the CShapes snapshot for the specified date.
}
\examples{
# Retrieve the dataset
cshp.data <- cshp()
# Get summary statistics
summary(cshp.data)
# Extract Switzerland
switzerland <- cshp.data[cshp.data$COWCODE==225,]
# Plot Switzerland
plot(switzerland)
# Extract a snapshot of cshapes as of June 30, 2002
# using the Gleditsch&Ward coding system
cshp.2002 <- cshp(date=as.Date("2002-6-30"), useGW=TRUE)
}
\author{<NAME>}
\seealso{
\code{\link[sp]{SpatialPolygonsDataFrame}}
}<file_sep>cshp <- function(date=NA, useGW=TRUE, simplify=FALSE, tolerance = 0.05) {
# check input
if (!is.na(date) && !inherits(date, "Date")) {
stop("date is not of type Date")
}
if (!is.na(date) && (date < as.Date("1946-1-1") | date > as.Date("2016-6-30"))) {
stop("Specified date is out of range")
}
# where to look for the dataset
path <- paste(system.file(package = "cshapes"), "shp/cshapes.shp", sep="/")
# load the dataset
cshp.full <- st_read(path)
if (simplify == T) {
cshp.full <- st_simplify(cshp.full, dTolerance = tolerance)
}
if (is.na(date)) {
cshp.full
} else if (useGW) {
cshp.full <- cshp.full[cshp.full$GWCODE>=0,]
startdate <- as.Date(paste(cshp.full$GWSYEAR, cshp.full$GWSMONTH, cshp.full$GWSDAY, sep="-"))
enddate <- as.Date(paste(cshp.full$GWEYEAR, cshp.full$GWEMONTH, cshp.full$GWEDAY, sep="-"))
cshp.part <- cshp.full[startdate <= date & enddate >= date,]
cshp.part
} else {
cshp.full <- cshp.full[cshp.full$COWCODE>=0,]
startdate <- as.Date(paste(cshp.full$COWSYEAR, cshp.full$COWSMONTH, cshp.full$COWSDAY, sep="-"))
enddate <- as.Date(paste(cshp.full$COWEYEAR, cshp.full$COWEMONTH, cshp.full$COWEDAY, sep="-"))
cshp.part <- cshp.full[startdate <= date & enddate >= date,]
cshp.part
}
}
<file_sep>\name{cshapes-package}
\alias{cshapes-package}
\alias{cshapes}
\docType{package}
\title{CShapes Dataset and Utilities}
\description{
R Package for CShapes, a GIS dataset of country boundaries (1946-2015). Includes functions for data extraction and the computation of weights matrices.}
\details{
The \code{cshapes} package facilitates the use of CShapes from R. CShapes is a GIS dataset of historical country boundaries (1946-today) and compatible with two country lists (Gleditsch and Ward 1999 and Correlates of War, see references below). In particular, the package enables access to the
dataset directly, as well as distance computations on country polygons for specific points in time. Access to the dataset from within R is done using the
\code{\link{cshp}} function. Two functions exist to compute minimum-, capital- and centroid distances between countries: the \code{\link{distmatrix}} function returns these as a matrix (convenient for many spatial statistical applications), and the \code{\link{distlist}} function returns a list of dyadic distances (distances between country pairs).
See the examples given in the documentation of the functions in this package. The main cshapes website is located at \url{http://nils.weidmann.ws/projects/cshapes} and contains additional documentation and examples for the dataset and the R package.
For more information on the CShapes dataset, see Weidmann, <NAME>., <NAME> and <NAME>. 2010. "The Geography of the International System: The CShapes Dataset." International Interactions 36(1).
The associated R package is introduced in Weidmann, <NAME>. and <NAME>. 2010. "Mapping and Measuring Country Shapes: The cshapes Package." R Journal 2(1). Available online at \url{https://journal.r-project.org/archive/2010-1/RJournal_2010-1_Weidmann+Skrede~Gleditsch.pdf}.
}
\author{
<NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
Maintainer: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
}
\references{
Correlates of War Project. 2011. "State System Membership List, v2011.1." Online, \url{http://correlatesofwar.org}.
Gleditsch, <NAME>. & <NAME>. 1999. "Interstate System Membership: A Revised List of the Independent States since 1816." International Interactions 25: 393-413.
Online, \url{http://privatewww.essex.ac.uk/~ksg/statelist.html}.
}
\keyword{ package }
<file_sep>\name{distmatrix}
\alias{distmatrix}
\title{Compute distance matrices on the CShapes dataset}
\description{
This function computes a distance matrix for the given date.
It selects all the active CShapes polygons, determines their distances and
outputs a distance matrix in kilometers. The function can compute different types of distance matrices,
specified by the "type" parameter: (i) capital distances, and (ii) centroid distances, and (iii) minimum distances
between polygons. The latter computation is very expensive if polygons have many nodes. For that reason, the function
simplifies the country polygons according to the Douglas-Peucker algorithm (\url{http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm}),
which eliminates points from the polygons and speeds up computation. The \code{tolerance} parameter specifies the tolerance for the simplification;
a value of 0 disables it.
}
\usage{
distmatrix(date, type="mindist", tolerance=0.1, useGW=T)
}
\arguments{
\item{date}{The date for which the distance matrix should be computed.
This argument must be of type Date and must be in the range 1/1/1946 - end of the dataset.}
\item{type}{Specifies the type of distance matrix: \code{capdist} for capital distances, \code{centdist} for centroid distances, and \code{mindist} for minimum distances.}
\item{useGW}{Boolean argument specifying the system membership coding. TRUE (Default): Gleditsch and Ward (1999). FALSE: Correlates of War.}
\item{tolerance}{Tolerance for polygon simplification according the the Douglas-Peucker algorithm. Only used for mindist computation (type="mindist").}
}
\value{
A quadratic weights matrix, with the row and column labels containing
the country identifiers in the specified coding system (COW or G&W).
}
\examples{
# Compute a matrix of minimum distances
# for the international system on 1/1/1946
# using the Correlates of War list and the default accuracy
\dontrun{wmat <- distmatrix(as.Date("1946-1-1"), type="capdist", tolerance=0.5, useGW=FALSE)}
# For model estimation, our matrix should contain
# the inverted distances
\dontrun{wmat <- 1/wmat}
# Fix the values along the diagonale
\dontrun{diag(wmat) <- 0}
}
\author{<NAME>}<file_sep>distlist <- function(date, type="mindist", tolerance=0.1, useGW=T) {
# check input
if (!inherits(date, "Date")) {
stop("date is not of type Date")
}
if (date < as.Date("1946-1-1") | date > as.Date("2016-6-30")) {
stop("Specified date is out of range")
}
if (!(type %in% c("mindist", "capdist", "centdist"))) {
stop("Wrong type argument. Possible values: mindist, capdist, centdist")
}
if (tolerance<0) {
stop("Tolerance must be >=0")
}
# minimum distance
if (type=="mindist") {
dmat <- distmatrix(date, type="mindist", tolerance, useGW)
}
# capital distance
if (type=="capdist") {
dmat <- distmatrix(date, type="capdist", useGW=useGW)
}
# centroid distance
if (type=="centdist") {
dmat <- distmatrix(date, type="centdist", useGW=useGW)
}
dimension <- ncol(dmat)
dimlabels <- colnames(dmat)
ccode1 <- as.vector(sapply(dimlabels, function (x) rep(x, dimension)))
ccode2 <- rep(dimlabels, dimension)
resultframe <- data.frame(cbind(as.numeric(ccode1), as.numeric(ccode2), as.numeric(dmat)))
colnames(resultframe) <- c("ccode1", "ccode2", type)
resultframe
}
|
a06c6b75026c1f78ffaf4f7d6410bfa0340beea5
|
[
"R"
] | 7
|
R
|
thereseanders/cshapes
|
623b3f94dd3d6e554d8a4b526295a9d8cc625856
|
e4c8d8917a381f5b6e1a4e0ff000065d94c7f57e
|
refs/heads/main
|
<file_sep>import copy
#dictionary format: [usability per weight index (initially 0), needed parts, weight in grams (initially), usability]
products = {"Notebook Office 13": [0, 205, 2451, 40],
"Notebook Office 14": [0, 420, 2978, 35],
"Notebook outdoor": [0, 450, 3625, 80],
"Mobiltelefon Büro": [0, 60, 717, 30],
"Mobiltelefon outdoor": [0, 157, 988, 60],
"Mobiltelefon Heavy-Duty": [0, 220, 1220, 65],
"Tablet Büro klein": [0, 620, 1405, 40],
"Tablet Büro groß": [0, 250, 1455, 40],
"Tablet outdoor klein": [0, 540, 1690, 45],
"Tablet outdoor groß": [0, 370, 1980, 68]
}
#this function takes one input array as described above and calculates the profitability index for this element and writes it at index 0 of the list;
#converts weights from grams to kg
def calculate_profitability_index(dict):
for key, value in products.items():
value[2] = value[2]/1000
value[0] = value[3]/(value[2]) # calculating the profitability per kg
#turns profitability index positive again (was negative during calculation)
def turn_profitability_positive(dict):
for key, value in dict.items():
if value[0] < 0:
value[0] = - value[0]
#gets key in dictionary with maximum profitability with respect to the available unit number and weight
def get_max_key(base_info, capacity):
while True:
current_max_key = max(base_info, key=base_info.get)
temp_value = base_info.get(current_max_key) #best maximum value guess, needs to be checked whether it fits in our truck
if temp_value[0] < 0:
return 0
if temp_value[2] < capacity and temp_value[0] >= 0 and temp_value[1] > 0:
#if enough capacity is available, return the key of the dict entry with max profitability
return current_max_key
else:
temp_value[0] = - temp_value[0] #to make sure it will not be detected as max during the max finding process, will be reversed at the end
base_info[current_max_key] = temp_value
#function for loading the empty transporter, first parameter load capacity in kg, second parameter weight of the driver, third parameter: available products dict
def load_transporter(capacity, weight, product_info):
#create an empty dictionary as loading list and inventory dictionary
loading_list = {}
# code to fill loading list
capacity_greedy = capacity - weight
usability = 0
#loading process with greedy algorithm
while True:
#finding the key with the current maximum usability and get the value array for it with fitting weight
current_max_key = get_max_key(product_info,capacity_greedy) #returns 0 when no fitting element can be found
if current_max_key == 0:
break
current_max_value = product_info.get(current_max_key)
#if blocks for faster loading (loads 100, 10, 1 in a row)
loading_keys = loading_list.keys() #gets the keys of the loading list to check whether there is already an entry with specified key
n = [100,10,1]
for elem in n:
if current_max_value[2]*elem < capacity_greedy and current_max_value[1] >= elem:
if current_max_key in loading_keys:
loading_list[current_max_key] += elem
capacity_greedy = capacity_greedy - (current_max_value[2] * elem)
current_max_value[1] = current_max_value[1] - elem
usability += current_max_value[3] * elem
else:
loading_list[current_max_key] = elem
capacity_greedy = capacity_greedy - (current_max_value[2] * elem)
current_max_value[1] = current_max_value[1] - elem
usability += current_max_value[3] * elem
turn_profitability_positive(product_info)
return loading_list, usability
#perform loading comparison
#initializing product lists, usabilities and loading lists
calculate_profitability_index(products)
#deep copies are needed here because of Python design priciples
product_list1 = copy.deepcopy(products)
product_list2 = copy.deepcopy(products)
usability_1 = 0
usability_2 = 0
usability_3 = 0
usability_4 = 0
total_usability_1 = 0
total_usability_2 = 0
loadinglist_1 = {}
loadinglist_2 = {}
loadinglist_3 = {}
loadinglist_4 = {}
#case 1
loadinglist_1, usability_1 = load_transporter(1100, 85.7, product_list1)
loadinglist_2, usability_2 = load_transporter(1100, 72.4, product_list1)
total_usability_1 = usability_1 + usability_2
#case 2
loadinglist_3, usability_3 = load_transporter(1100, 72.4, product_list2)
loadinglist_4, usability_4 = load_transporter(1100, 85.7, product_list2)
total_usability_2 = usability_3 + usability_4
if total_usability_1 > total_usability_2:
print("Gesamtnutzen: " + str(total_usability_1) + " Nutzeinheiten")
print("Ladungsliste 1. LKW: " + str(loadinglist_1))
print("Ladungsliste 2. LKW: " + str(loadinglist_2))
else:
print("Gesamtnutzen: " + str(total_usability_2) + " Nutzeinheiten")
print("Ladungsliste 1. LKW: " + str(loadinglist_3))
print("Ladungsliste 2. LKW: " + str(loadinglist_4))<file_sep># Coding Challenge BWI
The aim of this challenge was to develop an algorithm to fill two trucks with the maximum usability possible. To do this task, a greedy algorithm was chosen because it provides fast solution times and is easy to understand. As a runtime optimization feature a multiple item loading feature was implemented
# Run the code
To run the code, make sure that the Python package "copy" is installed. Once that is ensured, download the code and simply navigate to the saving directory. Run the code by typing "python3 greedy_new.py" in your console.
# Solution
Solution taken from the code:
Gesamtnutzen: 74640 Nutzeinheiten
Ladungsliste 1. LKW: {'Mobiltelefon outdoor': 157, 'Mobiltelefon Heavy-Duty': 220, 'Mobiltelefon Büro': 60, 'Tablet outdoor groß': 283}
Ladungsliste 2. LKW: {'Tablet outdoor groß': 87, 'Tablet Büro klein': 599}
|
d62a61a9d529bc0236d98f7353c9a5b7d70dd251
|
[
"Markdown",
"Python"
] | 2
|
Python
|
MoritzKraus/getinitBWI
|
145479a46f5f1d763348f1d2040662077dd8f4f8
|
0fc37e62976f0a2c6f86c0f30c905f0aa2a2e5ed
|
refs/heads/master
|
<repo_name>vishalsinghji/visitorbackened<file_sep>/models/postMessage.js
import mongoose from 'mongoose';
const postSchema = mongoose.Schema({
phone: Number,
purpose: String,
name: String,
address: String,
selectedFile: String,
createdAt: {
type: Date,
default: new Date(),
},
})
var PostMessage = mongoose.model('PostMessage', postSchema);
export default PostMessage;
|
7eb6c32b723154b61cf8d025116e6e6cfd4ac560
|
[
"JavaScript"
] | 1
|
JavaScript
|
vishalsinghji/visitorbackened
|
df62634de9d01658481795a3d8396fa9f2fdb8bb
|
63ed4bbd61ac416f969f783a54cab4934bf0524d
|
refs/heads/master
|
<file_sep>function makeRequest(urlEndpoint, func) {
let request = new XMLHttpRequest();
let jsonObj = null, obj = null;
request.onload = function() {
if (this.responseText) {
jsonObj = this.responseText;
obj = JSON.parse(jsonObj);
func(obj);
} else {
console.log("failed");
}
}
request.open("GET", urlEndpoint, true);
request.send();
return obj;
}
function createMovieDetailElement(parentTag, parentID, firstChildTag, firstChildText, lastNode) {
let parent = document.createElement(parentTag);
parent.id = parentID;
if (firstChildTag) {
let firstchild = document.createElement(firstChildTag);
firstchild.innerHTML = firstChildText;
parent.append(firstchild, lastNode);
return parent;
}
parent.append(lastNode);
return parent;
}
function showMovieDetail(obj, list) {
// make click effect
let selectedList = document.getElementsByClassName("selected-list");
[...selectedList].forEach((item) => {
item.classList.remove("selected-list");
});
list.classList.add("selected-list");
const {title, description, director, producer, rt_score} = obj;
// convert tr_score to star (100 = 5 stars)
rt_score_star = (rt_score/100 * 5).toFixed(2);
let movieDetailContainer = document.querySelector("div.movie-detail-container");
movieDetailContainer.innerHTML = "";
const movieTitle = createMovieDetailElement("h1","movie-title", null, null, title);
const movieDescription = createMovieDetailElement("p", "movie-description", null, null, description);
const movieDirector = createMovieDetailElement("p", "movie-director", "strong", "Director: ", director);
const movieProducer = createMovieDetailElement("p", "movie-producer", "strong", "Producer: ", producer);
const movieScore = createMovieDetailElement("p", "movie-score", "strong", "Score: ", rt_score_star);
const movieDescription2 = createMovieDetailElement("p", "movie-description", null, null, description);
const movieDescription3 = createMovieDetailElement("p", "movie-description", null, null, description);
const movieDescription4 = createMovieDetailElement("p", "movie-description", null, null, description);
const movieDescription5 = createMovieDetailElement("p", "movie-description", null, null, description);
const movieDescriptionContainer = createMovieDetailElement("div", "movie-description-container", null, null, movieDescription);
movieDescriptionContainer.append(movieDescription2, movieDescription3, movieDescription4, movieDescription5);
movieDetailContainer.append(movieTitle, movieDirector, movieProducer, movieScore, movieDescriptionContainer);
}
function App() {
makeRequest("https://ghibliapi.herokuapp.com/films", (movieObj) => {
movieObj.forEach(movie => {
// create new list element
let list = document.createElement("li");
list.className = "movie-list";
list.dataset.id = movie.id;
let title = document.createElement("p")
let director = document.createElement("p");
title.innerHTML = movie.title;
director.innerHTML = "Director: " + movie.director;
list.append(title, director);
// click a list to show movie details
list.addEventListener('click', showMovieDetail.bind(this, movie, list));
let movieListContainer = document.querySelector("div.movie-list-container>ul");
movieListContainer.append(list);
});
});
}
App();
<file_sep># STUDIO-GHIBLI-API
Learn to connect to an API with JavaScript
Go to link: https://chondan.github.io/MovieReviewFromSTUDIO-GHIBLI-API/
|
af30f0a475c1e47fda1acf58f815eff5855c9ad8
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
Chondan/MovieReviewFromSTUDIO-GHIBLI-API
|
c28e3346330a3f86a3461ef1430750dab8b99be4
|
82da5e43660454801d66d1eae361851d7f18dabd
|
refs/heads/master
|
<file_sep>#!/bin/bash
for file in $(ls *.js *.css *.json); do
MD5=`md5sum $file|awk '{ print $1 }'`
sed -i -e "s/\(.*$file?md5=\)\w*\"/\1$MD5\"/" index.htm
done
<file_sep>"use strict";
var _Utils = require("./utils.js");
var _Drawer = require("./draw.js");
var _Actions = require("./actions.js");
var _SecretActions = require("./secrets.js");
//var RtUpdate = require("./rt_network.js");
var gTemplates = require("json!./templates.json");
var _Document = require("./dom_document.js")
var fs = require("fs");
var url = require("url");
var XMLHttpRequest = require("xhr2");
var gPrivTimeline = {"done":0,"postsById":{},"oraphed":{count:0},"noKey":{},"noDecipher":{},nCmts:0,"posts":[] };
require("script!./config_srv.json");
var head = require("raw!./head.template");
global.window = {"setTimeout":function(){}}
var Actions_srv = new Object();
for(var key in new _Actions()){ Actions_srv[key]=function(a){return function(){ return ["Actions",a]; }; }(key)};
var SecretActions_srv = new Object();
for(var key in new _SecretActions()){ SecretActions_srv[key]=function(a){return function(){ return ["SecretActions",a]; }; }(key)};
module.exports = function(req,res){
var document = new _Document();
var cView = {
"gUsers": { "byName":{}}
,"gUsersQ": {}
,"gComments": {}
,"gAttachments": {}
,"gFeeds": {}
,"gEmbed": {}
,"gRt": {}
,"gNodes": {}
,"logins": {}
,"mainId": ""
,"rtSub" : {}
,"mode": "username"
,get "gMe"(){
var ids = Object.keys(this.logins);
if(ids.length == 1)return this.logins[ids[0]].data;
if((this.mainId == "")||(ids.length == 0))return null;
return this.logins[this.mainId].data;
}
,get "ids"(){
var ids = Object.keys(this.logins);
if (!ids.length) return null;
return ids;
}
};
var Utils = new _Utils(cView);
var Drawer = new _Drawer(cView);
cView.doc = document;
document.cView = cView;
cView.Utils = Utils;
cView.Drawer = Drawer;
cView.Actions = Actions_srv;
cView.SecretActions = SecretActions_srv;
Utils.genNodes(gTemplates.nodes).forEach( function(node){ cView.gNodes[node.className] = node; });
var Url2link = require("./url2link");
cView.autolinker = new Url2link({"truncate":25});
//cView.autolinker = new Autolinker({"truncate":20, "replaceFn":Utils.frfAutolinker } );
Utils.setStorage();
var urlReq = url.parse(req.url, true);
document.location = urlReq;
var locationPath = (urlReq.pathname).slice(gConfig.front.length);
var locationSearch = urlReq.search;
if (locationPath == "")locationPath = "home";
if (locationSearch == "")locationSearch = "?offset=0";
cView.cSkip = parseInt(locationSearch.match(/offset=([0-9]*).*/)[1]);
var arrLocationPath = locationPath.split("/");
cView.timeline = arrLocationPath[0];
if(req.headers.cookie) req.headers.cookie.split(";").some(function(c){
var cookie = c.split("=");
if(cookie[0].trim() == gConfig.tokenPrefix + "authToken" ){
cView.token = decodeURIComponent(cookie[1]);
return true;
}
});
document.head.innerHTML += head;
var nodeInitS = document.createElement("script");
nodeInitS.innerHTML = "\ninit();\nvar cView = document.cView;"
+ '\ncView.timeline = "'+ cView.timeline+'";' ;
if(["home", "filter", "settings", "requests"].some(function(a){
return a == cView.timeline;
})){
if(!cView.token) {
res.writeHeader(403);
nodeInitS.innerHTML += "\ncView.Utils.auth();";
document.body.appendChild(nodeInitS);
res.end(document.toString());
return;
}
}else if(!cView.token) cView.logins = [];
switch(cView.timeline){
case "settings":
case "requests":
cView.xhrurl = "";
locationSearch = "";
break;
default:
if(arrLocationPath.length > 1){
if (locationPath == "filter/discussions") {
cView.timeline = locationPath;
cView.xhrurl = gConfig.serverURL + "timelines/filter/discussions";
} else if (locationPath == "filter/direct") {
cView.timeline = locationPath;
cView.xhrurl = gConfig.serverURL + "timelines/filter/directs";
}else{
cView.xhrurl = gConfig.serverURL +"posts/"+arrLocationPath[1];
locationSearch = "?maxComments=all";
}
} else cView.xhrurl = gConfig.serverURL + "timelines/"+locationPath;
}
//initDoc(req)
//new Promise(function(resolve,reject){resolve([JSON.parse(fs.readFileSync("data.json"))]);})
getContent(cView.xhrurl+locationSearch, cView.token).then(function(vals){
var content = vals[0];
if(vals[1]){
cView.mainId = vals[1].users.id;
cView.logins[cView.mainId] = new Object();
cView.logins[cView.mainId].data = vals[1];
cView.logins[cView.mainId].token = cView.token;
Utils.refreshLogin(cView.mainId);
}
if(content){
Drawer.draw(content);
nodeInitS.innerHTML += "\ndocument.cView.gContent = " + JSON.stringify(content)+ ";";
}
if(typeof cView.gMe !== "undefined")
nodeInitS.innerHTML += '\n cView.mainId = "' + cView.mainId + '";'
+ '\ncView.token = cView.Utils.getCookie(gConfig.tokenPrefix + "authToken");'
+ '\ncView.logins[cView.mainId] = new Object() ;'
+ '\ncView.logins[cView.mainId].token = ' + 'cView.token;'
+ '\ncView.logins[cView.mainId].data = ' + JSON.stringify(cView.gMe)+ ';'
;
nodeInitS.innerHTML += "\nsrvDoc();"
document.body.appendChild(nodeInitS);
res.writeHead(200);
res.end(document.toString());
},function(ret){
res.writeHead(500);
res.end();
});
}
function getContent(url, token){
var arrP = new Array();
if (url != "")arrP.push(new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.onload = function(){
if(oReq.status < 400)
resolve(JSON.parse(oReq.response));
else {
//console.log(oReq.statusText);
reject();
}
};
oReq.open("get",url,true);
if(token)oReq.setRequestHeader("X-Authentication-Token", token);
oReq.send();
}));
else arrP.push(new Promise(function(resolve){resolve(null);}));
if(token) arrP.push(new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.open("get", gConfig.serverURL +"users/whoami", true);
oReq.setRequestHeader("X-Authentication-Token", token);
oReq.onload = function(){
if(oReq.status < 400)
resolve(JSON.parse(oReq.response));
else {
//console.log(oReq.statusText);
reject();
}
}
oReq.send();
}));
else arrP.push(new Promise(function(resolve){resolve(null);}));
return Promise.all(arrP);
}
<file_sep>"use strict";
define("./draw", [],function(){
function _Drawer(v){
this.cView = v;
}
_Drawer.prototype = {
constructor: _Drawer
,"writeAllLikes":function(id,nodeLikes){
var cView = this.cView;
var post = cView.doc.getElementById(id).rawData;
var context = cView.contexts[post.domain];
nodeLikes.innerHTML = "";
var nodeLike = cView.doc.createElement("span");
nodeLike.className = "p-timeline-user-like";
for(var like = 0; like < post.likes.length; like++){
var nodeCLike = nodeLike.cloneNode();
nodeCLike.innerHTML = context.gUsers[post.likes[like]].link;
//nodeLikes.childNodes[idx].appendChild(nodeCLike);
nodeLikes.appendChild(nodeCLike);
}
var suffix = cView.doc.createElement("span");
suffix.innerHTML = " liked this";
//nodeLikes.childNodes[idx].appendChild(suffix);
nodeLikes.parentNode.appendChild(suffix);
}
,"genLikes":function(nodePost){
var cView = this.cView;
var post = nodePost.rawData;
var context = cView.contexts[post.domain];
var postNBody = nodePost.cNodes["post-body"];
var node = cView.doc.createElement("div");
node.className = "likes";
postNBody.cNodes["post-info"].replaceChild(node, postNBody.cNodes["post-info"].cNodes["likes"]);
postNBody.cNodes["post-info"].cNodes["likes"] = node;
if(!Array.isArray(post.likes) || !post.likes.length ) return;
postNBody.cNodes["post-info"].cNodes["likes"].appendChild(cView.gNodes["likes-smile"].cloneNode(true));
var nodeLikes = cView.doc.createElement( "span");
/*
var l = post.likes.length;
if(cView.ids){
for (var idx = 0; idx< l;idx++) {
var like = post.likes[idx];
if(like == cView.gMe.users.id){
post.likes.splice(idx,1);
post.likes.unshift(like);
break;
}
}
}
*/
var nodeLike = cView.doc.createElement("span");
nodeLike.className = "p-timeline-user-like";
post.likes.forEach(function(like){
var nodeCLike = nodeLike.cloneNode();
nodeCLike.innerHTML = context.gUsers[like].link;
nodeLikes.appendChild(nodeCLike);
});
var suffix = cView.gNodes["likes-suffix"].cloneAll();
if (post.omittedLikes){
suffix.cNodes["likes-omitted"].hidden = false;
suffix.getElementsByTagName("a")[0].innerHTML = post.omittedLikes + " other people "
}
suffix.className = "nocomma";
postNBody.cNodes["post-info"].cNodes["likes"].appendChild(nodeLikes);
postNBody.cNodes["post-info"].cNodes["likes"].cNodes = new Object();
postNBody.cNodes["post-info"].cNodes["likes"].cNodes["comma"] = nodeLikes;
postNBody.cNodes["post-info"].cNodes["likes"].appendChild(suffix);
//postNBody.cNodes["post-info"].cNodes["likes"].appendChild(suffix);
nodeLikes.className = "comma";
if(context.ids.length && (post.likes[0] == context.gMe.users.id)){
postNBody.cNodes["post-info"].myLike = nodeLikes.childNodes[0];
if( postNBody.cNodes["post-info"].nodeLike) {
postNBody.cNodes["post-info"].nodeLike.innerHTML = "Un-like";
postNBody.cNodes["post-info"].nodeLike.action = false;
}
}
}
,"genUserDetails":function(username, context){
var cView = this.cView;
var user = context.gUsers.byName[username];
var nodeUD = cView.gNodes["user-details"].cloneAll();
var nodeInfo = nodeUD.cNodes["ud-info"];
nodeInfo.cNodes["ud-username"].value = user.username;
nodeInfo.getNode(["c","ud-avatar"],["c","ud-avatar-img"]).src = user.profilePictureMediumUrl;
nodeInfo.getNode(["c","ud-text"],["c","ud-title"]).innerHTML = user.untagScreenName;
if(typeof user.description === "string")
nodeInfo.getNode(["c","ud-text"],["c","ud-desc"])[(cView.readMore?"words":"innerHTML")] = context.digestText(user.description);
//nodeInfo.getNode(["c","ud-text"],["c","ud-desc"]).innerHTML = context.digestText(user.description);
if (user.type == "group")
["uds-subs","uds-likes","uds-com"].forEach(function(key){
nodeInfo.getNode(["c","ud-stats"],["c",key]).style.display = "none";
});
if(typeof user.statistics !== "undefined"){
var stats = {
"uds-subs":user.statistics.subscriptions
,"uds-subsc":user.statistics.subscribers > 0? user.statistics.subscribers:""
,"uds-likes":user.statistics.likes
,"uds-com":user.statistics.comments
}
Object.keys(stats).forEach(function(key){
nodeInfo.getNode(["c","ud-stats"],["c",key],["c","val"]).innerHTML = stats[key];
});
}
return nodeUD;
}
,"genProfile": function(user){
var cView = document.cView;
var context = cView.contexts[user.domain];
var nodeProfile = cView.gNodes["settings-profile"].cloneAll();
nodeProfile.getElementsByClassName("sp-username")[0].innerHTML = "@" + user.username;
nodeProfile.cNodes["chng-avatar"].cNodes["sp-avatar-img"].src = user.profilePictureMediumUrl;
if (typeof user.description !== "undefined")
nodeProfile.cNodes["gs-descr"].value = user.description;
var nodes = nodeProfile.getElementsByTagName("input");
if(typeof user.isProtected === "undefined") user.isProtected = "0";
if(typeof user.isPrivate === "undefined") user.isPrivate = "0";
for(var idx = 0; idx < nodes.length; idx++){
var node = nodes[idx];
switch(node.name){
case "id":
node.value = user.id;
break;
case "token":
node.value = context.logins[user.id].token;
break;
case "is-main":
node.checked = (context.logins[user.id].token == context.token);
node.name = "is-main-"+user.domain;
break;
case "email":
if(typeof user.email !== "undefined" )
node.value = user.email;
break;
case "domain":
node.value = user.domain;
break;
case "screen-name":
node.value = user.screenName;
break;
case "access":
node.name = ["access",user.domain, user.id].join("-");
if(JSON.parse(user.isPrivate)
&&( node.value == "is-private"))
node.checked = true;
else if(JSON.parse(user.isProtected)
&&(node.value == "is-protected"))
node.checked = true;
else if((node.value == "is-public")
&&(!JSON.parse(user.isProtected))
&&(!JSON.parse(user.isPrivate)))
node.checked = true;
break;
}
};
return nodeProfile;
}
,"drawSettings":function(){
var cView = this.cView;
var body = cView.doc.getElementById("container");
body.cNodes["pagetitle"].innerHTML = "Settings";
cView.doc.title = "Settings";
var nodeSettingsHead = cView.gNodes["settings-head"].cloneAll();
body.appendChild(nodeSettingsHead);
switch(cView.doc.location.pathname.split("/").pop()){
case "raw":
cView.addons.pr.then(function(){cView.Drawer.drawRaw(body)});
break;
case "accounts":
drawAcc();
break;
case "addons":
drawAddons();
break;
case "blocks":
drawBlocks();
break;
case "customui":
drawCustomUI();
break;
case "display":
default:
drawDisp();
}
cView.Common.setIcon("favicon.ico");
return cView.Utils._Promise.resolve();
function drawAcc(){
nodeSettingsHead.cNodes["sh-acc"].className = "sh-selected";
var nodeSettings = cView.gNodes["accaunts-settings"].cloneAll();
body.appendChild(nodeSettings);
Object.keys(cView.contexts).forEach(function (domain){
var context = cView.contexts[domain];
context.p.then(function(){
if (context.ids)context.ids.forEach(function(id){
nodeSettings
.cNodes["settings-profiles"]
.appendChild(cView.Drawer.genProfile(context.logins[id].data.users));
});
});
});
}
function drawAddons(){
nodeSettingsHead.cNodes["sh-addons"].className = "sh-selected";
cView.addons.pr.then(function(){
cView.addons.all.forEach(function(addon){
var node = addon.settings();
node.classList.add( "post");
body.appendChild(node);
});
});
}
function drawCustomUI(){
var customFunctions = require("./custom_functions.json");
nodeSettingsHead.cNodes["sh-custom-ui"].className = "sh-selected";
var nodeCtrl = cView.gNodes["custom-ui-settings-page"].cloneAll();
body.appendChild( nodeCtrl);
var host = cView.doc.getElementById("custom-ui-um-display")
var nodeSelect = cView.doc.getElementById("cu-um-function");
var chkBox = cView.doc.getElementById("use-upper");
chkBox.checked = JSON.parse (cView.localStorage.getItem(chkBox.value));
var usedFuncs = new Object();
try{
var scheme = JSON.parse(cView.localStorage.getItem("custom-ui-upper"));
scheme.forEach(function(item){
var nodeItem = cView.gNodes["custom-ui-item"].cloneAll();
var slots = cView.Utils.getInputsByName(nodeItem);
var funcId;
var text = "";
var i = null ;
var node;
Object.keys(item).forEach(function(key){
switch (key){
case "fn":
funcId = item[key];
break;
case "icon":
i = cView.doc.createElement("i");
i.className = "fa fa-2x fa-" + item[key];
slots["val"].value = item[key];
break;
case "text":
text = item[key];
slots["val"].value = item[key];
break;
}
});
if(funcId == "spacer"){
slots["type"].value = "spacer";
nodeItem.cNodes["title"].innerHTML = "•";
host.appendChild(nodeItem);
return;
}
slots["type"].value = funcId;
nodeItem.cNodes["title"].innerHTML = text;
if(i)nodeItem.cNodes["title"].appendChild(i);
nodeItem.title = funcId;
host.appendChild(nodeItem);
usedFuncs[funcId] = true;
});
}catch(e){};
Object.keys(customFunctions).forEach(function(funcId){
var nodeOption = cView.doc.createElement("option");
nodeOption.innerHTML = customFunctions[funcId].descr;
nodeOption.value = funcId;
if (usedFuncs[funcId] === true ) nodeOption.disabled = true;
nodeSelect.appendChild(nodeOption);
});
}
function drawBlocks(){
var lists = cView.blockLists;
nodeSettingsHead.cNodes["sh-blocks"].className = "sh-selected";
var nodeCtrl = cView.gNodes["blocks-settings-page-ctrl"].cloneAll();
cView.Utils.getInputsByName(nodeCtrl)["hideCups"].checked = JSON.parse(
cView.localStorage.getItem("addons-linkcups-hide")
);
body.appendChild( nodeCtrl);
Object.keys(cView.contexts).forEach(function (domain){
var context = cView.contexts[domain];
var page = cView.gNodes["blocks-settings-page"].cloneAll();
page.cNodes["title"].innerHTML = domain;
page.cNodes["domain"].value = domain;
cView.Utils.setChild(
page.cNodes["strings"]
,"content"
,cView.Drawer.genBlockStrPage(domain)
);
var appendUser = function(user){
page.getNode(["c","posts"],["c","content"]).appendChild(genBUser(user, "posts"));
};
Object.keys(lists).forEach(function(type){
var count = 0;
var list = cView.blocks[lists[type]][domain];
if(typeof list !== "undefined") Object.keys(list).forEach(function(id){
page.getNode(["c",type]).hidden = false;
var username;
if(list[id] === true){
var user = context.gUsers[id];
if (typeof user === "undefined"){
count++;
return;
}else username = user.username;
}else username = list[id];
var item = cView.gNodes["blocks-item"].cloneAll(true);
var inputs = cView.Utils.getInputsByName(item);
inputs["type"].value = type;
inputs["val"].value = id;
item.cNodes["title"].innerHTML = "@"+username;
page.getNode(["c",type],["c","content"]).appendChild(item);
});
if(count){
var span = cView.doc.createElement("span");
span.innerHTML = count + " unrecognized users";
page.getNode(["c",type],["c","content"]).appendChild(span);
}
});
body.appendChild(page);
});
cView.Common.updateBlockList();
}
function drawDisp(){
nodeSettingsHead.cNodes["sh-displ"].className = "sh-selected";
var nodeSettings = cView.gNodes["display-settings"].cloneAll();
body.appendChild(nodeSettings);
var mode = cView.localStorage.getItem("display_name");
if (mode == null) mode = "screen";
var theme = cView.localStorage.getItem("display_theme");
if (theme == null) theme = "expanded.css";
var nodes = nodeSettings.getElementsByTagName("input");
for(var idx = 0; idx < nodes.length; idx++){
var node = nodes[idx];
switch(node.type){
case "radio" :
if (( node.name == "display_name") &&(node.value == mode)
|| ( node.name == "display_theme") &&(node.value == theme))
node.checked = true;
else if(node.value == cView.localStorage.getItem(node.name))
node.checked = true;
break;
case "checkbox":
node.checked = JSON.parse (cView.localStorage.getItem(node.value));
break;
}
};
cView.doc.getElementById("rt-chkbox").checked = JSON.parse(cView.localStorage.getItem("rt"));
var bump = JSON.parse(cView.localStorage.getItem("rtbump"));
cView.doc.getElementById("rt-params").hidden = !bump;
cView.doc.getElementById("rt-bump").checked = bump ;
var oRTParams = cView.localStorage.getItem("rt_params");
if (oRTParams != null)
oRTParams = JSON.parse(oRTParams);
["rt-bump-int", "rt-bump-cd", "rt-bump-d"].forEach(function(id){
var node = cView.doc.getElementById(id);
if(oRTParams)node.value = oRTParams[id];
node.parentNode.getElementsByTagName("span")[0].innerHTML = node.value + " minutes";
});
}
}
,"drawSearch":function(search){
var cView = this.cView;
cView.doc.getElementById("container").cNodes["pagetitle"]
.innerHTML = "Search: " + search.query;
cView.doc.title ="Search: " + search.query;
var node = cView.gNodes["search-big"].cloneAll();
cView.Utils.setChild(node, "search-input", cView.gNodes["search-input"].cloneAll());
node.getElementsByTagName("form")[0].target = "_self";
Object.keys(cView.contexts).forEach(function(domain){
var el = cView.gNodes["search-domain"].cloneAll(true);
el.cNodes["i"].checked = (search.domains.indexOf(domain) != -1);
el.cNodes["i"].value = domain;
el.cNodes["s"].innerHTML = domain;
node.getElementsByClassName("search-domains")[0].appendChild(el);
});
cView.Utils.setChild(cView.doc.getElementById("container"), "details", node);
if(search.query == "")return;
cView.Utils.getInputsByName(node)["qs"].value = search.query ;
if(!cView.doc.getElementsByClassName("post").length){
var node = cView.gNodes["nothig-found"].cloneAll();
node.innerHTML += search.query;
cView.doc.posts.appendChild(node);
}else node.removeChild(node.cNodes["search-info"]);
}
,"genMore":function(isLast ){
var cView = this.cView;
var nodeMore = cView.doc.createElement("div");
nodeMore.className = "more-node";
var htmlPrefix = '<a href="' + gConfig.front+cView.fullPath + "?";
if( cView.search != "") htmlPrefix += cView.search+"&";
var htmlForward= "";
var htmlBackward = "";
//var fLastPage = (content.posts.length != cView.offset);
var backward = cView.skip*1 - gConfig.offset*1;
var forward = cView.skip*1 + gConfig.offset*1;
if (cView.skip){
if (backward>=0) htmlBackward = htmlPrefix + "offset="
+ backward*1+ "&limit="+gConfig.offset*1
+ '"><span style="font-size: 120%">←</span> Newer entries</a>';
nodeMore.innerHTML = htmlBackward ;
}
if(!isLast){
htmlForward = htmlPrefix + "offset="
+ forward*1 + "&limit="+gConfig.offset*1
+'">Older entries<span style="font-size: 120%">→</span></a>';
}
if ( (htmlBackward != "") && (htmlForward != "")) nodeMore.innerHTML += '<span class="spacer">—</span>'
nodeMore.innerHTML += htmlForward;
return nodeMore;
}
,"drawTimeline":function(posts,contexts){
var cView = this.cView;
var Drawer = cView.Drawer;
var body = cView.doc.getElementById("container");
var nodeMore = Drawer.genMore(!posts.length);
body.appendChild(nodeMore.cloneNode(true));
cView.doc.posts = cView.doc.createElement("div");
cView.doc.posts.className = "posts";
cView.doc.posts.id = "posts";
body.appendChild(cView.doc.posts);
cView.posts = new Array();
cView.doc.hiddenCount = 0;
var idx = 0;
posts.forEach(function(post){
var nodePost = null;
post.idx = idx++;
if (post.type == "metapost"){
var dups = post.dups.filter(function(post){
return post.isHidden != true;
});
if (dups.length == 1)
nodePost = Drawer.genPost(dups[0]);
else if(dups.length != 0)
nodePost = Drawer.makeMetapost( dups.map(Drawer.genPost, cView));
if (dups.length != post.dups.length) cView.doc.hiddenCount++;
}else if(post.isHidden) cView.doc.hiddenCount++;
else{
post.isHidden = false;
nodePost = Drawer.genPost(post);
}
if(nodePost)cView.doc.posts.appendChild(nodePost);
cView.posts.push({"hidden":post.isHidden,"data":post});
});
var nodeShowHidden = cView.gNodes["show-hidden"].cloneAll();
nodeShowHidden.cNodes["href"].action = true;
body.appendChild(nodeShowHidden);
if(cView.doc.hiddenCount) nodeShowHidden.cNodes["href"].innerHTML= "Show "+ cView.doc.hiddenCount + " hidden entries";
body.appendChild(nodeMore);
/*
var drop = Math.floor(cView.skip/3);
var toAdd = drop + Math.floor(gConfig.offset/3);
if((!gPrivTimeline.done)&& (cView.timeline == "home")&& matrix.ready){
gPrivTimeline.done = true;
new Promise(function (){addPosts(drop,toAdd,0);});
};
*/
}
,"drawPost": function(content,context) {
var cView = this.cView;
var singlePost = cView.Drawer.genPost(content);
var body = cView.doc.getElementById("container");
body.appendChild(singlePost);
var nodesHide = singlePost.getElementsByClassName("hide");
singlePost.hidden = false;
if (nodesHide.length)nodesHide[0].hidden = true;
cView.doc.title = "@"
+ context.gUsers[singlePost.rawData.createdBy].username + ": "
+ singlePost.rawData.body.slice(0,20).trim()
+ (singlePost.rawData.body.length > 20?"\u2026":"" )
+ " ("+ context.domain +")";
}
/*
var nodeRTCtrl = body.getElementsByClassName("rt-controls")[0];
nodeRTCtrl.cNodes["rt-chkbox"].checked = JSON.parse(cView.localStorage.getItem("rt"));
var nodeBump = nodeRTCtrl.cNodes["rt-bump"];
for(var idx = 0; idx<nodeBump.childNodes.length; idx++)
if(nodeBump.childNodes[idx].value == bump){
nodeBump.selectedIndex = idx;
break;
}
if(content.timelines) context.rtSub = {"timeline":[content.timelines.id]};
else context.rtSub = {"post":[content.posts.id]};
*/
,"drawRequests":function(){
var cView = this.cView;
var whoamis = new Array();
Object.keys(cView.contexts).forEach( function (domain){
var context = cView.contexts[domain];
context.ids.forEach(function(id){
whoamis.push(context.getWhoami(context.logins[id].token));
});
});
return cView.Utils._Promise.all(whoamis).then(function(){
var body = cView.doc.getElementById("container");
Object.keys(cView.contexts).forEach( function (domain){
genRequests(cView.contexts[domain]);
});
if (!body.getElementsByClassName("sub-request").length)
body.getElementsByClassName("pagetitle")[0].innerHTML = "No requests";
});
function genRequests(context){
var cView = context.cView;
var body = cView.doc.getElementById("container");
context.ids.forEach(function(loginId){
var login = context.logins[loginId].data;
if(!Array.isArray(login.requests)|| (login.requests.length == 0))
return;
var nodeH = cView.doc.createElement("h2");
nodeH.innerHTML = "@"+login.users.username+" requests";
body.appendChild(nodeH);
var nodeReqs = body.appendChild(cView.gNodes["req-body"].cloneAll());
login.requests.forEach( cView.Common.addUser, context);
login.requests.forEach(function(req){
var node = genReqNode(req, loginId);
if(req.src == loginId){
nodeReqs.cNodes["req-body-sent"].hidden = false;
node.cNodes["sr-ctrl"].hidden = true;
nodeReqs.cNodes["req-body-sent"].appendChild(node);
}else{
nodeReqs.cNodes["req-body-pend"].hidden = false;
nodeReqs.cNodes["req-body-pend"].appendChild(node);
}
});
});
function genReqNode(req, loginId){
var node = cView.gNodes["sub-request"].cloneAll();
var user = context.gUsers[req.id];
node.cNodes["sr-name"].innerHTML = user.link;
/*
'<a href="'
+gConfig.front + "as/"
+context.domain + "/"
+user.username + '">'
+user.screenName
+"</a>"
+" @" + user.username;
*/
if(req.type == "group")
node.cNodes["sr-name"].innerHTML += "<br />to "
+ context.gUsers[req.dest].link;
node.cNodes["sr-avatar"].src = user.profilePictureMediumUrl ;
node.cNodes["sr-user"].value = user.username;
node.cNodes["sr-id"].value = loginId;
node.cNodes["sr-src"].value = req.src;
node.cNodes["sr-dest"].value = req.dest;
node.cNodes["sr-reqid"].value = req.reqid;
node.cNodes["sr-type"].value = req.type;
node.cNodes["sr-domain"].value = context.domain;
return node;
}
}
}
,"drawGroups": function( ){
var cView = this.cView;
var out = cView.doc.createElement("div");
out.className = "subs-cont";
var domains = Object.keys(cView.contexts);
domains.forEach(function(domain){
var context = cView.contexts[domain];
if((context.gMe == null)
|| (typeof context.gMe.users.subscriptions === "undefined") )
return;
var subHead = cView.doc.createElement("h3");
subHead.innerHTML = domain;
out.appendChild(subHead);
var oSubscriptions = new Object();
context.gMe.subscriptions.forEach(function(sub){
oSubscriptions[sub.id] = sub;
});
var nodeGrps = cView.doc.createElement("div");
context.gMe.users.subscriptions.forEach(function(subid){
var sub = oSubscriptions[subid];
var user = context.gUsers[sub.user];
if((user.type == "user")||(sub.name != "Posts"))
return;
var node = cView.gNodes["sub-item"].cloneAll();
var a = node.cNodes["link"];
a.href = gConfig.front+ "as/" + context.domain+ "/" + user.username;
a.cNodes["usr-avatar"].src = user.profilePictureMediumUrl;
a.cNodes["usr-title"].innerHTML = user.title;
nodeGrps.appendChild(node);
});
out.appendChild(nodeGrps);
});
cView.doc.getElementById("container").appendChild(out);
return cView.Utils._Promise.resolve();
}
,"drawFriends": function(content,context){
var cView = context.cView;
var out = cView.gNodes["subs-cont"].cloneAll();
content.subscriptions.forEach(function(sub){
if(sub.name != "Posts")return;
var node = cView.gNodes["sub-item"].cloneAll();
var a = node.cNodes["link"];
var user = context.gUsers[sub.user];
a.href = gConfig.front+ "as/" + context.domain+ "/" + user.username;
a.cNodes["usr-avatar"].src = user.profilePictureMediumUrl;
a.cNodes["usr-title"].innerHTML = user.title;
if(user.type == "user")out.cNodes["sc-users"].appendChild(node);
else out.cNodes["sc-grps"].appendChild(node);
});
cView.doc.getElementById("container").appendChild(out);
}
,"drawSubs": function(content,context){
var cView = context.cView;
var out0 = cView.doc.createElement("div");
var out = cView.doc.createElement("div");
out0.appendChild(out);
out0.className = "subs-cont";
content.subscribers.forEach(function(sub){
var node = cView.gNodes["sub-item"].cloneAll();
var user = context.gUsers[sub.id];
var a = node.cNodes["link"];
a.href = gConfig.front+ "as/" + context.domain+ "/" + user.username;
a.cNodes["usr-avatar"].src = user.profilePictureMediumUrl;
a.cNodes["usr-title"].innerHTML = user.title;
out.appendChild(node);
});
cView.doc.getElementById("container").appendChild(out0);
}
,"genUserPopup": function(node, user){
var cView = this.cView;
var context = cView.contexts[user.domain];
var nodePopup = cView.gNodes["user-popup"].cloneAll(true);
cView.doc.getElementsByTagName("body")[0].appendChild(nodePopup);
nodePopup.id = "userPopup" + context.domain + user.id;
nodePopup.cNodes["up-avatar"].innerHTML = '<img src="'+ user.profilePictureMediumUrl+'" />';
nodePopup.cNodes["up-info"].innerHTML ="<span>@" + user.username + "</span><br>"+ user.link;
if((typeof context.gMe !== "undefined") && (context.ids.indexOf(user.id) == -1))
cView.Utils.setChild(nodePopup, "up-controls", cView.Drawer.genUpControls(user));
if (typeof node.createdAt !== "undefined"){
var spanDate = cView.doc.createElement("span");
spanDate.className = "up-date";
var txtdate = new Date(node.createdAt*1).toString();
spanDate.innerHTML = txtdate.slice(0, txtdate.indexOf("(")).trim();
nodePopup.appendChild(spanDate);
}
return nodePopup;
}
,"genUpControls":function(user){
var cView = this.cView;
var context = cView.contexts[user.domain];
var controls = cView.gNodes["up-controls"].cloneAll();
var subs = controls.cNodes["up-sbs"];
controls.user = user.username;
controls.domain = context.domain;
var isMulti = context.ids.length > 1;
context.ids.forEach(perLogin);
return controls;
function perLogin(id){
if (user.id == id)return;
var login = context.logins[id].data;
var friend = (typeof login.oFriends[user.id] !== "undefined");
var envelop = cView.gNodes["up-c-mu"].cloneAll();
envelop.loginId = id;
if (isMulti) envelop.cNodes["uname"].innerHTML = "@"+login.users.username+": ";
var nodeSub = envelop.cNodes["up-s"];
nodeSub.innerHTML = friend?"Unsubscribe":"Subscribe";
nodeSub.subscribed = friend;
if (!friend && (user.isPrivate == 1 )){
nodeSub.removeEventListener("click",cView["Actions"]["evtSubscribe"]);
var oRequests = new Object();
if (Array.isArray(login.requests)){
login.requests.forEach(function(req){
oRequests[req.id] = req;
});
}
if(Array.isArray(login.users.pendingSubscriptionRequests)
&&login.users.pendingSubscriptionRequests.some(function(a){
return oRequests[a].username == user.username;
})){
nodeSub = cView.Utils.setChild(envelop, "up-s", cView.doc.createElement("span"));
nodeSub.innerHTML = "Subscription request sent";
}else{
nodeSub.innerHTML = "Request subscription";
nodeSub.addEventListener("click", cView["Actions"]["reqSubscription"] );
}
}
controls.cNodes["up-sbs"].getElementsByTagName("ul")[0].appendChild(envelop);
if(friend
&& ((user.type == "group")
|| login.users.subscribers.some(function(sub){ return sub.id == user.id;}))){
envelop.cNodes["up-d"].href = gConfig.front + "filter/direct#"+ user.username;
envelop.cNodes["up-d"].target = "_blank";
}else{
envelop.cNodes["up-d"].hidden = true;
envelop.cNodes["up-d"].previousSibling.hidden = true;
}
var aBan = envelop.cNodes["up-b"];
/*if (user.type == "group"){
aBan.hidden = true;
envelop.cNodes["up-b"].previousSibling.hidden = true;
return;
}
*/
aBan.banned = login.users.banIds.indexOf( user.id) != -1;
if (aBan.banned){
aBan.innerHTML = "Un-ban";
aBan.removeEventListener("click",cView["Actions"]["genBlock"]);
aBan.addEventListener("click", cView["Actions"]["doUnBan"]);
}
}
}
,"regenHides":function(){
var cView = this.cView;
cView.posts.forEach(function(victim,idx){
victim.data.idx = idx;
});
}
,"updateDate":function(node, cView){
node.innerHTML = cView.Utils.relative_time(node.date);
var txtdate = new Date(node.date).toString();
node.title = txtdate.slice(0, txtdate.indexOf("(")).trim();
window.setTimeout(cView.Drawer.updateDate, 30000, node, cView);
}
,"genPost":function(post){
var cView = this.cView;
var Drawer = cView.Drawer;
if (post.isHidden !== true) post.isHidden = false;
var context = cView.contexts[post.domain];
var nodePost = cView.gNodes["post"].cloneAll();
var postNBody = nodePost.cNodes["post-body"];
var user = undefined;
if(post.createdBy) user = context.gUsers[post.createdBy];
nodePost.rtCtrl = new Object();
nodePost.homed = false;
nodePost.rawData = post;
nodePost.id = context.domain + "-post-" + post.id;
nodePost.isPrivate = false;
nodePost.commentsModerated = false;
if( typeof post.body === "string")
//postNBody.cNodes["post-cont"].innerHTML = context.digestText(post.body);
postNBody.cNodes["post-cont"][(cView.readMore?"words":"innerHTML")] = context.digestText(post.body);
var urlMatch ;
nodePost.hidden = cView.Common.chkBlocked(post);
nodePost.gotLock = false;
nodePost.gotShield = false;
if(typeof user !== "undefined"){
nodePost.cNodes["avatar"].cNodes["avatar-h"].innerHTML = '<img src="'+ user.profilePictureMediumUrl+'" />';
nodePost.cNodes["avatar"].cNodes["avatar-h"].userid = user.id;
postNBody.cNodes["title"].innerHTML = Drawer.genTitle(nodePost);
}
var nodeLock = postNBody.getNode(["c","post-info"],["c","post-controls"],["c","post-lock"]);
if(nodePost.gotLock)
nodeLock.innerHTML = "<i class='fa fa-lock icon'> </i>";
else if (nodePost.gotShield)
nodeLock.innerHTML = "<i class='fa fa-shield icon'> </i>";
if(nodePost.direct)
nodeLock.innerHTML += "<i class='fa fa fa-envelope icon'> </i>";
if(Array.isArray(post.attachments)&&post.attachments.length){
var attsNode = postNBody.cNodes["attachments"];
var bFirstImg = true;
post.attachments.forEach(function(att){
var nodeAtt = cView.doc.createElement("div");
var oAtt = context.gAttachments[att];
switch(oAtt.mediaType){
case "image":
var nodeA = cView.doc.createElement("a");
nodeA.target = "_blank";
nodeA.href = oAtt.url;
nodeA.border = "none";
if (typeof oAtt.imageSizes.t !== "undefined")
nodeAtt.t = oAtt.imageSizes.t;
else if(typeof oAtt.imageSizes.o !== "undefined")
nodeAtt.t = oAtt.imageSizes.o;
else nodeAtt.t = {"w":0};
var nodeImg = cView.doc.createElement("img");
/*
var showUnfolder = (post.src === "rt")?
cView.Actions.showUnfolderRt
:cView.Actions.showUnfolder;
*/
var showUnfolder = cView.Actions.showUnfolderRt;
nodeImg.style.height = 0;
nodeAtt.img = nodeImg;
nodeImg.addEventListener("load", showUnfolder);
if(bFirstImg){
nodeImg.src = oAtt.thumbnailUrl;
bFirstImg = false;
}else{
nodeAtt.url = oAtt.thumbnailUrl;
nodeAtt.hidden = true;
}
nodeA.appendChild(nodeImg);
nodeAtt.appendChild(nodeA);
attsNode.cNodes["atts-img"].appendChild(nodeAtt);
nodeAtt.className = "att-img";
break;
case "audio":
nodeAtt.innerHTML = '<audio style="height:40" preload="none" controls><source src="'+oAtt.url+'" ></audio> <br><a href="'+oAtt.url+'" target="_blank" ><i class="fa fa-download"></i> '+oAtt.fileName+'</a>';
nodeAtt.className = "att-audio";
attsNode.cNodes["atts-audio"].appendChild(nodeAtt);
break;
default:
nodeAtt.innerHTML = '<a href="'+oAtt.url+'" target="_blank" ><i class="fa fa-download"></i> '+oAtt.fileName+'</a>';
attsNode.appendChild(nodeAtt);
}
});
}else
if(((urlMatch = post.body.match(/(^|[^!])https?:\/\/[^\s\/$.?#].[^\s]*/i) )!= null)
&&(JSON.parse(cView.localStorage.getItem("show_link_preview")))){
cView.gEmbed.p.then(function(oEmbedPr){
Drawer.embedPreview(oEmbedPr
,urlMatch[0]
,postNBody.cNodes["attachments"]
//);
).then((post.src == "rt")?cView.Utils.unscroll:function(){});
});
}
var anchorDate = cView.doc.createElement("a");
if(typeof user !== "undefined") anchorDate.href = [gConfig.front + "as", context.domain, user.username , post.id].join("/");
postNBody.cNodes["post-info"].cNodes["post-controls"].cNodes["post-date"].appendChild(anchorDate);
anchorDate.date = JSON.parse(post.createdAt);
window.setTimeout(Drawer.updateDate, 10,anchorDate, cView);
if((typeof post.commentsDisabled !== "undefined")
&& (post.commentsDisabled == "1")){
postNBody.getNode(["c","post-info"],["c","post-controls"],["c","cmts-lock-msg"]).hidden = false;
} else post.commentsDisabled = "0";
if(context.ids.length){
var nodeControls;
if (context.ids.indexOf(post.createdBy) != -1){
nodeControls = cView.gNodes["controls-self"].cloneAll();
}else {
nodeControls = cView.gNodes["controls-others"].cloneAll();
postNBody.cNodes["post-info"].nodeLike = nodeControls.cNodes["post-control-like"];
nodeControls.cNodes["post-control-like"].action = true;
if(post.commentsDisabled == "1"){
var nodeCmtControls = nodeControls.getElementsByClassName("cmts-add");
for(var idx = 0; idx < nodeCmtControls.length; idx++){
nodeCmtControls[idx].style.display = "none";
nodeCmtControls[idx].nextSibling.style.display = "none";
}
}
}
nodeControls.className = "controls";
var aHide = nodeControls.cNodes["hide"];
//aHide.className = "hide";
aHide.innerHTML = post.isHidden?"Un-hide":"Hide";
aHide.action = !post.isHidden;
postNBody.cNodes["post-info"].cNodes["post-controls"].appendChild( nodeControls);
postNBody.cNodes["post-info"].cNodes["post-controls"].cNodes["controls"] = nodeControls;
//postNBody.cNodes["post-info"].cNodes["post-controls"].nodeHide = aHide;
}
if (post.likes) Drawer.genLikes(nodePost );
if (post.comments){
if(post.omittedComments){
if(post.comments[0])
postNBody.cNodes["comments"].appendChild(Drawer.genComment.call(context, context.gComments[post.comments[0]]));
var nodeLoad = cView.gNodes["comments-load"].cloneAll();
nodeLoad.getElementsByClassName("num")[0].innerHTML = post.omittedComments;
postNBody.cNodes["comments"].appendChild(nodeLoad);
if(post.comments[1])
postNBody.cNodes["comments"].appendChild(Drawer.genComment.call(context, context.gComments[post.comments[1]]));
}
else post.comments.forEach(function(commentId){
postNBody.cNodes["comments"]
.appendChild(Drawer.genComment.call(context, context.gComments[commentId]))
});
}
if (postNBody.cNodes["comments"].childNodes.length > 4)
postNBody.cNodes["many-cmts-ctrl"].hidden = false;
return nodePost;
}
,"genTitle":function(nodePost){
var cView = this.cView;
var domain = nodePost.rawData.domain;
var context = cView.contexts[domain];
var post = nodePost.rawData;
var user = context.gUsers[post.createdBy];
var title = "<span><a href='//"+ [gConfig.domains[domain].front, user.username, post.id].join("/")
+ "'><img src='"+gConfig.static + domain + ".ico' /></a></span> "+user.link;
//if(nodePost.isPrivate) title += "<span> posted a secret to "+StringView.makeFromBase64(matrix.gSymKeys[cpost.payload.feed].name)+"</span>";
nodePost.gotLock = true;
nodePost.gotShield = true;
if(false);
else if(post.postedTo){
post.postedTo.forEach(function(id){
nodePost.gotLock &= context.gFeeds[id].isPrivate;
nodePost.gotShield &= context.gFeeds[id].isProtected;
nodePost.direct = context.gFeeds[id].direct;
});
if ((post.postedTo.length >1)||(context.gFeeds[post.postedTo[0]].user.id!=user.id)){
title += "<span> posted to: </span>";
post.postedTo.forEach(function(id){
title += context.gFeeds[id].user.link;
});
}
}
if(post.isDirect == true)
nodePost.direct = true;
return title;
}
,"embedPreview": function (oEmbedPrs, victim, target){
var cView = this.cView;
var oEmbedURL;
var m;
var fake = {"then":function(){}};
var blacklist = gConfig.domains["FreeFeed"].fronts;
if(blacklist.some(function(item){return victim.indexOf(item)!= -1;})) return fake;
if((m = /^https:\/\/(?:docs\.google\.com\/(?:document|spreadsheets|presentation|drawings)|drive\.google\.com\/file)\/d\/([^\/]+)/.exec(victim)) !== null) {
return new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.onload = function(){
if(oReq.status < 400)
resolve(JSON.parse(oReq.response));
else reject(oReq.response);
}
oReq.open("get","https://www.googleapis.com/drive/v2/files/" + m[1] + "?key=AIzaSyA8TI6x9A8VdqKEGFSE42zSexn5HtUkaT8",true);
oReq.send();
}).then(function(info){
//var nodeiFrame = cView.doc.createElement("iframe");
//nodeiFrame.src = info.embedLink;
var nodeA = cView.doc.createElement("a");
var img = cView.doc.createElement("img");
var width = cView.doc.getElementById("container").clientWidth*3/4;
img.src = info.thumbnailLink.replace("=s220","=w"+ width+"-c-h"+ width/5 );// "=s"+cView.doc.getElementById("container").clientWidth/2+"-p");
var node = cView.doc.createElement("div");
node.className = "att-img";
nodeA.appendChild(img);
nodeA.href = victim;
node.appendChild(nodeA);
target.appendChild(node);
img.onerror=function(){nodeA.hidden = true;};
return node;
});
}else if (/^https?:\/\/(www\.)?pinterest.com\/pin\/.*/.exec(victim) !== null){
var node = cView.doc.createElement("div");
node.className = "att-img";
node.innerHTML = '<a data-pin-do="embedPin" href="' + victim + '"></a>';
target.appendChild(node);
return Promise.resolve(node);
}
var bIsOEmbed = oEmbedPrs.some(function(o){
return o.endpoints.some(function(endp){
if(!endp.schemes)console.log(endp.url)
else if (endp.schemes.some(function (scheme){
return victim.match(scheme) != null; })){
oEmbedURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D'"
+ encodeURIComponent(endp.url
+ "?url=" + victim
+ "&format=json"
+ "&maxwidth="+cView.doc.getElementById("container").clientWidth*3/4
)
+ "'&format=json";
return true;
}else return false;
});
});
if(bIsOEmbed){
return new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.onload = function(){
if(oReq.status < 400)
resolve(JSON.parse(oReq.response));
else reject(oReq.response);
}
oReq.open("get",oEmbedURL,true);
oReq.send();
}).then(function(qoEmbed){
if (!qoEmbed.query.count) return null;
var oEmbed = qoEmbed.query.results.json;
if(oEmbed.type == "photo"){
return target.appendChild(oEmbedImg(oEmbed.url,victim));
}else if (typeof oEmbed.html !== "undefined"){
if(oEmbed.html.indexOf("iframe") == 1){
var node = cView.doc.createElement("div");
node.innerHTML = oEmbed.html;
return target.appendChild(node);
}else if(typeof oEmbed.thumbnail_url !== "undefined"){
return target.appendChild(oEmbedImg(oEmbed.thumbnail_url,victim));
}else{
var iframe = cView.doc.createElement("iframe");
iframe.sandbox = true;
iframe.srcdoc = oEmbed.html;
iframe.style.width = oEmbed.width;
iframe.style.height = oEmbed.height;
return target.appendChild(iframe);
}
}
},doEmbedly );
}else return doEmbedly();
function oEmbedImg(url,victim){
if(!url.match(/^['"]?https?/)) return cView.doc.createElement("img");
var img = cView.doc.createElement("img");
img.src = url;
//img.style.width = oEmbed.width;
//img.style.height = oEmbed.height;
var node = cView.doc.createElement("a");
node.appendChild(img);
return node;
}
function doEmbedly(){
var aEmbed = cView.doc.createElement("a");
aEmbed.href = victim;
aEmbed.className = "embedly-card";
target.appendChild(aEmbed);
return fake;
}
}
,"genEditNode":function(post,cancel){
var cView = this.cView;
var nodeEdit = cView.gNodes["edit"].cloneAll();
nodeEdit.cNodes["edit-buttons"].cNodes["edit-buttons-post"].addEventListener("click",post);
nodeEdit.cNodes["edit-buttons"].cNodes["edit-buttons-cancel"].addEventListener("click",cancel);
cView.cTxt = nodeEdit.cNodes["edit-txt-area"];
return nodeEdit;
}
,"genComment":function(comment){
var cView = this.cView;
var context = this;
var nodeComment = cView.gNodes["comment"].cloneAll();
var listBlocksUsr = cView.blocks.blockComments[context.domain];
var listBlocksStr = cView.blocks.blockStrings[context.domain];
var cUser = context.gUsers[comment.createdBy];
if(( typeof listBlocksUsr!== "undefined")
&& (typeof cUser !== "undefined")
&& ( listBlocksUsr!= null)
&& (listBlocksUsr[cUser.id])){
nodeComment.innerHTML = "---";
nodeComment.hidden = true;
return nodeComment;
}
if(( typeof listBlocksStr!== "undefined")
&& ( listBlocksStr!= null)
&& (listBlocksStr.some(function(str){
return comment.body.toLowerCase().indexOf(str.toLowerCase())!= -1;
}))){
nodeComment.innerHTML = "---";
nodeComment.hidden = true;
return nodeComment;
}
var nodeSpan = nodeComment.getNode(["c","comment-body"],["c","cmt-content"]);
nodeComment.userid = null;
if( typeof comment.body === "string")
nodeSpan[(cView.readMore?"words":"innerHTML")] = context.digestText(comment.body);
nodeComment.id = context.domain + "-cmt-" + comment.id;
nodeComment.rawId = comment.id;
nodeComment.domain = context.domain;
nodeComment.createdAt = comment.createdAt;
if(typeof cUser === "undefined")
return nodeComment;
nodeComment.userid = cUser.id;
nodeComment.getNode(["c","comment-body"],["c","cmt-author"]).innerHTML = cUser.link ;
if(context.ids.length){
if(context.ids.indexOf(cUser.id) != -1)
cView.Utils.setChild(nodeComment.cNodes["comment-body"],"comment-controls",cView.gNodes["comment-controls"].cloneAll());
else if(!cUser.friend) nodeComment.cNodes["comment-date"].cNodes["date"].style.color = "#787878";
}
return nodeComment;
}
,"genDirectTo":function(victim, login){
var cView = this.cView;
var context = cView.contexts[login.domain];
var nodeDirectTo = cView.gNodes["new-direct-to"].cloneAll();
nodeDirectTo.userid = login.users.id;
nodeDirectTo.domain = login.domain;
if( Object.keys(cView.contexts).reduce(
function(prev,domain){ return prev.concat(cView.contexts[domain].ids);}
,[]
).length > 1 ){
nodeDirectTo.cNodes["mu-login"].innerHTML = context.domain + ": @" + login.users.username;
nodeDirectTo.cNodes["mu-login"].hidden = false;
victim.cNodes["add-sender"].hidden = false;
if (typeof victim.cNodes["add-sender"].ids === "undefined")
victim.cNodes["add-sender"].ids = [context.gMe.users.id];
}
victim.cNodes["post-to"].appendChild(nodeDirectTo);
nodeDirectTo.destType = "directs";
nodeDirectTo.className = "new-post-to";
nodeDirectTo.feeds = new Array();
victim.cNodes["edit-buttons"].cNodes["edit-buttons-post"].removeEventListener("click", cView["Actions"]["newPost"]);
victim.cNodes["edit-buttons"].cNodes["edit-buttons-post"].addEventListener("click", cView["Actions"]["postDirect"]);
victim.cNodes["edit-buttons"].cNodes["edit-buttons-post"].disabled = true;
var hash;
if((cView.fullPath.indexOf("#") != -1)
&& ((hash = cView.fullPath.substr(cView.fullPath.indexOf("#")+1)) != "")){
victim.cNodes["edit-buttons"].cNodes["edit-buttons-post"].disabled = false;
nodeDirectTo.getNode(["c","new-feed-input"],["c","input"]).value = hash;
}
var oSuggest = new Object();
var oDest = new Object();
if ((typeof login.users.subscribers !== "undefined") && (typeof login.users.subscriptions !== "undefined")){
for (var username in context.gUsers.byName){
var userid = context.gUsers.byName[username].id;
if (!login.oFriends[userid]
|| !(login.users.subscribers.some(function(sub){return sub.id == userid;})
|| (context.gUsers.byName[username].type == "group")
)
) continue;
oDest[username] = username;
var pos = oSuggest;
for(var idx = 0; idx < username.length; idx++){
if (typeof pos[username.charAt(idx)] === "undefined")
pos[username.charAt(idx)] = new Object();
pos = pos[username.charAt(idx)];
if (typeof pos.arr === "undefined") pos.arr = new Array();
pos.arr.push(username);
}
}
}
var input = nodeDirectTo.getNode(["c","new-feed-input"],["c","input"]);
input.dest = oDest;
input.suggest = oSuggest;
cView.updPostTo = function (login,clean){
if(clean == true) {
document.getElementsByClassName("add-sender")[0].ids = new Array();
var victims = document.getElementsByClassName("new-post-to");
while(victims.length)victims[0].parentNode.removeChild(victims[0]);
}
return cView.Drawer.genDirectTo(victim, login);
};
var rmSenders = victim.getElementsByClassName("rm-sender");
if(rmSenders.length > 1)
for (idx = 0; idx < rmSenders.length; idx++)rmSenders[idx].hidden = false;
victim.getNode(["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"genPostTo":function(victim, init, login){
var cView = this.cView;
var context = cView.contexts[login.domain];
var nodePostTo = cView.gNodes["new-post-to"].cloneAll();
var idx = 1;
init = ( init ? init : login.users.username )
var arrDest = (Array.isArray(init)?init:[init]);
if( Object.keys(cView.contexts).reduce(
function(prev,domain){ return prev.concat(cView.contexts[domain].ids);}
,[]
).length > 1 ){
nodePostTo.cNodes["mu-login"].innerHTML = login.domain + ": @" + login.users.username;
nodePostTo.cNodes["mu-login"].hidden = false;
victim.cNodes["add-sender"].hidden = false;
if (typeof victim.cNodes["add-sender"].ids === "undefined")
victim.cNodes["add-sender"].ids = [context.domain + "-"+ context.gMe.users.id];
}
victim.cNodes["post-to"].appendChild(nodePostTo);
nodePostTo.feeds = new Array();
arrDest.forEach(function(dest){
nodePostTo.feeds.push(dest);
var destButton = cView.gNodes["new-post-feed"].cloneAll();
destButton.oValue = dest;
if(dest != login.users.username)
destButton.innerHTML = dest;
else destButton.innerHTML = "My feed";
nodePostTo.cNodes["new-post-feeds"].appendChild(destButton);
});
nodePostTo.destType = "posts";
nodePostTo.parentNode.isPrivate = false;
nodePostTo.cNodes["new-feed-input"].addEventListener("focus", cView.Actions.newDirectInp, true);
var oDest = new Object();
var oSuggest = new Object();
if (typeof login.users.subscriptions !== "undefined"){
var oSubscriptions = new Object();
login.subscriptions.forEach(function(sub){if (sub.name == "Posts")oSubscriptions[sub.id] = sub; });
login.users.subscriptions.forEach(function(subid){
if (typeof oSubscriptions[subid] === "undefined") return;
var sub = context.gUsers[oSubscriptions[subid].user];
if((typeof sub !=="undefined") && (sub.type == "group")){
var title = sub.title.replace(/<(?:.|\n)*?>/gm, '').trim();
oDest[sub.username] = sub.username;
oDest[sub.screenName] = sub.username;
oDest[title] = sub.username;
[sub.username, sub.screenName].forEach(function(name){
var pos = oSuggest;
var nameLC = name.toLocaleLowerCase();
for(var idx = 0; idx < nameLC.length; idx++){
if (typeof pos[nameLC.charAt(idx)] === "undefined")
pos[nameLC.charAt(idx)] = new Object();
pos = pos[nameLC.charAt(idx)];
//if(idx == 0) continue;
if (typeof pos.arr === "undefined")
pos.arr = new Array();
if(pos.arr.indexOf(title)== -1)
pos.arr.push(title);
}
});
}
});
};
/*
groups.label = "Private groups";
for (var id in matrix.gSymKeys){
option = cView.doc.createElement("option");
option.value = id;
option.privateFeed = true;
option.innerHTML = StringView.makeFromBase64(matrix.gSymKeys[id].name);
groups.appendChild(option);
}
*/
var input = nodePostTo.getNode(["c","new-feed-input"],["c","input"]);
input.suggest = oSuggest;
input.dest = oDest;
cView.updPostTo = function (login,clean,_init){
if(clean == true) {
document.getElementsByClassName("add-sender")[0].ids = new Array();
var victims = document.getElementsByClassName("new-post-to");
while(victims.length)victims[0].parentNode.removeChild(victims[0]);
}
if(typeof _init === "undefined")
return cView.Drawer.genPostTo(victim, init,login);
return cView.Drawer.genPostTo(victim, _init,login);
};
var rmSenders = victim.getElementsByClassName("rm-sender");
if(rmSenders.length > 1)
for (idx = 0; idx < rmSenders.length; idx++)rmSenders[idx].hidden = false;
nodePostTo.userid = login.users.id;
nodePostTo.domain = login.domain;
victim.getNode(["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"blockPosts":function(node, action){
var cView = this.cView;
var context = cView.contexts[node.domain];
var user = context.gUsers.byName[node.user];
var nodesPosts = cView.doc.getElementsByClassName("post");
for(var idx = 0; idx < nodesPosts.length; idx++){
if((nodesPosts[idx].rawData.createdBy == user.id)
&& (nodesPosts[idx].rawData.domain == user.domain)){
nodesPosts[idx].hidden = action;
if (!action)cView.Drawer.applyReadMore(nodesPosts[idx]);
}
}
}
,"blockComments":function(node, action){
var cView = this.cView;
var context = cView.contexts[node.domain];
var user = context.gUsers.byName[node.user];
var nodesCmts = cView.doc.getElementsByClassName("comment");
for(var idx = 0; idx < nodesCmts.length; idx++){
if((nodesCmts[idx].userid == user.id)
&& (nodesCmts[idx].domain == user.domain)) {
if(action) {
nodesCmts[idx].innerHTML = "---";
nodesCmts[idx].hidden = true;
}
else{
var id = nodesCmts[idx].rawId;
var nodeNewCmt = cView.Drawer.genComment.call( context
,context.gComments[id]
);
nodesCmts[idx].parentNode.replaceChild( nodeNewCmt , nodesCmts[idx]);
cView.Drawer.applyReadMore(nodeNewCmt);
}
}
}
}
,"genMultiuser":function(ok, cancle){
/* context not implemented
var popup = cView.gNode["multiuser-dialog"].cloneAll();
cView.cView.ids.forEach(function(id){
var unit = cView.gNode["multiuser-unit"].cloneAll();
unit.getElementsByTagName("span")[0].innerHTML = "@"+
cView.logins[id].data.users.username;
unit.getElementsByTagName("button")[0].addEventListener("click",ok);
unit.getElementsByTagName("a")[0].addEventListener("click",cancle);
unit.getElementsByTagName("input")[0].value = id;
popup.cNodes["units"].appendChild(unit);
});
return popup;
*/
}
,"genAddSender":function(cb){
var cView = this.cView;
var popup = cView.gNodes["add-sender-dialog"].cloneAll();
Object.keys(cView.contexts).forEach(function (domain){
var context = cView.contexts[domain];
var title = document.createElement("p");
title.innerHTML = domain;
popup.cNodes["units"].appendChild(title);
context.ids.forEach(function(id){
var login = context.logins[id].data;
var unit = cView.gNodes["add-sender-unit"].cloneAll();
unit.getNode(["c","up-avatar"],["c","avatar-img"]).src = login.users.profilePictureMediumUrl;
unit.getNode(["c","asu-info"],["c","username"]).innerHTML = "@" + login.users.username;
unit.getNode(["c","asu-info"],["c","screen-name"]).innerHTML = login.users.untagScreenName;
unit.addEventListener("click", function(){cb(login,context)});
popup.cNodes["units"].appendChild(unit);
});
});
return popup;
}
,"genAddComment": function(context){
var cView = context.cView;
var nodeComment = cView.gNodes["comment"].cloneAll();
cView.Utils.setChild(nodeComment, "comment-body", cView.Drawer.genEditNode(cView.Actions.postNewComment,cView.Actions.cancelNewComment));
if(context.ids.length > 1 ){
nodeComment.getElementsByClassName("select-user")[0].hidden = false;
var nodeSelectUsr = nodeComment.getElementsByClassName("select-user-ctrl")[0];
context.ids.forEach(function(id){
var option = document.createElement("option");
option.innerHTML = "@"+context.logins[id].data.users.username;
option.value = id;
nodeSelectUsr.appendChild(option);
if(context.logins[id].token == context.token) option.selected = true;
});
}
nodeComment.userid = context.gMe.users.id;
return nodeComment;
}
,"updateReqs":function(){
var cView = this.cView;
cView.subReqsCount = 0;
Object.keys(cView.contexts).forEach(function(domain){
var context = cView.contexts[domain];
var ids = context.ids;
if(ids) cView.subReqsCount += ids.reduce(function(total, id){
var profile = context.logins[id].data.users;
if (Array.isArray(profile.subscriptionRequests))
return total + profile.subscriptionRequests.length;
else return total;
},0);
});
if (cView.subReqsCount){
var nodeInfo = cView.doc.getElementById("sr-info");
nodeInfo.cNodes["sr-info-a"].innerHTML = "You have "
+ cView.subReqsCount
+ " subscription requests to review.";
nodeInfo.hidden = false;
}
}
,"makeMetapost": function(dups){
var cView = this.cView;
var nodeRefMenu = document.createElement("div");
var nodeMetapost = document.createElement("div");
nodeMetapost.className = "metapost";
var score = new Array(dups.length);
var nodeMenu = document.createElement("div");
nodeMenu.className = "post-refl-menu";
nodeMetapost.appendChild(nodeMenu);
dups.forEach(function(nodePost){
nodePost.hidden = true;
nodeMetapost.appendChild(nodePost);
nodeMenu.appendChild( genMenuItem(nodePost.rawData));
score.push({
"s":cView.Common.calcPostScore(nodePost.rawData)
,"node": nodePost
});
});
score.sort(function(a,b){return b.s - a.s;});
nodeMetapost.rtCtrl = score[0].node.rtCtrl;
score[0].node.hidden = false;
var items = nodeMenu.getElementsByClassName("reflect-menu-item");
for (var idx = 0; idx < items.length; idx++ )
if(items[idx].cNodes["victim-id"].value === score[0].node.id)
items[idx].className += " pr-selected";
else items[idx].className += " pr-deselected";
nodeMetapost.rawData = new Object();
return nodeMetapost;
function genMenuItem(post){
var context = cView.contexts[post.domain];
var node = cView.gNodes["reflect-menu-item"].cloneAll();
node.cNodes["label"].innerHTML = post.domain
+ ": @" + context.gUsers[post.createdBy].username;
node.cNodes["victim-id"].value = context.domain + "-post-" + post.id;;
return node;
}
}
,"regenMetapost":function (host){
var cView = this.cView;
var nodes = host.getElementsByClassName("post");
var count = nodes.length;
if (count){
var newNode;
if(count > 1){
var arrNodes = new Array();
for(var idx = 0; idx < count; idx++)
arrNodes.push(nodes[idx]);
newNode = cView.Drawer.makeMetapost(arrNodes);
}else{
newNode = nodes[0];
newNode.hidden = false;
cView.Drawer.applyReadMore(newNode);
}
host.parentNode.replaceChild( newNode, host);
}else host.parentNode.removeChild(host);
return count;
}
,"applyReadMore": function(host, flag){
var cView = this.cView;
var lines = (flag === false)?0:cView.readMoreHeight;
var dummy = cView.gNodes["one-line"].cloneAll();
document.body.appendChild(dummy);
var lineHeight = dummy.offsetHeight;
var height = lineHeight* lines;
document.body.removeChild(dummy);
var nodes = ((typeof host.classList !=="undefined")
&& host.classList.contains("long-text"))?
[host]:host.getElementsByClassName("long-text");
for(var idx = 0; idx<nodes.length; idx++)
if(Array.isArray(nodes[idx].words))
makeReadMore(nodes[idx],height,nodes[idx].words );
function makeReadMore(node, height, words){
var high = words.length - 1;
var low = 0;
if((node.offsetTop == 0) || (node.innerHTML != "")) return;
if(node.isUnfolded == false) return;
if (typeof node.isUnfolded === "undefined" ) node.isUnfolded = false;
node.innerHTML = words.join(" ");
if((node.offsetHeight < (height + lineHeight))||!height||node.isUnfolded ) return;
var wrapper = cView.gNodes["read-more-wrapper"].cloneAll();
cView.Utils.setChild(node.parentNode, node.classList[0], wrapper);
cView.Utils.setChild(wrapper, "content", node);
var idx;
do{
idx = Math.ceil((high+low)/2);
node.innerHTML = words
.slice(0,idx+1)
.join(" ");
if(wrapper.offsetHeight < height) low = idx;
else if (wrapper.offsetHeight > height)high = idx;
else break;
}while((high - low) > 1);
var cHeight = wrapper.offsetHeight;
var inc = cHeight > height?-1:1;
while(wrapper.offsetHeight == cHeight){
idx += inc;
node.innerHTML = words
.slice(0,idx)
.join(" ");
}
node.innerHTML = words
.slice(0,idx-1)
.join(" ");
}
var unamesHC = host.getElementsByClassName("url2link-uname");
for(var idx = 0; idx < unamesHC.length; idx++){
unamesHC[idx].addEventListener(
"mouseover"
,cView.Actions.toggleHighlightCmts
);
unamesHC[idx].addEventListener(
"mouseout"
,cView.Actions.toggleHighlightCmts
);
}
}
,"makeErrorMsg":function(err,host){
var cView = this.cView;
var node ;
if (typeof host.cNodes === "undefined" ) host.cNodes = new Object();
if (typeof host.cNodes["msg-error"] !== "undefined")
node = host.cNodes["msg-error"] ;
else {
node = cView.doc.createElement("div");
node.className = "msg-error";
host.cNodes["msg-error"] = node;
host.appendChild(node);
}
node.hidden = false;
var msg;
try{msg = JSON.parse(err.data).err;}
catch(e){msg = err.data;}
node.innerHTML = err.code?("Error #"+err.code+": "+msg):"Looks like a network error";
}
,"genBlockStrPage":function(domain){
var cView = this.cView;
var blockStrings = cView.blocks.blockStrings[domain]
var page = cView.doc.createElement("div");
if(Array.isArray(blockStrings))blockStrings.forEach(function(str){
var item = cView.gNodes["blocks-item"].cloneAll(true);
var inputs = cView.Utils.getInputsByName(item);
inputs["type"].value = "str";
inputs["val"].value = str;
item.cNodes["title"].innerHTML = str;
page.appendChild(item);
});
return page;
}
,"drawRaw": function (output){
var cView = this.cView;
var settingsNames = require("./settings.json");
cView.doc.location.search.substr(1).split("&").forEach(function(item){
item = decodeURIComponent(item).split("=");
if ((item.length != 2) || (settingsNames.indexOf(item[0]) == -1)) return;
cView.localStorage.setItem(item[0], item[1]);
});
var node = cView.doc.createElement("div");
output.appendChild(node);
node.style["font-family"] = "monospace";
settingsNames.forEach(function(name){
node.innerHTML += name + "=" + cView.localStorage.getItem(name) + "<br />";
});
}
,"genCustomUI": function(scheme){
var cView = this.cView;
var customFunctions = require("./custom_functions.json");
var host = cView.doc.createElement("div");
scheme.forEach(function(item){
var funcId;
var text = "";
var i = null ;
var node;
Object.keys(item).forEach(function(key){
switch (key){
case "fn":
funcId = item[key];
break;
case "icon":
i = cView.doc.createElement("i");
i.className = "fa fa-2x fa-" + item[key];
break;
case "text":
text = item[key];
break;
}
});
if(funcId == "spacer"){
node = cView.doc.createElement("span");
node.innerHTML = "•";
}else{
node = cView.doc.createElement("a");
node.innerHTML = text;
node.title = customFunctions[funcId].descr;
if (i) node.appendChild(i);
var action = customFunctions[funcId].action;
node.addEventListener("mousedown",cView[action[0]][action[1]]);
if(Array.isArray(customFunctions[funcId].cl))
customFunctions[funcId].cl.forEach(function(name){
node.classList.add(name);
});
}
host.appendChild(node);
});
host.className = "controls-login";
return host;
}
,"drawNotifications":function(input, isLast){
var cView = this.cView;
var head = cView.gNodes["notifications-filters"].cloneAll();
var filter = cView.search.match(/filter=(\w+)/);
var victim;
if (filter) victim = head.cNodes["not-"+filter[1]];
else victim = head.cNodes["not-All"];
victim.classList.add("sh-selected");
victim.classList.remove("sh-item");
cView.doc.getElementById("container").appendChild(head);
var nodeMore = cView.Drawer.genMore(isLast);
cView.doc.getElementById("container").appendChild(nodeMore.cloneNode(true));
var ntfTemplates = new Object();
cView.Common.genNodes(require("./notifications.json")).forEach(function(node){
ntfTemplates[node.classList[0]] = node;
});
input.forEach(function(notifications){
var context = notifications.context;
var out = cView.doc.createElement("div");
out.className = "subs-cont";
out.classList.add("notifications-container");
var subHead = cView.doc.createElement("h3");
subHead.innerHTML = context.domain;
out.appendChild(subHead);
notifications.forEach(function(oNtf){
var nodeNtf = ntfTemplates[oNtf.event_type].cloneAll();
Object.keys(nodeNtf.cNodes).forEach(function(key){
var victim = nodeNtf.cNodes[key];
var suffix = "";
if(oNtf[key])switch(key){
case "created_user_id":
case "affected_user_id":
case "group_id":
victim.innerHTML = context.gUsers[oNtf[key]].link;
break;
case "comment_id":
suffix = "#"+context.domain+"-cmt-"+oNtf.comment_id;
case "post_id":
victim.href = [
gConfig.front + "as"
, context.domain
, context.gUsers[ oNtf.group_ip || oNtf.created_user_id].username
,oNtf.post_id
].join("/") + suffix ;
break;
default:
}
});
nodeNtf.cNodes.date.date = oNtf.date;
window.setTimeout(cView.Drawer.updateDate, 10,nodeNtf.cNodes.date, cView);
out.appendChild(nodeNtf);
});
if (notifications.length)
cView.doc.getElementById("container").appendChild(out);
});
cView.doc.getElementById("container").appendChild(nodeMore);
return cView.Utils._Promise.resolve();
}
,"drawSummary":function(posts,contexts, interval){
var cView = this.cView;
var Drawer = cView.Drawer;
var body = cView.doc.getElementById("container");
var head = cView.gNodes["summary-type"].cloneAll();
var victim = head.cNodes["summ-"+interval];
victim.classList.add("sh-selected");
victim.classList.remove("sh-item");
cView.doc.getElementById("container").appendChild(head);
cView.doc.posts = cView.doc.createElement("div");
cView.doc.posts.className = "posts";
cView.doc.posts.id = "posts";
body.appendChild(cView.doc.posts);
cView.posts = new Array();
cView.doc.hiddenCount = 0;
var idx = 0;
posts.forEach(function(post){
var nodePost = null;
post.idx = idx++;
if (post.type == "metapost"){
var dups = post.dups.filter(function(post){
return post.isHidden != true;
});
if (dups.length == 1)
nodePost = Drawer.genPost(dups[0]);
else if(dups.length != 0)
nodePost = Drawer.makeMetapost( dups.map(Drawer.genPost, cView));
if (dups.length != post.dups.length) cView.doc.hiddenCount++;
}else if(post.isHidden) cView.doc.hiddenCount++;
else{
post.isHidden = false;
nodePost = Drawer.genPost(post);
}
if(nodePost)cView.doc.posts.appendChild(nodePost);
cView.posts.push({"hidden":post.isHidden,"data":post});
});
var nodeShowHidden = cView.gNodes["show-hidden"].cloneAll();
nodeShowHidden.cNodes["href"].action = true;
body.appendChild(nodeShowHidden);
if(cView.doc.hiddenCount) nodeShowHidden.cNodes["href"].innerHTML= "Show "+ cView.doc.hiddenCount + " hidden entries";
}
};
return _Drawer;
});
<file_sep>"use strict";
define(
[
"./utils"
, "./common"
, "./draw"
, "./actions"
, "./router"
, "./hasher"
, "./faselector"
],function(
Utils
, _Common
, _Drawer
, _Actions
, _Router
, _Hasher
, _FaSelector
){
var apis = {
"freefeed": require("./freefeed")
,"mokum": require("./mokum")
}
var gTemplates = require("./templates.json");
var gDomains = require("./domains.json");
function _gMe(){
var context = this;
var logins = context.logins;
var mainId;
var ids = Object.keys(logins);
if(ids.length == 0)return null;
if(ids.length === 1){
mainId = ids[0];
context.token = logins[ids[0]].token;
}else ids.some(function(id){
if(logins[id].token == context.token) {
mainId = id;
return true;
}else return false;
});
logins[mainId].data.domain = context.domain;
return logins[mainId].data;
}
function _ids(){
var ids = Object.keys(this.logins);
return ids;
}
function _Context(v, domain, api){
var context = this ;
Object.keys(context.defaults).forEach(function(key){
context[key] = JSON.parse(JSON.stringify(context.defaults[key]))
});
context.domain = domain;
context.cView = v;
v.contexts[domain] = context;
context.api = new Object();
Object.keys(api.protocol).forEach(function(f){
context.api[f] = function(){
return api.protocol[f].apply(context, arguments)
.then(function(res){
return ( typeof res !== "undefined")?
api.parse(res)
:null;
});
}
});
context.api.parse = api.parse;
context.api.name = api.name;
this.p = new Utils._Promise( function(resolve){resolve()});
var rtFuncs = ["rtSubTimeline","rtSubPost","rtSubUser"];
if ((typeof api.oRT !== "undefined") && JSON.parse(v.localStorage.getItem("rt"))){
context.rt = new api.oRT(context,JSON.parse(v.localStorage.getItem("rtbump")));
rtFuncs.forEach(function(key){
context[key] = function(inp){
context.rt[key](inp);
};
});
}else rtFuncs.forEach(function(key){context[key] = function(){};});
Object.defineProperty(this, "gMe", {"get": _gMe});
Object.defineProperty(this, "ids", {"get": _ids});
}
_Context.prototype = {
constructor:_Context
,"defaults":{
"gUsers": { "byName":{}}
,"gUsersQ": {}
,"gComments": {}
,"gAttachments": {}
,"gFeeds": {}
,"gRt": {}
,"miscRts": {}
,"logins": {}
,"token": null
,"pending":[]
,"timelineId": null
}
,"initRt": function(){
var cView = this;
var bump = cView.localStorage.getItem("rtbump");
this.gRt = new RtUpdate(this.token, bump);
this.gRt.subscribe(this.rtSub);
}
,"digestText":function(text){
var context = this;
var arr = context.cView.autolinker.link(
text.trim().replace(/&/g,"&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/[\n\r]{2,}/g, "\r\r")
,"array"
).reduce(function(prev,curr){return prev.concat(curr);},[]);
arr.forEach(function(txt,idx,arr){
arr[idx] = txt.replace(
/___CONTEXT_PATH___/g
,gConfig.front+"as/"+context.domain
).replace(/(https?:\/\/)?friendfeed.com\/\w+/g
,"https://freefeed.net/archivePost?url=$&"
);
});
arr.toString = function(){return this.join(" ");};
return arr;
}
,"getWhoami": function(token){
var context = this;
return context.api["_getWhoami"](token).then(function(res){
var id = res.users.id;
if(typeof context.logins[id] === "undefined"){
context.logins[id] = new Object();
context.logins[id].token = token;
context.logins[id].domain = context.domain;
}
context.logins[id].data = res;
context.logins[id].data.domain = context.domain;
context.cView.Common.refreshLogin(id,context);
return res;
});
}
}
function _cView(doc){
var cView = this;
Object.keys(cView.defaults).forEach(function(key){
cView[key] = JSON.parse(JSON.stringify(cView.defaults[key]))
});
//cView.autolinker = new Autolinker({"truncate":20, "replaceFn":Utils.frfAutolinker } );
["localStorage", "sessionStorage"].forEach(function(storage){
cView[storage] = new Object();
["setItem", "getItem", "removeItem"].forEach(function(action){
cView[storage][action] = function(){
try{
return window[storage][action].apply(window[storage],arguments);
} catch(e){return null};
}
});
});
cView.doc = doc;
doc.cView = cView;
cView.cView = cView;
cView.Common = new _Common(cView);
cView.Drawer = new _Drawer(cView);
cView.Actions = new _Actions(cView);
cView.Router = new _Router(cView);
cView.hasher = new _Hasher["_Minhash"]({"fnum":1000});
cView.FaSelector = new _FaSelector(cView);
cView.addons = {
"all":new Array()
,"ok": function(){}
,"pr": new Object()
};
cView.addons.pr = new Utils._Promise(function(resolve){
cView.addons.ok = resolve;
});
//cView.SecretActions = new _SecretActions(cView);
var Url2link = require("./url2link");
cView.autolinker = new Url2link({ "truncate":25
,"url":{
"actions":[
["pre",cView.Common.setFrontUrl]
]
}
,"text":{
"actions":[
["post",function(text){
return text.replace(/\n/g," \n").split(" ")
.filter(function(txt){return txt!="";});
}]
]
}
,"hashtag":{
"actions":[
["post",function(text){
return text.replace(
/___CONTEXT_SEARCH___/
, gConfig.front+"search?qs="
);
}]
]
}
});
var domains = new Object();
var confDomains = Array.isArray(gConfig.domains)?gConfig.domains:Object.keys(gConfig.domains);
//gConfig.domains.forEach(function (d){
confDomains.forEach(function (d){
var cfg = gDomains[d];
domains[d] = cfg;
cView.contexts[d] = new _Context(cView, d, apis[cfg.api](cfg.server));
});
gConfig.domains = domains;
cView.leadContext = cView.contexts[gConfig.leadDomain];
}
_cView.prototype = {
constructor: _cView
,"defaults":{
"contexts":{}
,"gEmbed": {}
,"gNodes": {}
,"rtSub" : {}
,"cTxt": null
,"subReqsCount":0
,"blocks": {"blockPosts":{},"blockComments":{},"blockStrings":{}}
,"blockLists": {"cmts":"blockComments", "posts":"blockPosts"}
,"threshold":0.63
,"skip":0
,"minBody": 20
,"noBlocks":false
}
,"Utils":Utils
};
function init(doc){
var cView = new _cView(doc);
cView.Common.genNodes(gTemplates.nodes).forEach( function(node){
cView.gNodes[node.classList[0]] = node;
});
if(cView.Common.getCookie("privacy")){
var nodePriv = cView.doc.getElementById("privacy-popup");
nodePriv.parentNode.removeChild(nodePriv);
}
cView.Common.setIcon("throbber-16.gif");
return cView;
}
return {
"cView":_cView
,"init":init
}
});
<file_sep>"use strict";
/*
var cfg = {"srvurl":"http://moimosk.ru/cgi/secret?","authurl": gConfig.serverURL,"sk":16 };
*/
var CryptoPrivate = function(cfg){
this.cfg = cfg;
this.storage = window.sessionStorage;
if(typeof cfg.authurl === "undefined" ) throw new Error("authurl is not defined");
var sSymKeys = this.storage.getItem("crypto_keys");
if (sSymKeys != "undefined")if (sSymKeys) var gSymKeys = JSON.parse(this.storage.getItem("crypto_keys"));
if(!this.gSymKeys)this.loadKeys(gSymKeys);
var c_login = this.storage.getItem("crypto_login")
if(c_login){
c_login = JSON.parse(c_login);
this.password = <PASSWORD>(<PASSWORD>);
this.username =c_login.username;
}
}
CryptoPrivate.prototype = {
constructor: CryptoPrivate,
gSymKeys: undefined,
decipher: undefined,
cfg: undefined,
username: undefined,
password: <PASSWORD>,
constants:{"kidlength":btoa(openpgp.crypto.hash.sha256("1")).length},
pubCache: {},
pubQ: {},
decrypt: function(data){
var idL = this.cfg.encId.length;
if (data.slice(0,idL) != this.cfg.encId) return {"error":"0"};
if(typeof this.decipher === "undefined") return {"error":"4"};
var key = this.decipher[data.slice(idL, this.constants.kidlength+idL)];
if(typeof key === "undefined") return {"error":"3"};
return StringView.makeFromBase64(openpgp.crypto.cfb.decrypt("aes256", atob(key), atob(data.slice(idL+this.constants.kidlength) ))).toString();
},
encrypt: function(id, data){
var init = openpgp.crypto.getPrefixRandom("aes256");
var key_idx = Math.floor(Math.random()*this.cfg.sk);
if (typeof this.gSymKeys[id] === "undifined") return {"error":"1"};
var sym_key = atob(this.gSymKeys[id].aKeys[key_idx].key);
/*var init = new Uint8Array(16);
window.crypto.getRandomValues(init);
*/
return this.cfg.encId +this.gSymKeys[id].aKeys[key_idx].id+btoa(openpgp.crypto.cfb.encrypt( init,"aes256", new StringView(data).toBase64(), sym_key));
},
setPassword: function (pass){
this.password = <PASSWORD>);
caller.storage.setItem("crypto_login", JSON.stringify({"password":<PASSWORD>(<PASSWORD>), "username":gMe.users.username}));
},
makeToken: function(){
var caller = this;
return new Promise(function(resolve,reject){
var token = caller.storage.getItem("crypto_write_token");
if(token) return resolve( token);
caller.requestToken().then(function(){
token = caller.storage.getItem("crypto_write_token");
return resolve( token);
}, reject);
} );
},
logout: function(){
caller.storage.removeItem("key_pub");
caller.storage.removeItem("key_private");
caller.storage.removeItem("crypto_write_token");
caller.storage.removeItem("crypto_keys");
this.username = undefined;
this.password = <PASSWORD>;
this.decipher = new Object();
this.gSymKeys = new Object();
},
register: function(){
var caller = this;
var init = openpgp.crypto.getPrefixRandom("aes256");
var keyPuA = caller.storage.getItem("key_pub");
var keyPrA = caller.storage.getItem("key_private");
var my_passphrase = ""; // Key Pairs is always protected with a caller.password to safety.
return new Promise(function(resolve,reject){
if((typeof caller.password === "undefined")|| (typeof caller.username === "undefined")){
reject();
return;
}
if (!keyPuA)openpgp.generateKeyPair({numBits: 1024, userId: caller.username, passphrase: <PASSWORD>,unlocked: true }).then (function (a){
caller.storage.setItem("key_pub", a.publicKeyArmored);
caller.storage.setItem("key_private", a.privateKeyArmored);
keyPuA = a.publicKeyArmored;
keyPrA = a.privateKeyArmored;
go();
});else go();
function go(){
var oReqS = new XMLHttpRequest();
oReqS.open("POST", caller.cfg.srvurl+"register");
oReqS.onload = function(){
if(oReqS.status < 400){
var msgEnc = openpgp.message.readArmored(oReqS.response);
var dkey = openpgp.key.readArmored(keyPrA);
openpgp.decryptMessage(dkey.keys[0],msgEnc)
.then(function(msg){
caller.storage.setItem("crypto_write_token",msg);
caller.update().then( resolve());
});
}else reject();
}
oReqS.setRequestHeader("X-Authentication-Token", gConfig.token);
oReqS.setRequestHeader("Content-type","application/json");
oReqS.send(JSON.stringify({"d":keyPuA}));
}
});
},
initPrivate: function(grName){
var caller = this;
var arrKeys = new Array(caller.cfg.sk);
var id;
var grIdRaw = "";
for(var idx = 0; idx < caller.cfg.sk; idx++){
var key = openpgp.crypto.generateSessionKey("blowfish");
id = btoa(openpgp.crypto.hash.sha256(key));
arrKeys[idx]= {"id":id, "key":btoa(key)};
grIdRaw += key;
}
id = caller.username+"-"+btoa(openpgp.crypto.hash.sha256(grIdRaw));
var priv = new Object();
priv.aKeys = arrKeys;
priv.name = new StringView(grName).toBase64();
priv.id = id;
if (typeof caller.gSymKeys === "undefined") caller.gSymKeys = new Object();
caller.gSymKeys[id] = priv;
if (typeof caller.decipher === "undefined") caller.decipher = new Object();
priv.aKeys.forEach(function(key){
caller.decipher[key.id] = key.key;
});
return new Promise(function(resolve,reject){
caller.update().then(resolve,reject);
});
},
getUserPub: function(victim){
var caller = this;
return new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.open("GET", caller.cfg.srvurl+"user/"+victim);
oReq.onload = function(){
if(oReq.status < 400){
resolve(oReq.response);
}else reject(oReq.status);
}
oReq.send();
});
},
readMsg: function(msgEnc){
var caller = this;
return new Promise(function(resolve,reject){
var keyPrA = caller.storage.getItem("key_private");
if(!keyPrA) {
getUserPriv().then(function(){caller.readMsg.then(resolve,reject)},reject);
return;
}
var dkey = openpgp.key.readArmored(keyPrA);
openpgp.decryptMessage(dkey.keys[0],openpgp.message.readArmored(msgEnc)).then(function(msg){resolve(msg);}, reject);
});
},
genMsg: function(victim,data){
var caller = this;
return new Promise(function(resolve,reject){
caller.getUserPub(victim).then(function(arKey){
var key = openpgp.key.readArmored(arKey).keys[0];
openpgp.encryptMessage(key,data).then(resolve);
}, reject);
});
},
addKeys: function(keys){
if (!keys||(keys == "null")) return;
var caller = this;
if (typeof caller.gSymKeys === "undefined") caller.gSymKeys = new Object();
console.log(typeof caller.gSymKeys[keys.id]);
if((typeof caller.gSymKeys[keys.id]) != "undefined" )return;
caller.gSymKeys[keys.id] = keys;
if (typeof caller.decipher === "undefined") caller.decipher = new Object();
keys.aKeys.forEach(function(key){ caller.decipher[key.id] = key.key; });
caller.update();
},
loadKeys: function(keys){
if (!keys||(keys == "null")) return;
var caller = this;
caller.gSymKeys = keys;
if (typeof caller.decipher === "undefined") caller.decipher = new Object();
for(var pid in caller.gSymKeys)
caller.gSymKeys[pid].aKeys.forEach(function(key){ caller.decipher[key.id] = key.key; });
caller.storage.setItem("crypto_keys",JSON.stringify(caller.gSymKeys));
caller.ready = 1;
},
getUserPriv: function(){
var caller = this;
return new Promise(function(resolve,reject){
if((typeof caller.password === "undefined")|| (typeof caller.username === "undefined")){
reject(-2);
return;
}
var oReq = new XMLHttpRequest();
oReq.open("GET", caller.cfg.srvurl+"data" );
oReq.onload = function(){
if(oReq.status < 400){
var secret;
try {
secret = openpgp.crypto.cfb.decrypt("aes256",caller.password , atob(oReq.response));
} catch(e){
console.log(e);
reject(-1);
return;
}
secret = JSON.parse(secret);
caller.storage.setItem("key_private", secret.prkey);
caller.loadKeys(secret.symkeys);
resolve();
}else reject(oReq.status);
}
oReq.setRequestHeader("X-Authentication-User",caller.username);
oReq.send();
});
},
sign: function(data){
var caller = this;
return new Promise(function(resolve,reject){
var keyPrA = caller.storage.getItem("key_private");
if(!keyPrA) {
caller.getUserPriv().then(function(){caller.requestToken( resolve,reject)},reject);
return;
}
var sign = new openpgp.packet.Signature();
sign.signatureType = openpgp.enums.signature.text;
sign.hashAlgorithm = openpgp.config.prefer_hash_algorithm;
var pLit = new openpgp.packet.Literal();
pLit.setText( new StringView(data).toBase64());
keyPrA = openpgp.key.readArmored(keyPrA);
var pSignKey = keyPrA.keys[0].getSigningKeyPacket();
sign.publicKeyAlgorithm = pSignKey.algorithm;
sign.sign(pSignKey,pLit);
resolve(btoa(sign.write()));
});
},
verify: function(data, txtSign, username){
var caller = this;
return new Promise(function(resolve,reject){
var keyPub;
function gotUser(){
var sign = new openpgp.packet.Signature();
var binSign = atob(txtSign);
var pLit = new openpgp.packet.Literal();
pLit.setText( new StringView(data).toBase64());
sign.read(binSign,0,binSign.length);
var pKey = keyPub.keys[0].getKeyPacket([sign.issuerKeyId]);
if(!pKey)return reject();
if (!sign.verify(pKey, pLit))return reject();
resolve();
}
if (caller.pubCache[username]){
keyPub = caller.pubCache[username];
gotUser();
} else if(caller.pubQ[username]) caller.pubQ[username].then(
function(){
keyPub = caller.pubCache[username];
gotUser();
},reject);
else{
caller.pubQ[username] = new Promise(function(resolveP, rejectP){
caller.getUserPub(username).then(function(res){
keyPub = openpgp.key.readArmored(res);
caller.pubCache[username] = keyPub;
gotUser();
resolve();
resolveP();
},function(){
reject();
rejectP();
});
});
}
});
},
mkOwnToken: function(data){
if (typeof this.password === "undefined") return null;
return btoa(openpgp.crypto.hash.sha256(this.password+data));
},
requestToken: function(){
var caller = this;
return new Promise(function(resolve,reject){
var keyPrA = caller.storage.getItem("key_private");
if(!keyPrA) {
caller.getUserPriv().then(function(){caller.requestToken( resolve,reject)},reject);
return;
}
var oReq = new XMLHttpRequest();
oReq.open("GET", caller.cfg.srvurl+"token" );
oReq.onload = function(){
if(oReq.status < 400){
var msgEnc = openpgp.message.readArmored(oReq.response);
var dkey = openpgp.key.readArmored(keyPrA);
openpgp.decryptMessage(dkey.keys[0],msgEnc
).then(function(msg){
caller.storage.setItem("crypto_write_token",msg);
resolve();
},reject);
}else reject(oReq.status);
}
oReq.setRequestHeader("X-Authentication-User",caller.username);
oReq.send();
});
},
update: function(){
var caller = this;
var keyPrA = caller.storage.getItem("key_private");
return new Promise(function(resolve,reject){
if((typeof caller.password === "undefined")|| (typeof caller.username === "undefined")){
reject();
return;
}
var init = openpgp.crypto.getPrefixRandom("aes256");
var oReq = new XMLHttpRequest();
oReq.open("POST", caller.cfg.srvurl+"update" );
oReq.onload = function(){
if(oReq.status < 400){
resolve();
}else reject();
}
var token = caller.storage.getItem("crypto_write_token");
if(!token ) {
caller.requestToken().then(doReq,reject);
}else doReq();
function doReq(){
token = caller.storage.getItem("crypto_write_token");
oReq.setRequestHeader("X-Authentication-Token",token);
oReq.setRequestHeader("X-Authentication-User",caller.username);
oReq.setRequestHeader("Content-type","application/json");
oReq.send(JSON.stringify({"d": btoa(openpgp.crypto.cfb.encrypt( init,"aes256", JSON.stringify({"prkey":keyPrA,"symkeys":caller.gSymKeys }),caller.password ))}));
caller.storage.setItem("crypto_keys",JSON.stringify(caller.gSymKeys) );
}
});
}
}
<file_sep> "use strict";
var gPrivTimeline = {"done":0,"postsById":{},"oraphed":{count:0},"noKey":{},"noDecipher":{},nCmts:0,"posts":[] };
var matrix = new Object();
var Init = require("./init.js")
var Addons = require("./addons.js");
var polyfills = require("./polyfills.js");
window.browserDoc = function(){
var cView = document.cView;
var Utils = cView.Utils;
var locationPath = /(https?:\/\/[^\?]*)/.exec(document.location)[1].slice(gConfig.front.length);
if (locationPath == "")locationPath = "home";
cView.fullPath = locationPath;
var arrLocationPath = locationPath.split("/");
var settingsNames = require("./settings.json");
settingsNames.forEach(function(name){
var setting = cView.localStorage.getItem(name);
if (setting == "undefined")cView.localStorage.setItem(name, "false");
});
if(arrLocationPath[0].toLowerCase() != "settings"){
cView.search = document.location.search.slice(1);
var matchOffset = cView.search.match(/offset=(\d+)/);
if(matchOffset) cView.skip = matchOffset[1];
cView.search = cView.search.replace(/&?offset=\d+&?/,"").replace(/&?limit=\d+&?/,"")
}else if(document.location == gConfig.front +"settings/raw"){
var nodeSplash = document.getElementById("splash");
cView.Drawer.drawRaw(nodeSplash);
}else if(document.location == gConfig.front +"settings/wipe"){
settingsNames.forEach(function(setting){cView.localStorage.removeItem(setting)});
cView.Actions.logout();
}
setLocalSettings();
cView.Common.loadLogins();
var body = cView.gNodes["main"].cloneAll();
var nodeControls;
if(Object.keys(cView.contexts).some(function(domain){return cView.contexts[domain].token})){
if(cView.localStorage.getItem("use-custom-upper-menu") == "true"){
try{
var scheme = JSON.parse(cView.localStorage.getItem("custom-ui-upper"));
nodeControls = cView.Drawer.genCustomUI(scheme);
}catch(e){ nodeControls = cView.gNodes["controls-login"].cloneAll()}
}else nodeControls = cView.gNodes["controls-login"].cloneAll();
} else nodeControls = cView.gNodes["controls-anon"].cloneAll();
cView.Utils.setChild(body.cNodes["container"], "controls", nodeControls);
cView.doc.getElementsByTagName("body")[0].appendChild(body);
/*
var nodeDebug = document.createElement("div");
nodeDebug.id = "debug";
nodeDebug.className = "debug";
body.appendChild(nodeDebug);
nodeDebug.innerHTML = [document.location
,"--------"
,locationPath
,gConfig.front.length].join("<br>");
*/
var contexts = new Object();
Object.keys(cView.contexts).forEach(function(domain){contexts[domain] = cView.contexts[domain];});
cView.Router.route(contexts, locationPath).then(postInit,function(err){
console.log(err);
if (Array.isArray(err))
err = err.filter(function(item){return typeof item !== "undefined"})[0];
if( typeof err === "string") switch(err){
case "token":
cView.Common.auth();
break;
}else {
var nodeMsg = cView.gNodes["global-failure"].cloneAll();
body.getNode(["c","container"],["c","details"]).appendChild(nodeMsg);
try{
nodeMsg.cNodes["title"].innerHTML = "Error " + err.code;
nodeMsg.cNodes["info"].innerHTML = cView.Utils.err2html(err.data);
}catch(e){ };
}
postInit();
});
return ;
}
window.initDoc = function(){
Init.init(document);
polyfills();
//document.cView.Utils._Promise = Promise;
browserDoc();
}
function postInit(){
var cView = document.cView;
(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,cView.doc,"script","//www.google-analytics.com/analytics.js","ga");
ga("create", gConfig.ga, "auto");
ga("send", "pageview");
Object.keys(cView.contexts).forEach(function(domain){
var context = cView.contexts[domain];
Object.keys(context.logins).forEach(function(id){
context.getWhoami(context.logins[id].token);
context.rtSubUser(id);
});
});
//if(parseInt(cView.localStorage.getItem("rt")) ) cView.initRt();
if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
(function(a,b,c){
var d,e,f;
f="PIN_"+~~((new Date).getTime()/864e5),
a[f]||(a[f]=!0,a.setTimeout(function(){
d=b.getElementsByTagName("SCRIPT")[0],
e=b.createElement("SCRIPT"),
e.type="text/javascript",
e.async=!0,
e.src=c+"?"+f,
d.parentNode.insertBefore(e,d)
}
,10))
})(window,cView.doc,"//assets.pinterest.com/js/pinit_main.js");
}
var nodesAttImg = document.getElementsByClassName("atts-img");
for (var idx = 0; idx < nodesAttImg.length; idx++){
var nodeImgAtt = nodesAttImg[idx];
if(cView.Utils.chkOverflow(nodeImgAtt))
nodeImgAtt.parentNode.cNodes["atts-unfold"].hidden = false;
}
cView.Drawer.applyReadMore( cView.doc);
window.addEventListener("whoamiUpdated", cView.Common.regenCounters);
var nodeSplash = document.getElementById("splash");
nodeSplash.parentNode.removeChild(nodeSplash);
cView.Common.setIcon("favicon.ico");
Addons.commit(cView).then(function(){
var lists = cView.blockLists;
Object.keys(cView.contexts).forEach(function (domain){
var context = cView.contexts[domain];
Object.keys(lists).forEach(function(type){
var list = cView.blocks[lists[type]][domain];
if(typeof list !== "undefined") Object.keys(list).forEach(function(id){
if(list[id] !== true) return;
var user = context.gUsers[id];
if(typeof user === "undefined") return;
list[id] = user.username;
});
});
});
cView.Common.updateBlockList();
});
}
window.srvDoc = function(){
var cView = document.cView;
var idx = 0;
var aidx = 0;
setLocalSettings();
if(typeof cView.gContent !== "undefined")
cView.Drawer.loadGlobals(cView.gContent);
regenCNodes(document.getElementsByTagName("body")[0]);
switch(cView.timeline){
case "settings":
return cView.Drawer.drawSettings();
case "requests":
return cView.Drawer.drawRequests();
default:
}
document.posts = document.getElementById("posts");
document.hiddenCount = 0;
document.hiddenPosts = new Array();
if(Array.isArray(cView.gContent.posts))
cView.gContent.posts.forEach(function(post){
document.hiddenPosts.push({"data":post, "is": post.isHidden});
if(!post.isHidden) document.getElementById(post.id).rawData = post;
else document.hiddenCount++;
});
else if(typeof cView.gContent.posts !== "undefined")
document.getElementById(cView.gContent.posts.id).rawData = cView.gContent.posts;
setAttr(document.getElementsByClassName("avatar-h"),"userid");
setAttr(document.getElementsByTagName("a"),"action");
Object.keys(gEvents).forEach(function(id){
var node = document.getElementById(id);
var eh = gEvents[id];
Object.keys(eh).forEach(function(evt){
eh[evt].forEach(function(a){
node.addEventListener(evt, cView[a[0]][a[1]])
});
});
});
if(cView.gContent.comments)cView.gContent.comments.forEach(function(cmt){
var nodeComment = document.getElementById(cmt.id);
if(nodeComment ){
nodeComment.createdAt = cmt.createdAt;
nodeComment.userid = cmt.createdBy;
}
});
var nodesDate = document.getElementsByClassName("post-date");
for(idx = 0; idx < nodesDate.length; idx++){
var victim = nodesDate[idx]; do victim = victim.parentNode; while(victim.className != "post");
var aNode = nodesDate[idx].getElementsByTagName("a")[0];
aNode.date = JSON.parse(victim.rawData.createdAt);
window.setTimeout(cView.Drawer.updateDate, 100, aNode, cView);
}
var arrUsernames = new Array();
var nodesUsernames = document.getElementsByClassName("username");
for(idx = 0; idx < nodesUsernames.length; idx++)
arrUsernames.push(nodesUsernames[idx]);
arrUsernames.forEach(function(node){
if(typeof cView.gUsers.byName[node.innerHTML] !== "undefined")
node.parentNode.outerHTML = cView.gUsers.byName[node.innerHTML].link;
});
var urlMatch;
if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
var nodesPost = document.getElementsByClassName("post");
for(idx = 0; idx < nodesPost.length; idx ++){
if(((urlMatch = nodesPost[idx].rawData.body.match(/https?:\/\/[^\s\/$.?#].[^\s]*/i) )!= null)
&& (!nodesPost[idx].rawData.attachments))
(function(url, nodePost){
cView.gEmbed.p.then(function(oEmbedPr){
cView.Drawer.embedPreview(oEmbedPr
,url[0]
,nodePost.cNodes["post-body"].cNodes["attachments"]
);
});
})(urlMatch, nodesPost[idx]);
}
}
["blockPosts", "blockComments"].forEach(function(list){
if(Array.isArray(cView[list]))
cView[list].forEach(function(user){ cView.Drawer[list](user,true); });
});
var nodeAddSender = document.getElementsByClassName("add-sender")[0];
if(nodeAddSender != null) nodeAddSender.ids = [cView.mainId];
var nodeNewPostTo = document.getElementsByClassName("new-post-to")[0];
if(nodeNewPostTo != null) nodeNewPostTo.userid = cView.mainId;
cView.Utils.postInit();
}
function regenCNodes(node){
var cView = document.cView;
node.cNodes = new Object();
node.getNode = function(){
var args = cView.Utils.args2Arr.apply(this,arguments);
args.unshift(node);
return cView.Utils.getNode.apply(node, args);
};
for(var idx = 0; idx < node.childNodes.length; idx++){
regenCNodes(node.childNodes[idx]);
var cName = node.childNodes[idx].className;
if(cName != "")node.cNodes[cName] = node.childNodes[idx];
}
}
function setAttr(nodes, name){
for(var idx = 0; idx < nodes.length; idx++){
var aidx = 0;
do{
if (nodes[idx].attributes[aidx].name == name){
nodes[idx][name] = nodes[idx].attributes[aidx].value;
if (nodes[idx][name] == "true") nodes[idx][name] = true;
if (nodes[idx][name] == "false") nodes[idx][name] = false;
break;
}
}while(++aidx< nodes[idx].attributes.length);
}
}
function setLocalSettings(){
var cView = document.cView;
try{
if(JSON.parse(cView.localStorage.getItem("blocks")))
cView.blocks = JSON.parse(cView.localStorage.getItem("blocks"));
}catch(e){
settingsError("bolcks");
}
try{
if(typeof cView.blocks.blockStrings === "undefined")
cView.blocks.blockStrings = new Object();
Object.keys(cView.blockLists).forEach(function(type){
if (typeof cView.blocks[cView.blockLists[type]] === "undefined"){
cView.blocks[cView.blockLists[type]] = new Object();
}
});
}catch(e){
settingsError("blockLists");
}
var nameMode = cView.localStorage.getItem("screenname");
if(nameMode){
cView.localStorage.setItem("display_name", nameMode);
cView.localStorage.removeItem("screenname");
}
cView.mode = cView.localStorage.getItem("display_name");
cView.readMore = JSON.parse(cView.localStorage.getItem("read_more"));
//default
if (cView.localStorage.getItem("read_more_height") == null) cView.localStorage.setItem("read_more_height", 10);
cView.readMoreHeight = cView.readMore? JSON.parse(cView.localStorage.getItem("read_more_height")):0;
cView.blockLonely = JSON.parse(cView.localStorage.getItem("hide-lonely-posts"));
cView.noMetapost = JSON.parse(cView.localStorage.getItem("no_metapost"));
var cssTheme = cView.localStorage.getItem("display_theme");
if (cssTheme == "main.css") {
cssTheme = "expanded.css";
cView.localStorage.setItem("display_theme", cssTheme)
}
var sheet;
var idx;
try{
for ( idx = 0 ; idx< document.styleSheets.length; idx ++)
if( document.styleSheets[idx].title == "local")
sheet = document.styleSheets[idx];
if (JSON.parse(cView.localStorage.getItem("show_newlines")))
sheet.insertRule(".long-text{white-space:pre-wrap;}",0);
else
sheet.insertRule(".long-text{white-space:normal;}",0);
}catch(e){
settingsError("show_newlines");
}
if(cssTheme)
document.getElementById("main-stylesheet").href = gConfig.static
+ cssTheme
+ "?build="
+ encodeURIComponent(___BUILD___);
if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
var nodeEmScript = document.createElement("script");
(function(w, d){
var id='embedly-platform', n = 'script';
if (!d.getElementById(id)){
w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);};
var e = d.createElement(n); e.id = id; e.async=1;
e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js';
var s = d.getElementsByTagName(n)[0];
s.parentNode.insertBefore(e, s);
}
})(window, document);
embedly("defaults", {
cards: {
height: 200
//width: 700
//align: 'right',
//chrome: 0
}
});
embedly('on', 'card.rendered', function(iframe){
// cView.Utils.unscroll(iframe);
});
cView.gEmbed.p = new Promise(function(resolve,reject){
var oReq = new XMLHttpRequest();
oReq.onload = function(){
if(oReq.status < 400)
resolve(JSON.parse(oReq.response));
else reject(oReq.response);
}
oReq.open("get",gConfig.static + "providers.json",true);
oReq.send();
});
}
if (cView.localStorage.getItem("do_dark_theme") == "true"){
var elCSS = document.createElement("link");
elCSS.rel = "stylesheet";
elCSS.href = "https://gitcdn.xyz/repo/dym-sh/freefeed-dark.css/master/no-wrap.css";
document.getElementsByTagName("head")[0].appendChild(elCSS);
}
}
function settingsError(id){
var msg = "Error applying {"+id+"}";
console.log(msg);
var dialog = document.getElementById("modalDlg");
if (!dialog){
dialog = document.cView.gNodes["modal-error-dlg"].cloneAll();
document.body.appendChild(dialog);
}
dialog.cNodes["value"].innerHTML += msg + "<br>";
}
<file_sep>"use strict";
define("./addons/likecomm",["../utils"],function(utils){
var cView;
//var domain = "FreeFeed";
//var auth = false;
var nodesT = new Object();
var template = [
{"c":"control", "cl":["inline-control"]
,"el":[
{"c":"spacer","t":"span","txt":"—", "p":{"hidden":true}}
,{"c":"display","t":"span" }
,{"c":"action", "t":"a", "cl":["like-comm-action"], "e":{"click":["addons-like-comm","action"]}}
]}
,{"c":"display", "cl":["like-comm"], "t":"a", "e":{"click":["addons-like-comm","show"]}}
];
var handlers = {
"action":function(e){
var nodeCmt = e.target.getNode(["p","comment"]);
var id = nodeCmt.rawId;
var action = e.target.action;
var post = e.target.getNode(["p","post"]).rawData;
var domain = nodeCmt.domain;
var context = cView.contexts[domain];
switch(context.api.name){
case "FreeFeed":
utils.xhr({
"url":gConfig.domains[domain].server.serverURLV2
+"comments/"+ id + (action?"/like":"/unlike")
,"method":"post"
,"token":context.token
}).then(function(res){
res = JSON.parse(res);
res.users.forEach(cView.Common.addUser, context);
var fMyCmt = res.likes.some( function(like){
return like.userId == context.gMe.users.id;
});
context.gComments[id].hasOwnLike = fMyCmt;
context.gComments[id].likes = res.likes.length;
apply({ "id":id
,"likes": res.likes.length
,"my_likes": fMyCmt
}
,nodeCmt
);
});
break;
case "Mokum":
utils.xhr({
"url":[gConfig.domains[domain].server.serverApiURL + "posts"
, context.gUsers[post.createdBy].username
, post.id
, "clike"
, id+".json"
].join("/")
,"method": action?"post":"DELETE"
,"headers":{
"X-API-Token":context.token
,"Accept": "application/json"
,"Content-Type": "application/json"
}
}).then(function(res){
e.target.action = !action;
e.target.innerHTML = (!action?"like":"un-like");
});
break;
}
}
,"show":function(e){
var id = e.target.getNode(["p","comment"]).rawId;
var domain = e.target.getNode(["p","comment"]).domain;
var context = cView.contexts[domain];
switch(context.api.name){
case "FreeFeed":
utils.xhr({
"url":gConfig.domains[domain].server.serverURLV2
+ "comments/" + id + "/likes"
,"token":context.token
}).then(function(res){
res = JSON.parse(res);
if(res.status == "error") return;
res.users.forEach(cView.Common.addUser, context);
display(res.likes.map(function(like){
return context.gUsers[like.userId].username;
}));
});
break;
case "Mokum":
var clikes = context.gComments[id].clikes;
if(Array.isArray(clikes))
display(clikes.map(function(id){return context.gUsers[id].username;}));
break;
}
return;
function display(data){
var popup = cView.gNodes["user-popup"].cloneAll();
popup.style.top = e.target.offsetTop;
popup.style.left = e.target.offsetLeft;
popup.cNodes["up-info"].innerHTML = "<b>Liked by:</b>";
if (!data.length)popup.cNodes["up-info"].innerHTML = "No info";
data.forEach(function(uname){
var div = cView.doc.createElement("div");
var link = cView.doc.createElement("a");
link.innerHTML = "@" + uname;
link.href = gConfig.front + "as/"+domain+"/"+uname;
div.appendChild(link);
popup.cNodes["up-info"].appendChild(div);
});
e.target.parentNode.appendChild(popup);
cView.Utils.fixPopupPos(popup);
};
}
,"evtUpdNode":function (e){
var node = e.detail;
var context = cView.contexts[node.domain];
if(!node
||(typeof context == "undefined")
||(node.classList[0] !== "comment")
||(context.api.name !== "FreeFeed"))
return;
var cmt = context.gComments[node.rawId];
apply({ "id":node.rawId
,"likes":(cmt.likes == ""?0:cmt.likes)
,"my_likes":(cmt.hasOwnLike == true?"1":"0")
}
,node
);
}
,"evtNewNode":function (e){
var arrNodes = e.detail;
if(!arrNodes)return;
arrNodes = Array.isArray(arrNodes)?arrNodes:[arrNodes];
var cmts = new Object();
arrNodes.forEach(function(node){
var domain;
switch(node.classList[0]){
case "post":
domain = node.rawData.domain;
if(!Array.isArray(cmts[domain]))cmts[domain] = new Array();
var comments = node.getElementsByClassName("comment");
for (var idx = 0; idx < comments.length; idx++ )
if(typeof comments[idx].rawId !== "undefined")
cmts[domain].push( comments[idx]);
break;
case "comment":
domain = node.domain;
if(!Array.isArray(cmts[domain]))cmts[domain] = new Array();
cmts[domain].push(node);
break;
}
});
loadLikes(cmts);
}
,"evtCLikeMokum" :function(e){
apply(e.detail.info,e.detail.node);
}
}
function setControls(node){
var context = cView.contexts[node.domain];
var nodeControl = nodesT["control"].cloneAll();
node.cNodes["comment-body"].appendChild(nodeControl );
node.cNodes["comment-body"].cNodes["like-comm"] = nodeControl;
if(context.gMe){
nodeControl.cNodes["spacer"].hidden = false;
nodeControl.cNodes["action"].action = true;
nodeControl.cNodes["action"].innerHTML = "好";
if (context.gMe.users.id == node.userid) {
nodeControl.cNodes["action"].hidden = true;
nodeControl.cNodes["spacer"].hidden = true;
}
}
return nodeControl;
}
function apply (likeInfo, node){
var context = cView.contexts[node.domain];
var nodeControl = node.getNode( ["c","comment-body"] ,["c","like-comm"]);
if (!nodeControl) nodeControl= setControls(node);
var nodeLike = cView.doc.createElement("span");
if(likeInfo.likes){
nodeControl.cNodes["spacer"].hidden = false;
nodeLike = nodesT["display"].cloneAll();
nodeLike.innerHTML = likeInfo.likes;
if(context.gMe && (context.gMe.users.id != node.userid)){
nodeControl.cNodes["action"].action = (likeInfo.my_likes == "0");
nodeControl.cNodes["action"].innerHTML = (likeInfo.my_likes == "0"?"like":"un-like");
}
}else if(context.gMe && (context.gMe.users.id != node.userid)){
nodeControl.cNodes["spacer"].hidden = false;
nodeControl.cNodes["action"].action = true;
nodeControl.cNodes["action"].innerHTML = "好";
}
cView.Utils.setChild(
nodeControl
,"display"
,nodeLike
);
};
function initLikes(){
cView.Common.genNodes(template).forEach(function(node){
nodesT[node.classList[0]] = node;
});
cView["addons-like-comm"] = handlers;
/*
if(typeof cView.contexts[domain] === "undefined") return;
var genCmt = cView.Drawer.genComment;
cView.Drawer.genComment = function(comment){
var nodeComment = genCmt.call(this, comment);
if (this.domain == domain) setControls(nodeComment);
return nodeComment;
}
var arrCmts = Object.keys(cView.contexts[domain].gComments);
if (!arrCmts.length) return;
arrCmts.forEach(function(id){
node = cView.doc.getElementById(domain+"-cmt-"+id);
if(node)setControls( node);
});
*/
var cmts = new Object();
var nodesCmt = cView.doc.getElementsByClassName("comment");
for(var idx = 0; idx < nodesCmt.length; idx++){
if( nodesCmt[idx].classList.contains("comments-load") )
continue;
var domain = nodesCmt[idx].domain;
if(!Array.isArray(cmts[domain]))cmts[domain] = new Array();
cmts[domain].push(nodesCmt[idx]);
}
loadLikes(cmts);
}
function loadLikes(cmts) {
var likeApi = {
"FreeFeed":function (context, arrCmts){
arrCmts.forEach(function(id){
var commentId = context.domain + "-cmt-" + id;
var cmt = context.gComments[id];
var nodeCmt = document.getElementById(commentId);
if(nodeCmt){
apply({ "id":id
,"likes":(cmt.likes == ""?0:cmt.likes)
,"my_likes":(cmt.hasOwnLike == true?"1":"0")
}
,nodeCmt
);
}
});
}
,"Mokum": function (context, arrCmts){
arrCmts.forEach(function(id){
var commentId = context.domain + "-cmt-" + id;
var cmt = context.gComments[id];
var nodeCmt = document.getElementById(commentId);
var cmtCount = ( typeof cmt.clikes_count !== "undefined" ) ?
cmt.clikes_count : (Array.isArray(cmt.clikes)?cmt.clikes.length:0);
if(nodeCmt && cmtCount){
apply({ "id":id
,"likes":cmtCount
,"my_likes":(
(typeof cmt.user_liked !== "undefined")
&& cmt.user_liked ?"1":"0"
)
}
,nodeCmt
);
}
});
}
}
Object.keys(cmts).forEach(function(domain){
var context = cView.contexts[domain];
if(typeof context === "undefined") {
console.log("Something went wrong. Unknown domain:", domain);
return;
}
likeApi[context.api.name](context, cmts[domain].map(function(node){
setControls(node);
return node.rawId;
}));
});
}
return function(cV){
return {
"run": function (){
cView = cV;
initLikes();
window.addEventListener("newNode",cView["addons-like-comm"].evtNewNode);
window.addEventListener("updNode",cView["addons-like-comm"].evtUpdNode);
window.addEventListener("evtCLikeMokum",cView["addons-like-comm"].evtCLikeMokum);
return cView.Utils._Promise.resolve();
}
,"settings":function(){return cView.doc.createElement("span");}
}
};
});
<file_sep>var icecream = require('./vanilla_srv.js');
http.createServer(icecream).lisen(3334);
<file_sep>var process = require("process");
var webpack = require("webpack");
var request = require("then-request");
var fs = require("fs");
var Promise = require("promise");
var write = Promise.denodeify(fs.writeFile);
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
var WebpackBeforeBuildPlugin = require('before-build-webpack');
var build = process.env["___BUILD___"] || "unstable";
build = "\"" + build + "\"";
// "https://cdn.rawgit.com/FortAwesome/Font-Awesome/blob/master/src/icons.yml";
module.exports = {
"target":"web"
,"mode": "none"
,performance: { hints: false }
,"entry":{
"vanilla":"./browser.js"
,"expanded":"./expandedcss.js"
,"compact":"./compactcss.js"
}
,"output":{
"publicPath": "./"
,"path": __dirname
,"filename":"[name].js"
}
,"plugins":[
new webpack.DefinePlugin({
"___BUILD___":build
})
,new MiniCssExtractPlugin({"filename":"[name].css"})
,new WebpackBeforeBuildPlugin(function(compiler, callback) {
var icons = request("GET", "https://cdn.rawgit.com/FortAwesome/Font-Awesome/4722e3ea/src/icons.yml").then(function(res){
return write("icons.yml", res.getBody(), "utf8");
}).then(()=>{console.log("icos")});
var tlds = require("./loadtlds").then(()=>{console.log("tlds")});
Promise.all([tlds, icons]).then(()=>{console.log("success"); callback();});
}
/* , ['run', 'watch-run', 'done']*/
)
]
,"module": {
"rules": [
/* {
"test": /\.json$/
,"use":[ {"loader": "compact-json-loader"}]
},*/{
"test": /\.css$/
,"use":[ { "loader": MiniCssExtractPlugin.loader}
,{ "loader": "css-loader"}
/*,{ "loader": "postcss-loader"
, "options": { parser: 'sugarss',
plugins: {
'postcss-import': {},
'postcss-preset-env': {},
'cssnano': {}
}
}
}*/
]
},{
test: /\.yml$/
,use: 'yml-loader'
}
]
}
/*
,"postcss": function () {
return [require('autoprefixer'), require('precss')];
}
*/
};
<file_sep>"use strict";
define("./addons/linkcups",["../utils"],function(utils){
var cView;
var fHide = false;
function linkCups (nodePost){
var cmtsHC = nodePost.getElementsByClassName("comment");
var loadIdx = cmtsHC.length;
var idx;
for(idx = 0; idx < cmtsHC.length; idx++){
if(cmtsHC[idx].classList.contains("comments-load")){
loadIdx = idx;
break;
}
}
idx = cmtsHC.length;
while(idx--){
if( (cmtsHC[idx].hidden === true )|| (cmtsHC[idx].cups === true)) continue;
cmtsHC[idx].cups = true;
var cups = new Object();
var content = cmtsHC[idx].getElementsByClassName("long-text")[0];
if(typeof content === "undefined") continue;
var matches = content.innerHTML.match(/[\^\u2191]+/g);
if(Array.isArray(matches))matches.forEach(function(match){
var target = idx-match.length;
if( (target < 0 )||( (idx > loadIdx)&&( target <= loadIdx) ))
return;
if(cmtsHC[target].hidden){
if(fHide) cmtsHC[idx].hidden = true;
return;
}
cups[match] = cmtsHC[target];
var re = new RegExp("(^|[^\\^\\u2191])("
+match.replace(/\^/g,"\\x5e")
+")(?![\\^\\u2191])"
,"g"
);
content.innerHTML = content.innerHTML.replace(re
,"$1<a class=\"cups_"
+match.length
+"\">$2</a>"
);
});
Object.keys(cups).forEach(function(cup){
var spans = cmtsHC[idx].getElementsByClassName("cups_"+ cup.length);
for(var s = 0; s < spans.length; s++)
addHighlightEvts(spans[s],cups[cup]);
});
}
}
function addHighlightEvts (host, target){
function on(){host.classList.add("highlighted");target.classList.add("highlighted");}
function off(){host.classList.remove("highlighted");target.classList.remove("highlighted");}
host.addEventListener("mouseover",on );
host.addEventListener("mouseout", off);
host.addEventListener("click",function(){
on();
host.removeEventListener("mouseout", off);
setTimeout(function(){host.addEventListener("mouseout", off);off();} , 1000);
window.scroll(0,target.offsetTop);
});
}
var handlers = {
"evtNewNode":function(e){
var arrNodes = e.detail;
if(!arrNodes)return;
var posts = new Object();
arrNodes = Array.isArray(arrNodes)?arrNodes:[arrNodes];
arrNodes.forEach(function(node){
switch(node.classList[0]){
case "post":
posts[node.id] = node;
break;
case "comment":
var post = node.getNode(["p","post"]);
posts[post.id] = post;
break;
}
});
Object.keys(posts).forEach(function(id){linkCups(posts[id])});
}
,"evtUpdNode":function(e){
var node = e.detail;
if(!node||(node.classList[0] !== "comment"))
return;
node.cups = false;
linkCups(node.getNode(["p","post"]));
}
}
return function(cV){
cView = cV;
cView["addons-linkcups"] = handlers;
fHide = JSON.parse(cView.localStorage.getItem("addons-linkcups-hide"));
return {
"run": function (){
var nodesPosts = document.getElementsByClassName("post");
for ( var idx = 0; idx < nodesPosts.length; idx++)
linkCups(nodesPosts[idx]);
window.addEventListener("newNode", handlers.evtNewNode);
window.addEventListener("updNode", handlers.evtUpdNode);
return utils._Promise.resolve();
}
,"settings":function(){return cView.doc.createElement("span");}
}
};
});
<file_sep>"use strict";
define("RtHandler", [], function(){
function likeCmt(data, context){
var that = this;
var cView = document.cView;
data.users.forEach(cView.Common.addUser,context);
context.gComments[data.comments.id] = data.comments;
var commentId = context.domain+"-cmt-"+ data.comments.id;
var nodeComment = document.getElementById(commentId);
if (nodeComment)
window.dispatchEvent(new CustomEvent("updNode", {"detail":nodeComment}));
}
var RtHandler = function (bump){
var that = this;
var cView = document.cView;
var rtParams = cView.localStorage.getItem("rt_params");
if(typeof bump !== "undefined") that.bump = bump;
if( rtParams ){
var oRTparams = JSON.parse(rtParams);
that.bumpCooldown = oRTparams["rt-bump-cd"]*60000;
that.bumpInterval = oRTparams["rt-bump-int"]*60000;
that.bumpDelay = oRTparams["rt-bump-d"]*60000;
}
if(typeof cView.bumpIntervalId !== "undefined" ) clearInterval(cView.bumpIntervalId);
if(that.bump) cView.bumpIntervalId = setInterval(function(){that.chkBumps();}, that.bumpInterval);
};
RtHandler.prototype = {
constructor: RtHandler
,bumpCooldown: 1200000
,bumpInterval: 60000
,bumpDelay: 0
,timeGrow: 1000
,bump: 0
,insertSmooth: function(node, nodePos, host){
var that = this;
var cView = document.cView;
var victim = document.getElementById(node.id);
if(typeof host === "undefined" )host = document.posts;
if(victim) victim.parentNode.removeChild(victim);
if(!nodePos)host.appendChild(node);
else nodePos.parentNode.insertBefore(node,nodePos);
if(["metapost", "post"].indexOf(node.className) != -1)
cView.Drawer.regenHides();
cView.Drawer.applyReadMore(node);
/*
setTimeout(function(){
node.style.height = height;
node.style.opacity = 1;
setTimeout(function(){
node.style.height = "auto";
node.style.overflow = "unset";
} , that.timeGrow);
}, 1);
if(document.getElementsByClassName("posts").length == 0){
console.log("%s, %s",node.id, nodePos.id);
console.log( cView.posts);
throw "Same shit again";
}
*/
return node;
}
,setBumpCooldown: function(cooldown){
var that = this;
var cView = document.cView;
that.bumpCooldown = cooldown;
clearInterval(cView.bumpIntervalId);
if(that.bumpCooldown && that.bumpInterval ) cView.bumpIntervalId = setInterval(function(){that.chkBumps}, that.bumpInterval);
}
,chkBumps: function(){
var that = this;
var cView = document.cView;
if(!Array.isArray(cView.bumps))cView.bumps = new Array();
cView.bumps.forEach(that.bumpPost, that);
cView.bumps = new Array();
}
,unshiftPost: function(data, context){
var that = this;
var cView = document.cView;
if(cView.skip)return;
if (context.gMe && Array.isArray(context.gMe.users.banIds)
&& (context.gMe.users.banIds.indexOf(data.posts.createdBy) > -1))
return;
cView.Common.loadGlobals(data, context);
data.posts.domain = context.domain;
data.posts.src = "rt";
var nodePost = manageMeta(cView.Drawer.genPost(data.posts));
if(nodePost.classList[0] == "metapost" ){
if(!nodePost.isHidden)this.bumpPost(nodePost);
} else {
cView.posts.unshift({
"hidden":nodePost.rawData.isHidden
,"data":nodePost.rawData
});
cView.Drawer.regenHides();
if (!nodePost.rawData.isHidden)
cView.Utils.unscroll.call(that
,that.insertSmooth
,nodePost
,document.posts.firstChild
);
}
window.dispatchEvent(new CustomEvent("newNode", {"detail":nodePost}));
function manageMeta(nodePost){
nodePost.rawData.sign = cView.hasher.of(nodePost.rawData.body);
if(cView.posts.some(function(a){
if((typeof a.data.id !== "undefined")
&& (a.data.id == nodePost.rawData.id))
return true;
else return false;
}))return nodePost;
if (nodePost.rawData.body.length < cView.minBody)
return nodePost;
var targetMeta = cView.posts.find(function(a){
if((typeof a.data.dups!== "undefined")
&&a.data.dups.some( function(dup){return dup.id == nodePost.rawData.id;}))
return true;
else return false;
});
if(typeof targetMeta !== "undefined")
targetMeta.data.dups = targetMeta.data.dups.filter(function(dup){
return dup.id != nodePost.rawData.id;
});
else {
var targetMeta = cView.posts.find(function(a){
if (Math.abs(a.data.createdAt-nodePost.rawData.createdAt)>48*3600*1000)
return false;
return cView.hasher.similarity(
a.data.sign
, nodePost.rawData.sign
) > cView.threshold;
});
}
if(typeof targetMeta === "undefined") return nodePost;
var oldNode = null;
if(targetMeta.data.type == "metapost"){
oldNode = document.getElementById(
targetMeta.data.dups[0].domain
+"-post-"
+targetMeta.data.dups[0].id
).parentNode;
}else {
targetMeta.data = cView.Common.metapost([targetMeta.data]);
oldNode = document.getElementById(
targetMeta.data.dups[0].domain
+"-post-"
+targetMeta.data.dups[0].id
);
}
targetMeta.data.dups.push(nodePost.rawData);
if(targetMeta.hidden){
nodePost.isHidden = true;
return nodePost;
}
var host = oldNode.parentNode;
var dummy = document.createElement("div");
var newNode = nodePost;
host.insertBefore(dummy,oldNode );
var posts = targetMeta.data.dups.map(function(post){
return document.getElementById(
post.domain
+ "-post-"
+ post.id
);
}).filter(function(node){return node;}).concat(nodePost)
host.removeChild(oldNode);
nodePost = cView.Drawer.makeMetapost( posts);
host.replaceChild(nodePost, dummy);
cView.Common.markMetaMenu(newNode);
return nodePost;
}
}
,bumpPost: function(nodePost){
var cView = document.cView;
if(cView.skip || (nodePost.rawData.idx === 0))return;
var that = this;
if(nodePost.rtCtrl.isBeenCommented)
nodePost.rtCtrl.bumpLater = function(){ that.bumpPost(nodePost);}
else {
var nodeParent = nodePost.parentNode;
if(nodeParent&&(nodeParent.className == "metapost")){
nodePost = nodeParent;
nodeParent = nodePost.parentNode;
}
var postInfo = cView.posts.splice(nodePost.rawData.idx,1);
cView.posts.unshift(postInfo[0]);
cView.Utils.unscroll.call(that
,that.insertSmooth
,nodePost
,nodeParent?nodeParent.firstChild:null
);
}
}
,injectPost: function(id, context){
var that = this;
var cView = document.cView;
if(cView.skip)return;
context.api.getPost(context.token, "posts/" + id /*, ["comments"]*/).then(function(data){
that.unshiftPost(data,context);
});
}
,"comment:new": function(data, context){
var that = this;
var cView = document.cView;
if (context.gMe && Array.isArray(context.gMe.users.banIds)
&& (context.gMe.users.banIds.indexOf(data.comments.createdBy) > -1))
return;
var commentId = context.domain + "-cmt-" +data.comments.id;
var postId = context.domain+"-post-" +data.comments.postId;
var nodePost = document.getElementById(postId);
var nodeComment;
data.users.forEach(cView.Common.addUser,context);
if(nodePost){
context.gComments[data.comments.id] = data.comments;
if(!Array.isArray( nodePost.rawData.comments))
nodePost.rawData.comments = new Array();
nodePost.rawData.comments.push(data.comments.id);
if(!document.getElementById(commentId))
nodeComment = cView.Utils.unscroll(function(){
var nodeComment = that.insertSmooth(
cView.Drawer.genComment.call(context, data.comments)
,null
,nodePost.cNodes["post-body"].cNodes["comments"]
);
cView.Drawer.applyReadMore(nodeComment);
nodePost.hidden |= cView.Common.chkBlocked(nodePost.rawData);
return nodeComment;
});
else return;
if (that.bump && ( (nodePost.rawData.updatedAt*1 + that.bumpCooldown) < Date.now())){
if(!Array.isArray(cView.bumps))cView.bumps = new Array();
setTimeout(function(){ cView.bumps.push(nodePost)},that.bumpDelay+1);
}
nodePost.rawData.updatedAt = Date.now();
cView.Common.markMetaMenu(nodePost);
if(nodePost.getElementsByClassName("comment").length>4)
nodePost.getNode(["c","post-body"],["c","many-cmts-ctrl"]).hidden = false;
window.dispatchEvent(new CustomEvent("newNode", {"detail":nodeComment}));
}else that.injectPost(data.comments.postId, context);
}
,"comment:update": function(data, context){
var cView = document.cView;
var commentId = context.domain+"-cmt-"+ data.comments.id;
var postId = context.domain+"-post-"+data.comments.postId;
context.gComments[data.comments.id] = data.comments;
var nodeComment = document.getElementById(commentId);
if (nodeComment){
var newComment = cView.Drawer.genComment.call(context, data.comments);
cView.Utils.unscroll(function(){
var nodePost = document.getElementById(postId);
nodeComment.parentNode.replaceChild( newComment , nodeComment);
cView.Drawer.applyReadMore( newComment );
cView.Common.markMetaMenu(nodePost);
return newComment;
});
window.dispatchEvent(new CustomEvent("updNode", {"detail":newComment}));
}
}
,"comment:destroy": function(data, context){
var cView = document.cView;
if(typeof context.gComments[data.commentId] !== "undefined")delete context.gComments[data.commentId];
var postId = context.domain+"-post-" +data.postId;
var commentId = context.domain+"-cmt-" +data.commentId;
var nodePost = document.getElementById(postId);
if(!nodePost)return;
if((typeof nodePost.rawData.comments !== "undefined")
&&(nodePost.rawData.comments.indexOf(commentId) > -1))
nodePost.rawData.comments.splice(nodePost.rawData.comments.indexOf(commentId),1);
var nodeComment = document.getElementById(commentId);
if (nodeComment) cView.Utils.unscroll(function(){
nodeComment.parentNode.removeChild(nodeComment);
cView.Common.markMetaMenu(nodePost);
nodePost.hidden |= cView.Common.chkBlocked(nodePost.rawData);
return nodeComment.parentNode;
});
}
,"comment_like:new": likeCmt
,"comment_like:remove": likeCmt
,"like:new": function(data, context){
var that = this;
var cView = document.cView;
if (context.gMe && Array.isArray(context.gMe.users.banIds)
&& (context.gMe.users.banIds.indexOf(data.users.id) > -1))
return;
cView.Common.addUser.call(context, data.users);
var postId = context.domain+"-post-" +data.meta.postId;
var nodePost = document.getElementById(postId);
if(nodePost){
if (!Array.isArray(nodePost.rawData.likes)) nodePost.rawData.likes = new Array();
if (nodePost.rawData.likes.indexOf(data.users.id) > -1) return;
nodePost.rawData.likes.unshift(data.users.id);
cView.Utils.unscroll(function(){
cView.Drawer.genLikes(nodePost);
nodePost.rawData.updatedAt = Date.now();
cView.Common.markMetaMenu(nodePost);
nodePost.hidden |= cView.Common.chkBlocked(nodePost.rawData);
return nodePost;
});
}else that.injectPost(data.meta.postId, context);
}
,"like:remove": function(data, context){
var cView = document.cView;
var postId = context.domain+"-post-" +data.meta.postId;
var nodePost = document.getElementById(postId);
if(nodePost && Array.isArray(nodePost.rawData.likes)
&& (nodePost.rawData.likes.indexOf(data.meta.userId) > -1 )) {
nodePost.rawData.likes.splice(nodePost.rawData.likes.indexOf(data.meta.userId), 1) ;
cView.Utils.unscroll(function(){
cView.Drawer.genLikes(nodePost);
nodePost.cNodes["post-body"].cNodes["post-info"].nodeLike.innerHTML = "Like";
nodePost.cNodes["post-body"].cNodes["post-info"].nodeLike.action = true ;
cView.Common.markMetaMenu(nodePost);
return nodePost;
});
nodePost.hidden |= cView.Common.chkBlocked(nodePost.rawData);
}
}
,"post:new" : function(data, context){
var that = this;
var cView = document.cView;
if(cView.skip)return;
var postId = context.domain+"-post-" +data.posts.id;
if(document.getElementById(postId)) return;
that.unshiftPost(data, context);
}
, "post:update" : function(data, context){
var cView = document.cView;
var postId = context.domain+"-post-" +data.posts.id;
var nodePost = document.getElementById(postId);
if(!nodePost) return;
var nodeCont = cView.doc.createElement("div");
nodePost.rawData.body = data.posts.body;
nodePost.rawData.postedTo = data.posts.postedTo;
nodePost.cNodes["post-body"].cNodes["title"].innerHTML = cView.Drawer.genTitle(nodePost);
nodePost.cNodes["post-body"].cNodes["title"].className = "title";
nodeCont.words = context.digestText(data.posts.body);
nodeCont.className = "post-cont long-text";
nodeCont.dir = "auto";
cView.Utils.setChild(nodePost.cNodes["post-body"], "post-cont", nodeCont);
delete nodeCont.isUnfolded;
cView.Utils.unscroll(function(){
cView.Drawer.applyReadMore( nodeCont);
cView.Common.markMetaMenu(nodePost);
nodePost.hidden |= cView.Common.chkBlocked(nodePost.rawData);
return nodePost;
});
window.dispatchEvent(new CustomEvent("updNode", {"detail":nodePost}));
}
, "post:destroy" : function(data, context){
var cView = document.cView;
var postId = context.domain+"-post-" +data.meta.postId;
var victim = document.getElementById(postId);
if(!victim) return;
var host = victim.parentNode;
if(host.classList[0] == "metapost"){
cView.Utils.unscroll(function(){
host.removeChild(victim);
cView.Drawer.regenMetapost(host);
return host;
});
var metapostData = cView.posts[victim.rawData.idx].data;
metapostData.dups = metapostData.dups.filter(function(dup){
return dup.id != victim.rawData.id;
});
if (metapostData.dups.length == 1)
cView.posts[victim.rawData.idx].data = metapostData.dups[0];
}else{
var dummy = document.createElement("div");
cView.Utils.unscroll(function(){
victim.parentNode.replaceChild(dummy, victim);
return dummy;
});
dummy.parentNode.removeChild(dummy);
cView.posts.splice(victim.rawData.idx,1);
}
}
, "post:hide" : function(data, context){
var cView = document.cView;
var postId = context.domain+"-post-" +data.meta.postId;
var nodePost = document.getElementById(postId);
if(!nodePost) return;
cView.Actions.doHide(nodePost, true, "rt");
}
, "post:unhide" : function(data, context){
var cView = document.cView;
var postId = context.domain+"-post-" +data.meta.postId;
var nodePost = document.getElementById(postId);
if(!nodePost)
cView.posts.forEach(function (item){
if (item.hidden && (item.data.id == data.meta.postId))
nodePost = cView.Drawer.genPost(item.data);
});
if (nodePost) cView.Actions.doHide(nodePost, false, "rt");
}
, "user:update" : function(data, context){
var cView = document.cView;
var user = context.logins[data.user.id].data.users;
Object.keys(data.user).forEach(function(key){ user[key] = data.user[key];});
cView.Common.regenCounters();
}
}
return RtHandler;
});
<file_sep>VERSION = $(shell git describe --tags --always)
BUILD_ENV ?= stable
IMAGE = freefeed/vanilla-$(BUILD_ENV)
image:
docker build --build-arg BUILD_ENV=$(BUILD_ENV) --build-arg VERSION=$(VERSION) -t $(IMAGE):$(VERSION) .
latest: image
@docker tag $(IMAGE):$(VERSION) $(IMAGE):latest
push:
@docker push $(IMAGE):$(VERSION)
push-latest:
@docker push $(IMAGE):latest
.PHONY: image latest push push-latest
<file_sep>"use strict";
var gRoutes = require("./routes.json");
function is(val){return (typeof val !== "undefined")&&(val != null);};
var chk = {
"token":function(contexts){
Object.keys(contexts).forEach(function(domain){
if (!contexts[domain].token)
delete contexts[domain];
});
return Object.keys(contexts).length?null:"token";
}
,"leadContext":function(contexts){
if (Object.keys(contexts).length > 1){
var leadContext = new Object();
leadContext[gConfig.leadDomain] = contexts[gConfig.leadDomain];
contexts = leadContext;
}
return null;
}
}
function some(_Promise,arr ){
return new _Promise(function(resolve, reject){
var count = arr.length;
var failed = true;
if(!count)resolve();
var reses = new Array(count);
var failes = new Array(count);
function alldone(ok, data,idx){
if (ok) {
failed = false;
reses[idx] = data;
}else failes[idx] = data;
if (--count)return;
(!failed)?resolve(reses):reject(failes);
}
arr.forEach(function(item, idx){
function success(res){alldone(true, res,idx);};
function fail(res){alldone(false, res ,idx);};
if( typeof item.then !== "function")item = _Promise.resolve(item);
item.then(success, fail);
});
});
}
function mixedTimelines (cView, contexts, prAllT,prAllC){
return cView.Utils._Promise.all([prAllT,prAllC]).then( function (res){
var domains = Object.keys(contexts);
var posts = new Array();
cView.doc.getElementById("loading-msg").innerHTML = "Building page";
res[0].forEach(function(data,idx){
if(typeof data === "undefined" )return;
var context = contexts[domains[idx]];
cView.Common.loadGlobals( data, context);
if(typeof data.posts !== "undefined" ){
data.posts.forEach(function(post, pos){
post.domain = domains[idx];
post.initPos = pos;
});
posts = posts.concat(data.posts);
}
if(is(data.timelines)&& is(data.timelines.id)){
context.timelineId = data.timelines.id;
if(JSON.parse(cView.localStorage.getItem("rt")))
context.rtSubTimeline(data);
}
});
if(!(cView.noMetapost === true))posts = undup(cView, posts);
posts.sort(function(a,b){return b.bumpedAt - a.bumpedAt;});
return [posts,contexts];
});
}
function undup (cView, posts){
posts.forEach(function(post,idx){
post.sign = cView.hasher.of(post.body);
if (is(post.comments) && post.comments.length){
var commentId = post.comments[post.comments.length-1];
post.bumpedAt = cView.contexts[post.domain].gComments[commentId].createdAt;
}else post.bumpedAt = post.createdAt;
});
//var hashes = posts.map(function(post){return hash.of(post.body);});
var duplicates = new Object();
for(var idx = 0; idx < posts.length-1; idx++){
if(
posts[idx].body.length < cView.minBody
||(posts[idx].body.split(cView.autolinker.hashtag.regex).join(" ").trim() == "" )
) continue;
for(var v = idx+1; v < posts.length; v++){
if(
(posts[v].body.length < cView.minBody)
||(Math.abs(posts[idx].createdAt-posts[v].createdAt)>48*3600*1000)
||(posts[v].body.split(cView.autolinker.hashtag.regex).join(" ").trim() == "" )
) continue;
if( cView.hasher.similarity(posts[idx].sign,posts[v].sign)>cView.threshold){
var dups;
if (is(duplicates[idx]))dups = duplicates[idx];
else if (is(duplicates[v]))dups = duplicates[v];
else dups = new Object();
dups[idx] = true;
dups[v] = true;
duplicates[idx] = duplicates[v] = dups;
}
}
}
Object.keys(duplicates).forEach(function(idx){
idx = parseInt(idx);
if (!is(duplicates[idx]))return;
posts.push(
cView.Common.metapost(
Object.keys( duplicates[idx]).map(function(v){
return posts[parseInt(v)];
}).filter(function(post){return post != null;})
)
);
Object.keys(duplicates[idx])
.forEach(function(v){
v = parseInt(v);
delete duplicates[v];
posts[v] = null;
});
});
return posts.filter(function(post){return post != null;});
}
define("./router",[],function(){
function _Router(v){
this.cView = v;
};
_Router.prototype = {
"route":function(contexts, path){
var cView = this.cView;
if (cView.doc.title == "") cView.doc.title = "Feeds";
if (path.indexOf("#") != -1 )
path = path.substr(0,path.indexOf("#"));
var arrPath = path.split("/").filter(function(str){return str != "";});
var step = gRoutes;
for(var idx = 0; idx < arrPath.length; idx++){
var txtStep = arrPath[idx];
if (is(step.req) && chk[step.req](contexts))
return cView.Utils._Promise.reject(chk[step.req](contexts));
if(is(step.reroute))
return cView[step.reroute[0]][step.reroute[1]](contexts, path);
if (is(step.vals) && is(step.vals[txtStep]))
step = step.vals[txtStep];
else if (is(step.default)) step = step.default;
}
if (is(step.default)) step = step.default;
if(is(step.dest)){
cView.doc.getElementById("loading-msg").innerHTML = "Loading content";
if((step.dest.length == 3)&& chk[step.dest[2]](contexts) )
return cView.Utils._Promise.reject(chk[step.dest[2]](contexts));
return cView[step.dest[0]][step.dest[1]](contexts, path);
}
return cView.Utils._Promise.reject();
}
,"directs":function(contexts){
var cView = this.cView;
return new cView.Utils._Promise(function(resolve,reject){
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
var body = cView.doc.getElementById("container");
body.appendChild(nodeAddPost);
var domains = Object.keys(contexts);
var context = contexts[gConfig.leadDomain];
if (!is(context))context = contexts[domains[0]];
context.p.then(function () {
cView.Drawer.genDirectTo(nodeAddPost
,context.gMe);
});
cView.Router.timeline(contexts, "filter/directs").then(function(){
body.cNodes["pagetitle"].innerHTML = "Direct messages";
cView.doc.title += ": Direct messages";
if (!cView.skip) domains.forEach(function(domain){
var context = contexts[domain];
cView.contexts[domain].gMe.users.unreadDirectsNumber = 0;
context.api.resetDirectsCount(context.token);
});
window.dispatchEvent(new CustomEvent("whoamiUpdated"));
resolve();
},reject);
});
}
,"routeContext":function(contexts, path){
var cView = this.cView;
var arrPath = path.split("/").filter(function(str){return str != "";});
var singleContext = new Object();
singleContext[arrPath[1]] = contexts[arrPath[1]];
cView.doc.title = arrPath[1]
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
var newPath = arrPath.slice(2).join("/");
return this.route(singleContext, (newPath != "")?newPath:"home");
}
,"routeHome":function(contexts){
var cView = this.cView;
return new cView.Utils._Promise(function(resolve,reject){
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
var body = cView.doc.getElementById("container");
body.appendChild(nodeAddPost);
var domains = Object.keys(contexts);
var mainContext = (domains.indexOf(gConfig.leadDomain) != -1)?
contexts[gConfig.leadDomain]:contexts[domains[0]];
mainContext.p.then(function () {
cView.Drawer.genPostTo(nodeAddPost
,null
,mainContext.gMe);
});
cView.Router.timeline(contexts, "home" ).then(resolve,reject);
});
}
,"routeMe": function(contexts, path){
var cView = this.cView;
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
var domains = Object.keys(contexts);
var body = cView.doc.getElementById("container");
var mainContext = (domains.indexOf(gConfig.leadDomain) != -1)?
contexts[gConfig.leadDomain]:contexts[domains[0]];
mainContext.p.then(function () {
cView.Drawer.genPostTo(nodeAddPost
,null
,mainContext.gMe);
});
body.appendChild(nodeAddPost);
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = path;
cView.doc.title +=": " + path
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
var prContxt = new Array();
var prConts = new Array();
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api.getTimeline(
context.token
,context.gMe.users.username
,cView.skip
));
});
var prAllT = cView.Utils._Promise.all(prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
return mixedTimelines (cView, contexts, prAllT,prAllC)
.then(function(mix){
cView.Drawer.drawTimeline(mix[0],mix[1]);
cView.Drawer.updateReqs();
});
}
,"routeComments": function(contexts, path){
var cView = this.cView;
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
var domains = Object.keys(contexts);
var body = cView.doc.getElementById("container");
var mainContext = (domains.indexOf(gConfig.leadDomain) != -1)?
contexts[gConfig.leadDomain]:contexts[domains[0]];
mainContext.p.then(function () {
cView.Drawer.genPostTo(nodeAddPost
,null
,mainContext.gMe);
});
body.appendChild(nodeAddPost);
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = path;
cView.doc.title +=": " + path
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
var prContxt = new Array();
var prConts = new Array();
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api.getTimeline(
context.token
,context.gMe.users.username+"/comments"
,cView.skip
));
});
var prAllT = cView.Utils._Promise.all(prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
return mixedTimelines (cView, contexts, prAllT,prAllC)
.then(function(mix){
cView.Drawer.drawTimeline(mix[0],mix[1]);
cView.Drawer.updateReqs();
});
}
,"subscribers":function(contexts, path){
var cView = this.cView;
return cView.Router.subs(contexts, path, cView.Drawer.drawSubs);
}
,"subscriptions":function(contexts, path){
var cView = this.cView;
return cView.Router.subs(contexts, path, cView.Drawer.drawFriends);
}
,"subs":function(contexts, path, fn){
var cView = this.cView;
var context = contexts[Object.keys(contexts)[0]];
return cView.Utils._Promise.all([ context.api.getSubs(context.token,path),context.p ])
.then(function(res){
cView.Common.loadGlobals(res[0], context);
var body = cView.doc.getElementById("container");
body.cNodes["pagetitle"].innerHTML = path;
cView.doc.title = "@"+path.split("/")[0]+ "'s " + path.split("/")[1] + " ("+context.domain+")";
fn.call(cView, res[0],context);
});
}
,"groups":function(contexts, path){
var cView = this.cView;
return cView.Utils._Promise.all(Object.keys(contexts).map(function(domain){
return contexts[domain].p;
})).then(function(res){
var body = cView.doc.getElementById("container");
body.cNodes["pagetitle"].innerHTML = path;
cView.doc.title = "My groups";
cView.Drawer.drawGroups();
});
}
,"unmixed":function(contexts, path){
var cView = this.cView;
return new cView.Utils._Promise(function(resolve,reject){
var body = cView.doc.getElementById("container");
var nodeDummy = body.appendChild(cView.doc.createElement("div"));
var domains = Object.keys(contexts);
var domain = (domains.indexOf(gConfig.leadDomain) != -1)? gConfig.leadDomain :domains[0];
var cs = new Object();
cs[domain] = contexts[domain];
var context = cs[domain];
var username = path.split("/")[0];
cView.Router.timeline(cs, path).then(function(){
var feed = context.gUsers.byName[username];
cView.origin = feed.id;
if(feed.type == "user"){
cView.noBlocks = true;
var nodesPosts = cView.doc.getElementsByClassName("post");
for(var idx = 0; idx < nodesPosts.length; idx++){
nodesPosts[idx].hidden = false;
cView.Drawer.applyReadMore(nodesPosts[idx]);
}
}
//cView.Common.addUser.call(context, feed);
cView.doc.title = "@"+feed.username + ", a " + context.domain + " feed.";
cView.Utils.setChild(body, "details", cView.Drawer.genUserDetails(feed.username, context));
if (context.ids)
cView.Utils.setChild(body, "up-controls", cView.Drawer.genUpControls(feed));
var names = new Array();
context.ids.forEach( function(id){
names.push(context.gUsers[id].username);
});
if (names.indexOf(feed.username)!= -1) {
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
body.replaceChild(nodeAddPost, nodeDummy);
cView.Drawer.genPostTo(
nodeAddPost
,null
,context.logins[context.gUsers.byName[feed.username].id].data
);
}
if ((feed.type == "group") && feed.friend){
var nodeAddPost = cView.gNodes["new-post"].cloneAll();
body.replaceChild(nodeAddPost, nodeDummy);
cView.Drawer.genPostTo(
nodeAddPost
,feed.username
,context.gMe
);
}
resolve();
},reject);
});
}
,"singlePost":function(contexts,path){
var cView = this.cView;
cView.noBlocks = true;
var context = Object.keys(contexts).map(function(d){ return contexts[d];})[0];
return cView.Utils._Promise.all( [
context.api.getPost(context.token, path, ["comments"])
,context.p
]).then( function (res){
cView.doc.getElementById("loading-msg").innerHTML = "Building page";
cView.Common.loadGlobals(res[0], context);
var post = res[0].posts;
if(Array.isArray(post))post = post[0];
post.domain = context.domain;
cView.Drawer.drawPost(post,context);
if(JSON.parse(cView.localStorage.getItem("rt"))) context.rtSubPost(res[0]) ;
if(is(res[0].timelines))
context.timelineId = res[0].timelines.id;
});
}
,"routeSearch":function(contextsIn){
var cView = this.cView;
var search = cView.search.match(/qs=([^&]+)/);
var domains = new Array();
var reDomains = /d=([^&]+)/g;
var match = null;
while((match = reDomains.exec(cView.search)) !== null)
domains.push(match[1]);
if (!domains.length){
var arrSkipDomains = (new Array()).concat(JSON.parse(cView.localStorage.getItem("skip_domains")));
domains =Object.keys(contextsIn).filter(function(domain){
return arrSkipDomains.indexOf(domain) == -1;
});
}
if(!search){
cView.Drawer.drawSearch({"query":"","domains":domains});
return cView.Utils._Promise.resolve();
}
var contextsOut = new Object();
Object.keys(contextsIn).forEach(function(domain){
if(domains.indexOf(domain) != -1)
contextsOut[domain] = contextsIn[domain];
});
if(!Object.keys(contextsOut).length){
contextsOut = contextsIn;
domains = Object.keys(contextsIn);
}
return this.timeline(
contextsOut
,search[1]
,"getSearch"
).then(function(){
cView.Drawer.drawSearch({
"query":decodeURIComponent(search[1].replace(/\+/g, " "))
,"domains":domains
})
});
}
,"routeNotifications":function(contexts, path){
var cView = this.cView;
var prConts = new Array();
var prContxt = new Array();
var domains = Object.keys(contexts);
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api.getNotifications(context.token,cView.search, cView.skip));
});
var prAllT = some(cView.Utils._Promise, prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = path;
cView.doc.title +=": " + path;
return cView.Utils._Promise.all([prAllT,prAllC]).then( function (res){
cView.doc.getElementById("loading-msg").innerHTML = "Building page";
var isLast = res[0].reduce(function(total, curr){
if (typeof curr.isLastPage !== "undefined")
total &= curr.isLastPage;
return total;
}, true);
cView.Drawer.drawNotifications(
res[0].map(function(data,idx){
if(typeof data === "undefined" )return;
var context = contexts[domains[idx]];
cView.Common.loadGlobals( data, context);
if(typeof data.Notifications !== "undefined" ){
data.Notifications.context = context;
return data.Notifications;
}else return null;
}).filter(Boolean)
, isLast
);
cView.Drawer.updateReqs();
});
}
,"timeline":function(contexts, path, source ){
var cView = this.cView;
source = (typeof source !== "undefined")?source:"getTimeline";
var arrContent = new Array();
var prConts = new Array();
var prContxt = new Array();
var domains = Object.keys(contexts);
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api[source](context.token,path, cView.skip, cView.localStorage.getItem("friends-view")));
});
var prAllT = some(cView.Utils._Promise, prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = path;
cView.doc.title +=": " + path
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
return mixedTimelines(cView, contexts, prAllT,prAllC)
.then(function(mix){
cView.Drawer.drawTimeline(mix[0],mix[1]);
cView.Drawer.updateReqs();
});
}
,"routeSummary":function(contexts, path ){
var cView = this.cView;
var arrContent = new Array();
var prConts = new Array();
var prContxt = new Array();
var intervals = {"1":"day","7":"week","30":"month" };
var domains = Object.keys(contexts);
var summaryLookup = path.match(/(?:(\w+)\/)?summary(?:\/(\d+))?/);
var source = ((typeof summaryLookup[1] !== "undefined")?summaryLookup[1]:null);
var interval = ((typeof summaryLookup[2] !== "undefined")?summaryLookup[2]:"7");
cView.summarySource = source?source+"/":"";
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api.getSummary(context.token,source,interval));
});
var prAllT = some(cView.Utils._Promise, prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
return mixedTimelines(cView, contexts, prAllT,prAllC)
.then(function(mix){
var authorTitle = "";
if (source){
var context = mix[1][Object.keys(mix[1])[0]];
authorTitle = " — " + context.gUsers.byName[source].title;
}
var title = "Best of the " + intervals[interval]
+authorTitle;
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = title;
cView.doc.title +=": " + title.replace(/<.*>/g,"")
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
mix[0].sort(function(a,b){return a.initPos - b.initPos;});
cView.Drawer.drawSummary(mix[0],mix[1], interval);
cView.Drawer.updateReqs();
});
}
,"memories":function(contexts, path ){
var cView = this.cView;
var arrContent = new Array();
var prConts = new Array();
var prContxt = new Array();
var intervals = {"1":"day","7":"week","30":"month" };
var domains = Object.keys(contexts);
var summaryLookup = path.match(/(?:(\w+)\/)?memories(?:\/(\d+))/);
var source = ((typeof summaryLookup[1] !== "undefined")
?summaryLookup[1]:"home");
var interval = new Date(summaryLookup[2].replace(/(\d{4})(\d{2})(\d{2})/,"$1-$2-$3"));
domains.forEach(function(domain){
var context = contexts[domain];
prContxt.push(context.p);
prConts.push(context.api.getMemories(context.token,source,interval,cView.skip));
});
var prAllT = some(cView.Utils._Promise, prConts);
var prAllC = cView.Utils._Promise.all(prContxt);
return mixedTimelines(cView, contexts, prAllT,prAllC)
.then(function(mix){
var authorTitle = "";
if (source != "home"){
var context = mix[1][Object.keys(mix[1])[0]];
authorTitle = context.gUsers.byName[source].title;
}
var title = authorTitle + " memories: posts from " + interval.toLocaleDateString();
cView.doc.getElementById("container").cNodes["pagetitle"].innerHTML = title;
cView.doc.title +=": " + title.replace(/<.*>/g,"")
.replace("&","&")
.replace("<","<")
.replace(">",">") ;
mix[0].sort(function(a,b){return a.initPos - b.initPos;});
cView.Drawer.drawTimeline(mix[0],mix[1]);
cView.Drawer.updateReqs();
});
}
}
return _Router;
});
<file_sep>FROM node:12 as builder
ARG BUILD_ENV
ARG VERSION
ENV ___BUILD___="${BUILD_ENV}_${VERSION}"
ADD . /vanilla
WORKDIR /vanilla
RUN rm -rf node_modules && \
rm -f log/*.log && \
cp config/${BUILD_ENV}.json ./config.json && \
npm install && \
./node_modules/.bin/webpack --config config.js && \
./write_hash.sh
FROM scratch
COPY --from=builder /vanilla /var/www/vanilla
VOLUME /var/www/vanilla
<file_sep>"use strict";
function is(val){return typeof val !== "undefined";};
function goUnfolder(nodeImgAtt){
var host = nodeImgAtt.parentNode;
var total = 0;
var cView = document.cView;
for(var idx = 0; idx < nodeImgAtt.childNodes.length; idx++){
total += nodeImgAtt.childNodes[idx].t.w ;
var nodeImg = nodeImgAtt.childNodes[idx].img;
if(idx && (typeof nodeImg.src === "undefined")||(nodeImg.src == "") ) {
nodeImgAtt.childNodes[idx].hidden = false;
/*
nodeImg.addEventListener("load",function(){
cView.Utils.unscroll(function(){
nodeImg.style.height = "auto";
return nodeImgAtt;
});
});
*/
nodeImg.src = nodeImgAtt.childNodes[idx].url;
}
if (host.clientWidth < total) break;
total += nodeImgAtt.childNodes[idx].style["margin-left"]*(!!idx);
}
if ((host.clientWidth < total)&&(nodeImgAtt.childNodes.length > 1) )
host.cNodes["atts-unfold"].hidden = false;
}
define("./actions",[],function() {
function appendAttachment(nodeNewPost, name, file){
var cView = document.cView;
var nodeInput = nodeNewPost.getNode(["c","edit-buttons"], ["c","edit-buttons-upload"]);
nodeInput.disabled = true;
var host = nodeNewPost.getNode(["c","post-to"]);
var nodeSpinner = cView.doc.createElement("div");
var buttonPost = nodeNewPost.getElementsByClassName("edit-buttons-post")[0];
buttonPost.disabled = true;
host.buttonPost = buttonPost;
host.nodeInput = nodeInput;
host.nodeSpinner = nodeSpinner;
nodeSpinner.innerHTML = '<img src="'+gConfig.static+'throbber-100.gif">';
nodeNewPost.getNode(["c", "new-post-cont"],["c","attachments"]).appendChild(nodeSpinner);
if (typeof host.files === "undefined") host.files = new Array();
if (typeof host.attachs === "undefined") host.attachs = new Object();
host.files.push({
"name":name
,"file":file
,"timestamp":Date.now()
});
regenAttaches(host);
}
function regenAttaches(host){
var cView = document.cView;
if (typeof host.attachs === "undefined") return;
var nodesDest = host.childNodes;
var nodeInput = host.getNode(["p","new-post"], ["c","edit-buttons-upload"]);
delete host.attP;
var arrAttP = new Array();
for (var idx = 0; idx < nodesDest.length; idx++ )(function(domain, userid){
var context = cView.contexts[domain];
var fullId = domain +"-"+ userid;
if (typeof host.attachs[fullId] === "undefined")
host.attachs[fullId] = {
"arrP":[]
,"arrId":[]
,"timestamps":[]
}
host.files.forEach(function(oAttach){
if (host.attachs[fullId].timestamps.indexOf(oAttach.timestamp) == -1){
var token = context.logins[userid].token;
host.attachs[fullId].arrP.push(
context.api.sendAttachment(
token
,oAttach.file
,oAttach.name
).then(function(data){
var payload = data.attachments;
var attachments = Array.isArray(payload)?payload[0]:payload ;
var id = attachments.id;
host.attachs[fullId].arrId.push(id);
if (typeof host.nodeSpinner === "undefined") return data;
var nodeAtt = cView.doc.createElement("div");
nodeAtt.className = "att-img";
nodeAtt.innerHTML = '<a target="_blank" href="'
+attachments.url
+'" border=none ><img src="'
+attachments.thumbnailUrl
+'"></a>';
host.nodeSpinner.parentNode.replaceChild(nodeAtt, host.nodeSpinner);
delete host.nodeSpinner;
return data;
})
);
arrAttP = arrAttP.concat(host.attachs[fullId].arrP);
host.attachs[fullId].timestamps.push(oAttach.timestamp);
}
});
})(nodesDest[idx].domain, nodesDest[idx].userid);
host.attP = cView.Utils._Promise.all(arrAttP).then( function(data){
host.nodeInput.value = "";
host.nodeInput.disabled = false;
host.buttonPost.disabled = false;
return data;
},function(data){
host.nodeInput.value = "";
host.nodeInput.disabled = false;
host.buttonPost.disabled = false;
if (typeof host.nodeSpinner === "undefined")
delete host.nodeSpinner;
});
}
function _Actions(v){
this.cView = v;
};
_Actions.prototype = {
constructor:_Actions
/*
,"auth": function(){
var cView = document.cView;
cView.Utils.auth();
}
*/
,"newPost": function(e){
var cView = document.cView;
var textField = e.target.getNode(["p","new-post"],["c","new-post-cont"],["c","edit-txt-area"]);
if (textField.value == ""){
alert("you should provide some text");
return;
}
textField.disabled = true;
e.target.disabled = true;
var nodeSpinner = e.target.parentNode.appendChild(cView.gNodes["spinner"].cloneNode(true));
var postsTo = e.target.getNode(["p", "new-post"]).getElementsByClassName("new-post-to");
var arrPostsTo = new Array(postsTo.length);
var body = cView.Common.urlsToCanonical(textField.value);
for (var idx = 0; idx < postsTo.length; idx++)arrPostsTo[idx] = postsTo[idx];
var nodeError = e.target.parentNode.getElementsByClassName("msg-error")[0];
if(typeof nodeError !== "undefined") nodeError.parentNode.removeChild(nodeError);
cView.Utils._Promise.all(arrPostsTo.map(send)).then(function(res){
var nodeAtt = cView.doc.createElement("div");
var nodePostTo = e.target.getNode(["p", "new-post"],["c","post-to"]);
delete nodePostTo.attachs;
delete nodePostTo.files;
delete nodePostTo.attP;
nodeAtt.className = "attachments";
textField.parentNode.replaceChild(nodeAtt,
textField.parentNode.cNodes["attachments"]);
textField.parentNode.cNodes["attachments"] = nodeAtt;
textField.value = "";
textField.disabled = false;
e.target.disabled = false;
textField.style.height = "4em";
try{ e.target.parentNode.removeChild(nodeSpinner); }
catch(e){};
var arrNodes = new Array();
arrPostsTo.forEach(function(postTo,idx){
res[idx].posts.domain = postTo.domain;
var context = cView.contexts[postTo.domain];
cView.Common.loadGlobals(res[idx], context);
var nodePostId = [
context.domain
,"post"
,res[idx].posts.id
].join("-");
if(!cView.doc.getElementById(nodePostId)){
var nodePost = cView.doc.posts.insertBefore(
cView.Drawer.genPost(res[idx].posts)
, cView.doc.posts.childNodes[0]
)
cView.Drawer.applyReadMore(nodePost);
arrNodes.push(nodePost);
}
});
window.dispatchEvent(new CustomEvent("newNode", {"detail":arrNodes}));
var login;
if (cView.leadContext.gMe)
login = cView.leadContext.gMe;
else Object.keys(cView.contexts).some(function(domain){
return login = cView.contexts[domain].gMe;
});
cView.updPostTo(login, true);
cView.Drawer.regenHides();
} ,function(err){
textField.disabled = false;
e.target.disabled = false;
try{
e.target.parentNode.removeChild(nodeSpinner );
}catch(e){};
cView.Drawer.makeErrorMsg(err,e.target.parentNode);
});
function send(postTo){
var context = cView.contexts[postTo.domain];
var postdata = new Object();
postdata.meta = new Object();
postdata.post = new Object();
var input = postTo.getNode(["c","new-feed-input"],["c", "input"]);
var feed = input.value;
if((feed != "") && (typeof input.dest[feed] !== "undefined")
&& (postTo.feeds.indexOf(input.dest[feed]) == -1) ){
postTo.feeds.push(input.dest[feed]);
}
postdata.post.body = body;
postdata.meta.feeds = postTo.feeds ;
if(typeof postTo.parentNode.attachs !== "undefined")
postdata.post.attachments = postTo.parentNode.attachs[context.domain+"-"+postTo.userid].arrId;
return context.api.sendPost(
context.logins[postTo.userid].token
,postdata
,context.logins[postTo.userid].data.users.username
,postTo.destType
,context.timelineId
);
}
/* if(postTo.isPrivate){
oReq.open("post",matrix.cfg.srvurl+"post", true);
oReq.setRequestHeader("x-content-type", "post");
oReq.setRequestHeader("Content-type","text/plain");
oReq.onload = onload;
var payload = {
"feed":postTo.feeds[0],
"type":"post",
"author":cView.gMe.users.username,
"data":textField.value
};
matrix.sign(JSON.stringify(payload)).then(function(sign){
var token = matrix.mkOwnToken(sign);
if(!token) return console.log("Failed to make access token");
oReq.setRequestHeader("x-content-token", token);
post = matrix.encrypt(postTo.feeds,
JSON.stringify({"payload":payload,"sign":sign}));
oReq.setRequestHeader("Content-type","application/json");
oReq.send(JSON.stringify({"d":post}));
},function(){console.log("Failed to sign")});
}else*/{
}
}
,"attachmentCtrl": function(e){//TODO
appendAttachment(
e.target.getNode(["p","new-post"])
, e.target.value
, e.target.files[0]
);
}
,"editPost": function(e) {
var cView = document.cView;
var victim = e.target.getNode(["p","post"]);
var domain = victim.rawData.domain;
victim.classList.add("new-post");
var nodeBody = victim.cNodes["post-body"];
var nodeEdit = cView.Drawer.genEditNode(cView.Actions.postEditedPost,cView.Actions.cancelEditPost);
var textArea = nodeEdit.cNodes["edit-txt-area"];
victim.cNodes["add-sender"] = cView.doc.createElement("div");
var nodePostTo = cView.doc.createElement("div");
textArea.value = victim.rawData.body;
cView.Utils.setChild(nodeBody , "post-cont", nodeEdit);
cView.Utils.setChild(nodeBody , "title", nodePostTo);
victim.cNodes["post-to"] = nodePostTo;
victim.cNodes["edit-buttons"] = nodeEdit.cNodes["edit-buttons"];
nodeBody.feeds = victim.rawData.postedTo;
cView.Drawer.genPostTo(victim
,nodeBody.feeds.map(function(id){return cView.contexts[domain].gFeeds[id].user.username ;})
,cView.contexts[domain].logins[victim.rawData.createdBy].data
);
/*
nodeTo.domain = victim.rawData.domain ;
nodeTo.userid = victim.rawData.createdBy;
nodeBody.replaceChild(nodeTo , nodeBody.cNodes["title"]);
*/
if (textArea.scrollHeight > textArea.clientHeight)
textArea.style.height = textArea.scrollHeight + "px";
}
,"cancelEditPost": function(e){
var cView = document.cView;
var victim = e.target.getNode(["p","post"]);
var context = cView.contexts[victim.rawData.domain]
var postCNode = cView.doc.createElement("div");
postCNode.innerHTML = context.digestText(victim.rawData.body);
postCNode.className = "post-cont long-text";
postCNode.dir = "auto";
victim.cNodes["post-body"].replaceChild(postCNode,e.target.parentNode.parentNode );
victim.cNodes["post-body"].cNodes["post-cont"] = postCNode;
victim.cNodes["post-body"].cNodes["title"].innerHTML = cView.Drawer.genTitle(victim);
victim.cNodes["post-body"].cNodes["title"].className = "title";
cView.Drawer.applyReadMore(postCNode);
cView.cTxt = null;
}
,"postEditedPost": function(e){
var cView = document.cView;
var nodePost =e.target.getNode(["p","post"]);
var context = cView.contexts[nodePost.rawData.domain];
e.target.disabled = true;
var post = new Object();
post.createdAt = nodePost.rawData.createdAt;
post.createdBy = nodePost.rawData.createdBy;
post.updatedAt = Date.now();
post.attachments = nodePost.rawData.attachments;
var postdata = new Object();
postdata.post = post;
var textField = e.target.parentNode.parentNode.cNodes["edit-txt-area"];
textField.disabled = true;
e.target.parentNode.replaceChild(cView.gNodes["spinner"].cloneNode(true),e.target.parentNode.cNodes["edit-buttons-cancel"] );
var postTo = nodePost.getElementsByClassName("new-post-to")[0];
var input = postTo.getNode(["c","new-feed-input"],["c", "input"]);
var feed = input.value;
if((feed != "") && (typeof input.dest[feed] !== "undefined")
&& (postTo.feeds.indexOf(input.dest[feed]) == -1) ){
postTo.feeds.push(input.dest[feed]);
}
post.feeds = postTo.feeds ;
post.body = cView.Common.urlsToCanonical( textField.value);
context.api.editPost(
context.logins[nodePost.rawData.createdBy].token
,nodePost.rawData.id
,postdata
).then(function(res){
var post = res.posts;
var postCNode = cView.doc.createElement("div");
nodePost.rawData.body = post.body;
nodePost.rawData.postedTo = post.postedTo;
nodePost.cNodes["post-body"].cNodes["title"].innerHTML = cView.Drawer.genTitle(nodePost);
nodePost.cNodes["post-body"].cNodes["title"].className = "title";
/*
var cpost = matrix.decrypt(post.body);
if (typeof cpost.error === "undefined") {
cpost = JSON.parse(cpost);
post.body = cpost.payload.data;
nodePost.sign = cpost.sign;
}
*/
nodePost.cNodes["post-body"].replaceChild(postCNode,e.target.parentNode.parentNode );
nodePost.cNodes["post-body"].cNodes["post-cont"] = postCNode;
postCNode.innerHTML = context.digestText(post.body);
postCNode.className = "post-cont long-text";
postCNode.dir = "auto";
},function(err){
cView.Drawer.makeErrorMsg(err,textField.parentNode);
});
cView.cTxt = null;
/*
if(nodePost.isPrivate){
oReq.open("put",matrix.cfg.srvurl+"edit", true);
oReq.setRequestHeader("x-content-type", "post");
oReq.setRequestHeader("Content-type","application/json");
//oReq.onload = onload;
var payload = {
"feed":nodePost.feed,
"type":"post",
"author":cView.gMe.users.username,
"data":text
};
oReq.setRequestHeader("x-access-token", matrix.mkOwnToken(nodePost.sign));
matrix.sign(JSON.stringify(payload)).then(function(sign){
var token = matrix.mkOwnToken(sign);
if(!token) return console.log("Failed to make access token");
oReq.setRequestHeader("x-content-token", token);
oReq.setRequestHeader("x-content-id",nodePost.id);
post = matrix.encrypt(nodePost.feed,
JSON.stringify({"payload":payload,"sign":sign}));
oReq.send(JSON.stringify({"d":post}));
},function(){console.log("Failed to sign")});
}else
*/
}
,"deletePost": function(e){
var cView = document.cView;
var victim =e.target.getNode(["p", "post"]);
cView.Actions.deleteNode(victim, cView.Actions.doDeletePost);
}
,"doDeletePost": function(but){
var cView = document.cView;
var victim = but.node;
var context = cView.contexts[victim.rawData.domain];
but.parentNode.parentNode.removeChild(but.parentNode);
context.api.deletePost(
context.logins[victim.rawData.createdBy].token
,victim.rawData.id
).then(function(){
var host = victim.parentNode;
host.removeChild(victim);
if(host.className == "metapost"){
cView.Drawer.regenMetapost(host);
var metapostData = cView.posts[victim.rawData.idx].data;
metapostData.dups = metapostData.dups.filter(function(dup){
return dup.id != victim.rawData.id;
});
if (metapostData.dups.length == 1)
cView.posts[victim.rawData.idx].data = metapostData.dups[0];
} else cView.posts.splice(victim.rawData.idx,1);
cView.Drawer.regenHides();
}, function(err){
victim.hidden = false;
cView.Drawer.makeErrorMsg(err,victim);
});/*
if(victim.isPrivate){
oReq.open("delete",matrix.cfg.srvurl+"delete",true);
oReq.setRequestHeader("x-content-id", victim.id);
oReq.setRequestHeader("x-access-token", matrix.mkOwnToken(victim.sign));
oReq.setRequestHeader("x-content-type", "post");
oReq.send();
}else*/{
}
}
,"postLike": function(e){
var cView = document.cView;
var nodeLikes = cView.Utils.getNode(e.target,["p","post-info"],["c","likes"]);
var nodePost = cView.Utils.getNode(nodeLikes, ["p","post"]);
var context = cView.contexts[nodePost.rawData.domain];
var action = e.target.action;
e.target.innerHTML = "";
e.target.appendChild(cView.gNodes["spinner"].cloneAll());
context.api.sendLike(context.token, nodePost.rawData.id, action).then(function(){
if(action){
var idx;
var likesUL;
if (!nodeLikes.childNodes.length){
nodeLikes.appendChild(cView.gNodes["likes-smile"].cloneNode(true));
likesUL = cView.doc.createElement( "span");
likesUL.className ="comma";
var suffix = cView.doc.createElement("span");
suffix.id = e.target.parentNode.postId+"-unl";
suffix.innerHTML = " liked this";
nodeLikes.appendChild(likesUL);
nodeLikes.appendChild(suffix);
}else {
/* for(idx = 0; idx < nodeLikes.childNodes.length; idx++)
if (nodeLikes.childNodes[idx].nodeName == "UL")break;
likesUL = nodeLikes.childNodes[idx];
*/
likesUL = nodeLikes.cNodes["comma"];
}
var nodeLike = cView.doc.createElement("span");
nodeLike.className = "p-timeline-user-like";
nodeLike.innerHTML = context.gUsers[context.gMe.users.id].link;
if(likesUL.childNodes.length)likesUL.insertBefore(nodeLike, likesUL.childNodes[0]);
else likesUL.appendChild(nodeLike);
e.target.parentNode.parentNode.parentNode.myLike = nodeLike;
if(!Array.isArray(nodePost.rawData.likes)) nodePost.rawData.likes = new Array();
nodePost.rawData.likes.unshift(context.gMe.users.id);
action = false;
}else{
nodePost.rawData.likes.splice(nodePost.rawData.likes.indexOf(context.gMe.users.id), 1) ;
var myLike = e.target.parentNode.parentNode.parentNode.myLike;
likesUL = myLike.parentNode;
likesUL.removeChild(myLike);
cView.Drawer.genLikes(nodePost);
/*
if (likesUL.childNodes.length < 2){
var nodePI = nodeLikes.parentNode;
nodePI.cNodes["likes"] = cView.doc.createElement("div");
nodePI.cNodes["likes"].className = "likes";
nodePI.replaceChild(nodePI.cNodes["likes"], nodeLikes);
}
*/
action = true;
}
e.target.action = action;
e.target.innerHTML=action?"Like":"Un-like";
try{
e.target.parentNode.cNodes["msg-error"].hidden = true;
}catch(e){};
},function(err) {
cView.Drawer.makeErrorMsg(err,e.target.parentNode);
e.target.innerHTML=action?"Like":"Un-like";
});
}
,"unfoldLikes": function(e){
var cView = document.cView;
var nodePost = e.target.getNode(["p","post"]);
var rawData = nodePost.rawData;
var context = cView.contexts[rawData.domain];
var span = e.target.getNode(["p","nocomma"]);
var nodeLikes = span.parentNode.cNodes["comma"];
if (nodePost.rawData.omittedLikes > 0){
context.api.getPost(context.token
,context.gUsers[rawData.createdBy].username + "/" + rawData.id
,["likes"]
).then (function(postUpd){
span.parentNode.removeChild(span);
postUpd.users.forEach(cView.Common.addUser, context);
nodePost.rawData.likes = postUpd.posts.likes;
cView.Drawer.writeAllLikes(nodePost.id, nodeLikes);
try{
nodeLikes.parentNode.cNodes["msg-error"].hidden = true;
}catch(e){};
},function (err){
cView.Drawer.makeErrorMsg(err,nodeLikes.parentNode);
});
}else cView.Drawer.writeAllLikes(id, nodeLikes);
}
,"getUsername": function(e){
var cView = document.cView;
var node = e.target; do node = node.parentNode; while(typeof node.user === "undefined");
var nodePopUp = node.getNode(["p","user-popup"]);
if ( cView.cTxt == null ){
if (nodePopUp && (typeof nodePopUp.post !== "undefined"))
cView.Actions.addComment({"target":nodePopUp.post});
else return;
}
cView.cTxt.value += "@" + node.user;
if(nodePopUp) nodePopUp.parentNode.removeChild(nodePopUp);
}
,"reqSubscription": function(e){
var cView = document.cView;
var username = cView.Utils.getNode(e.target,["p","up-controls"]).user;
var loginId = e.target.getNode(["p","up-c-mu"]).loginId;
var domain = e.target.getNode(["p","up-controls"]).domain;
var context = cView.contexts[domain];
context.api.reqSub(
context.logins[loginId].token
,username
,context.gUsers.byName[username].type
).then( function(){
var span = cView.doc.createElement("span");
span.innerHTML = "Request sent";
e.target.parentNode.replaceChild(span, e.target);
context.getWhoami(context.logins[loginId].token);
} );
}
,"evtSubscribe": function(e){
var cView = document.cView;
var target = e.target;
var nodeParent = target.parentNode;
var spinner = cView.gNodes["spinner"].cloneAll();
nodeParent.replaceChild(spinner, target);
var nodeUC = cView.Utils.getNode(nodeParent,["p","up-controls"]);
var username = nodeUC.user;
var loginId = nodeParent.getNode(["p","up-c-mu"]).loginId;
var context = cView.contexts[nodeUC.domain];
context.api.evtSub(
context.logins[loginId].token
,username
,target.subscribed
,context.gUsers.byName[username].type
).then( function(res){
context.logins[loginId].data = res;
cView.Common.refreshLogin(loginId,context);
cView.Utils.setChild(nodeParent.getNode(["p","up-controls"]).parentNode, "up-controls", cView.Drawer.genUpControls(context.gUsers.byName[username]));
context.getWhoami(context.logins[loginId].token);
},function(){
cView.Drawer.makeErrorMsg(err,nodeParent);
nodeParent.replaceChild( target, spinner);
});
}
,"showHidden": function(e){
var cView = document.cView;
if(e.target.action){
if(!cView.doc.hiddenCount)return;
var nodeHiddenPosts = cView.doc.createElement("div");
nodeHiddenPosts.id = "hidden-posts";
cView.posts.forEach(function(oPost){
if(oPost.data.type == "metapost"){
var nodeOut;
var hides = oPost.data.dups.filter(function(post){
return post.isHidden;
});
if (hides.length == 0)return;
if (hides.length == 1)
nodeOut = cView.Drawer.genPost(hides[0]);
else nodeOut = cView.Drawer.makeMetapost(
hides.map(cView.Drawer.genPost, cView)
);
return nodeHiddenPosts.appendChild(nodeOut);
}
if(!oPost.hidden)return;
nodeHiddenPosts.appendChild(
cView.Drawer.genPost(oPost.data)
);
});
e.target.parentNode.parentNode.insertBefore(nodeHiddenPosts , e.target.parentNode.nextSibling);
e.target.innerHTML = "Collapse "+ cView.doc.hiddenCount + " hidden entries";
cView.Drawer.applyReadMore(nodeHiddenPosts);
}else{
var nodeHiddenPosts = cView.doc.getElementById("hidden-posts");
if (nodeHiddenPosts) nodeHiddenPosts.parentNode.removeChild(nodeHiddenPosts);
if (cView.doc.hiddenCount) e.target.innerHTML = "Show "+ cView.doc.hiddenCount + " hidden entries";
else e.target.innerHTML = "";
}
e.target.action = !e.target.action;
}
,"postHide": function(e){
var cView = document.cView;
var victim = e.target.getNode(["p","post"]);
var action = e.target.action;
var context = cView.contexts[victim.rawData.domain];
context.api.sendHide(context.token, victim.rawData.id, action).then(function(){
cView.Actions.doHide(victim, action, "user");
});
}
,"doHide": function(victim, action){
var cView = document.cView;
var nodeHide = victim.getNode(["c","post-body"],["c","post-info"],["c","post-controls"],["c","controls"],["c","hide"]);
var host = victim.parentNode;
if(!host || (action != nodeHide.action)) return;
var oPost = cView.posts[victim.rawData.idx];
var nodeShow = cView.doc.getElementsByClassName("show-hidden")[0];
if (!nodeShow){
nodeShow = cView.gNodes["show-hidden"].cloneAll();
nodeShow.cNodes["href"].action = true;
cView.doc.getElementById("content").appendChild(nodeShow);
}
var aShow = nodeShow.cNodes["href"];
var count = 1;
if(action){
host.removeChild(victim);
if(host.className != "metapost") oPost.hidden = true;
else cView.Drawer.regenMetapost(host);
if ((oPost.data.type != "metapost")
|| !oPost.data.dups.some(function(dup){return dup.isHidden == true;}))
cView.doc.hiddenCount++;
aShow.action = false;
aShow.dispatchEvent(new Event("click"));
}else{
nodeHide.innerHTML = "Hide";
cView.posts[victim.rawData.idx].hidden = false;
if(oPost.data.type == "metapost"){
var unhidden = oPost.data.dups.find(function(post){
return post.isHidden?0:1;
});
if (typeof unhidden === "undefined" )
insertPost(victim);
else{
var dupId = [unhidden.domain,"post" ,unhidden.id].join("-");
var dup = document.getElementById(dupId);
var newHost = dup.parentNode;
if (newHost.className == "metapost" ){
newHost.appendChild(victim);
cView.Drawer.regenMetapost(newHost);
}else{
var dummy = document.createElement("div");
newHost.insertBefore(dummy, dup);
newHost.replaceChild(
cView.Drawer.makeMetapost([victim, dup])
,dummy
);
}
}
if((host.className != "metapost")|| !cView.Drawer.regenMetapost(host))
cView.doc.hiddenCount--;
}else{
insertPost(victim);
cView.doc.hiddenCount--;
}
cView.Drawer.applyReadMore(victim);
if(cView.doc.hiddenCount)
aShow.innerHTML = "Collapse "
+ cView.doc.hiddenCount
+ " hidden entries";
else aShow.dispatchEvent(new Event("click"));
}
victim.rawData.isHidden = action;
nodeHide.action = !action;
function insertPost(victim){
var idx = victim.rawData.idx;
var count = 0;
do if(cView.posts[idx--].hidden)count++;
while ( idx >0 );
if ((victim.rawData.idx - count+1) >= cView.doc.posts.childNodes.length )
cView.doc.posts.appendChild(victim);
else cView.doc.posts.insertBefore(victim
,cView.doc.posts.childNodes[victim.rawData.idx - count+1]
);
}
}
,"addComment": function(e){
var cView = document.cView;
var nodePost = cView.Utils.getNode(e.target,["p","post"]);
var postNBody = nodePost.cNodes["post-body"];
if(nodePost.rtCtrl.isBeenCommented === true)return;
nodePost.rtCtrl.isBeenCommented = true;
var nodeComment = cView.Drawer.genAddComment(cView.contexts[nodePost.rawData.domain]);
postNBody.cNodes["comments"].appendChild(nodeComment);
cView.cTxt = nodeComment.getElementsByClassName("edit-txt-area")[0];
cView.cTxt.focus();
}
,"editComment": function(e){
var cView = document.cView;
var victim = e.target.getNode(["p", "comment"]);
var context = cView.contexts[victim.domain];
var nodeEdit = cView.Drawer.genEditNode(cView.Actions.postEditComment,cView.Actions.cancelEditComment);
var textArea = nodeEdit.cNodes["edit-txt-area"];
textArea.value = context.gComments[victim.rawId].body;
victim.replaceChild( nodeEdit, victim.cNodes["comment-body"]);
victim.cNodes["comment-body"] = nodeEdit;
nodeEdit.className = "comment-body";
cView.cTxt = victim.getElementsByClassName("edit-txt-area")[0];
cView.cTxt.focus();
if (textArea.scrollHeight > textArea.clientHeight)
textArea.style.height = textArea.scrollHeight + "px";
}
,"postEditComment": function(e){
var cView = document.cView;
var nodeComment = e.target.getNode(["p", "comment"]);
var postId = nodeComment.getNode(["p","post"]).rawData.id;
var context = cView.contexts[nodeComment.domain];
var textField = e.target.parentNode.parentNode.cNodes["edit-txt-area"];
e.target.disabled = true;
var spinner = cView.gNodes["spinner"].cloneNode(true);
var nodeCancel = e.target.parentNode.replaceChild(spinner, e.target.parentNode.cNodes["edit-buttons-cancel"] );
var comment = context.gComments[nodeComment.rawId];
comment.body = cView.Common.urlsToCanonical(textField.value);
comment.updatedAt = Date.now();
var postdata = new Object();
postdata.comment = comment;
context.api.editComment( context.logins[comment.createdBy].token
,comment.id, postdata,postId
).then( function(res){
nodeComment.parentNode.replaceChild(cView.Drawer.genComment.call(context, res.comments),nodeComment);
context.gComments[comment.id] = res.comments;
},function(err){
e.target.disabled = false;
e.target.parentNode.replaceChild(nodeCancel, spinner);
cView.Drawer.makeErrorMsg(err,nodeComment);
});
cView.cTxt = null;
}
,"cancelEditComment": function(e){
var cView = document.cView;
var nodeComment = e.target.getNode(["p","comment"]);
var context = cView.contexts[nodeComment.getNode(["p","post"]).rawData.domain];
var newNodeComment = cView.Drawer.genComment.call(context, context.gComments[nodeComment.rawId]);
nodeComment.parentNode.replaceChild(newNodeComment,nodeComment);
cView.Drawer.applyReadMore(newNodeComment);
cView.cTxt = null;
}
,"processText": function(e) {
var cView = document.cView;
cView.cTxt = e.target;
if (e.target.scrollHeight > e.target.clientHeight)
e.target.style.height = e.target.scrollHeight + "px";
if (e.ctrlKey && (e.which == "13")){
e.preventDefault();
e.stopImmediatePropagation();
//if(text.charAt(text.length-1) == "\n") e.target.value = text.slice(0, -1);
e.target.parentNode.parentNode.getElementsByClassName("edit-buttons-post")[0].dispatchEvent(new Event("click"));
}
}
,"cancelNewComment": function(e){
var cView = document.cView;
var nodePost = e.target.getNode(["p", "post"]);
nodePost.rtCtrl.isBeenCommented = false;
if(typeof nodePost.rtCtrl.bumpLater !== "undefined")
setTimeout(nodePost.rtCtrl.bumpLater, 1000);
var nodeComment = e.target.getNode(["p", "comment"]);
nodeComment.parentNode.removeChild(nodeComment);
cView.cTxt = null;
}
,"postNewComment": function(e){
var cView = document.cView;
e.target.disabled = true;
var textField = e.target.getNode(["p","edit"], ["c","edit-txt-area"]);
var spinner = cView.gNodes["spinner"].cloneNode(true);
var nodeEButtons = textField.parentNode.cNodes["edit-buttons"];
var butCancel = e.target.parentNode.replaceChild(spinner,e.target.parentNode.cNodes["edit-buttons-cancel"] );
var nodeComment = cView.Utils.getNode(textField, ["p", "comment"]);
var nodePost = cView.Utils.getNode(nodeComment,["p", "post"])
var context = cView.contexts[nodePost.rawData.domain];
nodeEButtons.cNodes["edit-buttons-post"].disabled = true;
var comment = new Object();
comment.body = cView.Common.urlsToCanonical(textField.value);
comment.postId = nodePost.rawData.id;
comment.createdAt = null;
comment.createdBy = null;
comment.updatedAt = null;
comment.post = null;
var postdata = new Object();
postdata.comment = comment;
var token;
var nodesSelectUsr = nodeComment.getElementsByClassName("select-user-ctrl")[0].childNodes;
if(context.ids.length > 1){
for(var idx = 0; idx < nodesSelectUsr.length; idx++){
if (nodesSelectUsr[idx].selected){
token = context.logins[nodesSelectUsr[idx].value].token;
break;
}
}
}else token = context.token;
var nodeError = nodeEButtons.getElementsByClassName("msg-error")[0];
if(typeof nodeError !== "undefined") nodeError.parentNode.removeChild(nodeError);
context.api.sendComment(token,postdata).then(function(res){
nodePost.rtCtrl.isBeenCommented = false;
if(typeof nodePost.rtCtrl.bumpLater !== "undefined")
setTimeout(nodePost.rtCtrl.bumpLater, 1000);
var comment = res.comments;
context.gComments[comment.id] = comment;
if( nodeComment.parentNode.children.length > 4 )
nodePost.getNode(["c","post-body"],["c","many-cmts-ctrl"]).hidden = false;
if(!document.getElementById(context.domain + "-cmt-" + comment.id)){
var newComment = cView.Drawer.genComment.call(context, comment);
nodeComment.parentNode.replaceChild(newComment ,nodeComment);
cView.Drawer.applyReadMore(newComment);
if(nodePost.rawData.comments.indexOf(comment.id) == -1)
nodePost.rawData.comments.push(comment.id);
window.dispatchEvent(new CustomEvent("newNode", {"detail":newComment}));
} else nodeComment.parentNode.removeChild(nodeComment);
},function(err){
nodeEButtons.cNodes["edit-buttons-post"].disabled = false;
nodeEButtons.replaceChild(butCancel,spinner );
cView.Drawer.makeErrorMsg(err,nodeEButtons);
});
cView.cTxt = null;
}
,"deleteComment": function(e){
var cView = document.cView;
var nodeComment = e.target.getNode(["p", "comment"]);
cView.Actions.deleteNode(nodeComment,cView.Actions.doDeleteComment);
}
,"deleteNode": function(node,doDelete){
var cView = document.cView;
var nodeConfirm = cView.doc.createElement("div");
var butDelete = cView.doc.createElement("button");
butDelete.innerHTML = "delete";
butDelete.node = node;
butDelete.onclick = function(){doDelete(butDelete);};
var butCancel0 = cView.doc.createElement("button");
butCancel0.innerHTML = "cancel";
butCancel0.onclick = function (){cView.Actions.deleteCancel(nodeConfirm)};
var aButtons = [butDelete,butCancel0] ;
nodeConfirm.innerHTML = "<p>Sure delete?</p>";
aButtons.forEach(function(but){ but.className = "confirm-button";});
nodeConfirm.appendChild(aButtons.splice(Math.floor(Math.random()*2 ),1)[0]);
nodeConfirm.appendChild(aButtons[0]);
node.parentNode.insertBefore(nodeConfirm,node);
nodeConfirm.node = node;
node.hidden = true;
}
,"deleteCancel": function(nodeConfirm){
var cView = document.cView;
nodeConfirm.node.hidden = false;
nodeConfirm.parentNode.removeChild(nodeConfirm);
}
,"doDeleteComment": function(but){
var cView = document.cView;
var nodeComment = but.node;
var nodePost = nodeComment.getNode(["p", "post"])
var context = cView.contexts[nodePost.rawData.domain];
but.parentNode.parentNode.removeChild(but.parentNode);
but.node.hidden = false;
var token;
if( typeof context.logins[nodeComment.userid] != "undefined")
token = context.logins[nodeComment.userid].token;
else if (typeof context.logins[nodePost.rawData.createdBy] != "undefined" )
token = context.logins[nodePost.rawData.createdBy].token;
else return;
context.api.deleteComment(token, nodeComment.rawId, nodePost.rawData.id ).then(function(){
if(nodeComment.parentNode) nodeComment.parentNode.removeChild(nodeComment);
delete context.gComments[nodeComment.rawId];
});
/*
if(nodePost.isPrivate){
oReq.open("delete",matrix.cfg.srvurl+"delete",true);
oReq.setRequestHeader("x-content-id", nodeComment.id);
oReq.setRequestHeader("x-access-token", matrix.mkOwnToken(nodeComment.sign));
oReq.setRequestHeader("x-content-type", "comment");
oReq.send();
}else{
*/
}
,"unfoldComm": function(e){
var cView = document.cView;
var nodePost = e.target.getNode(["p","post"]);
var domain = nodePost.rawData.domain;
var context = cView.contexts[domain];
var id = nodePost.id;
var spUnfold = e.target.parentNode.appendChild(cView.doc.createElement("i"));
var host = e.target.getNode(["p","comment-body"]);
spUnfold.className = "fa fa-spinner fa-pulse";
return context.api.getPost(context.token
, context.gUsers[nodePost.rawData.createdBy].username
+ "/" + nodePost.rawData.id
, ["comments"]
).then( function(postUpd){
var arrCmts = new Array();
nodePost.rawData.omittedComments = 0;
cView.Common.loadGlobals(postUpd, context);
postUpd.posts.domain = domain;
cView.doc.getElementById(id).rawData = postUpd.posts;
var nodePB = cView.doc.getElementById(id).cNodes["post-body"];
var text = "";
if (nodePost.rtCtrl.isBeenCommented == true)
text = nodePB.getElementsByTagName("textarea")[0].value;
if(typeof nodePost.rtCtrl.bumpLater !== "undefined")
setTimeout(nodePost.rtCtrl.bumpLater, 1000);
var host = cView.doc.createElement("div");
host.className = "comments";
postUpd.comments.forEach(function(cmt){
context.gComments[cmt.id] = cmt;
var nodeCmt = cView.Drawer.genComment.call(context, cmt);
host.appendChild(nodeCmt);
arrCmts.push(nodeCmt);
});
if (nodePost.rtCtrl.isBeenCommented == true){
var nodeComment = cView.Drawer.genAddComment(context);
host.appendChild(nodeComment);
nodeComment.getElementsByClassName("edit-txt-area")[0].value = text;
}
cView.Utils.setChild(nodePB,"comments", host);
nodePost.getNode(["c","post-body"],["c","many-cmts-ctrl"]).hidden = false;
if ((context.ids.indexOf(postUpd.posts.createdBy) == -1) && (postUpd.posts.commentsDisabled == "1")){
var nodeCmtControls = nodePost.getElementsByClassName("cmts-add");
for(var idx = 0; idx < nodeCmtControls.length; idx++){
nodeCmtControls[idx].style.display = "none";
nodeCmtControls[idx].nextSibling.style.display = "none";
}
}
cView.Drawer.applyReadMore( nodePB);
window.dispatchEvent(new CustomEvent("newNode", {"detail":arrCmts}));
return postUpd;
},function(err){
spUnfold.parentNode.removeChild(spUnfold);
cView.Drawer.makeErrorMsg(err,host);
});
}
,"calcCmtTime": function(e){
var cView = document.cView;
var nodeCmt = cView.Utils.getNode(e.target,["p","comment"]);
if (typeof(nodeCmt.createdAt) !== "undefined" ){
var absUxTime = nodeCmt.createdAt*1;
var txtdate = new Date(absUxTime ).toString();
e.target.title = cView.Utils.relative_time(absUxTime) + " ("+ txtdate.slice(0, txtdate.indexOf("(")).trim()+ ")";
}
}
,"me": function(e){
e.currentTarget.href = gConfig.front+"filter/me";
}
,"goComments": function(e){
e.currentTarget.href = gConfig.front+"filter/comments";
}
,"home": function(e){
e.currentTarget.href = gConfig.front;
}
,"directs": function(e){
e.currentTarget.href = gConfig.front+ "filter/direct";
}
,"notifications": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications";
}
,"bestof": function(e){
e.currentTarget.href = gConfig.front+ "filter/best_of";
}
,"my": function(e){
e.currentTarget.href = gConfig.front+ "filter/discussions";
}
,"newDirectInp": function(e){
var cView = document.cView;
var nodeP = e.target.getNode(["p","new-post-to"]);
var victim = e.target.getNode(["p", "new-post"]);
if(e.which == "13") return cView.Actions.newDirectAddFeed(e);
var nodeTip = cView.gNodes["friends-tip"].cloneAll();
nodeTip.inp = e.target;
nodeTip.style.top = e.target.offsetHeight;
nodeTip.style.left = 0;// e.target.offsetLeft ;
nodeTip.style.width = e.target.offsetWidth;
if((typeof e.target.tip !== "undefined") && e.target.tip.parentNode) {
e.target.parentNode.replaceChild(nodeTip, e.target.tip);
e.target.tip = nodeTip;
}else e.target.tip = e.target.parentNode.appendChild(nodeTip);
var myFeed = cView.contexts[nodeP.domain].logins[nodeP.userid].data.users.username;
if((nodeP.destType == "posts") && (nodeP.feeds.indexOf(myFeed) == -1 )){
var li = document.createElement("li");
li.innerHTML = "My Feed";
li.className = "ft-i";
nodeTip.cNodes["ft-list"].appendChild(li);
li.addEventListener("click",function(e){
var liMyFeed = cView.gNodes["new-post-feed"].cloneAll();
liMyFeed.innerHTML = "My Feed";
liMyFeed.oValue = myFeed;
nodeP.cNodes["new-post-feeds"].appendChild(liMyFeed);
nodeP.feeds.push(myFeed);
nodeP.getNode(["p","new-post"], ["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
});
}
var txt = e.target.value.toLocaleLowerCase();
var pos = e.target.suggest;
for(var idx = 0; idx < txt.length; idx++){
if (typeof pos[txt.charAt(idx)] !== "undefined")
pos = pos[txt.charAt(idx)];
else{
pos = null;
break;
}
}
if(pos && pos.arr)pos.arr.forEach(function(user){
var li = cView.gNodes["ft-i"].cloneAll();
li.innerHTML = user;
nodeTip.cNodes["ft-list"].appendChild(li);
});
if(typeof e.target.dest[txt] !== "undefined")
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"doBan": function(e){
var cView = document.cView;
//var nodePopUp = e.target; do nodePopUp = nodePopUp.parentNode; while(nodePopUp.className != "user-popup");
var nodeUC = e.target.getNode(["p","up-controls"]);
var username = nodeUC.user;
var bBan = e.target.checked;
var nodeParent = e.target.parentNode;
var loginId = e.target.getNode(["p","up-c-mu"]).loginId;
var context = cView.contexts[nodeUC.domain];
var user = context.gUsers.byName[username];
var spinner = cView.gNodes["spinner"].cloneNode(true);
nodeParent.replaceChild(spinner,e.target);
context.api.doBan(context.logins[loginId].token,username, bBan).then(function(){
var banIds = context.logins[loginId].data.users.banIds;
if (bBan)banIds.push(context.gUsers.byName[username].id);
else{
var idx = banIds.indexOf(user.id);
if (idx != -1 ) banIds.splice(idx, 1);
}
cView.Common.saveLogins();
if (typeof nodeUC.parentNode !== "undefined" )
cView.Utils.setChild(nodeUC.parentNode, "up-controls", cView.Drawer.genUpControls(user));
},function(){
if (typeof nodeUC.parentNode !== "undefined" )
cView.Utils.setChild(nodeUC.parentNode, "up-controls", cView.Drawer.genUpControls(user));
});
}
,"doUnBan": function(e){
var cView = document.cView;
var nodeHost = e.target.getNode(["p","up-controls"]);
var loginId = e.target.getNode(["p","up-c-mu"]).loginId;
var context = cView.contexts[nodeHost.domain];
var username = nodeHost.user;
var user = context.gUsers.byName[username];
var spinner = cView.gNodes["spinner"].cloneNode(true);
e.target.parentNode.replaceChild(spinner,e.target);
context.api.doBan(context.logins[loginId].token, username, false).then(function(){
var banIds = context.logins[loginId].data.users.banIds;
var idx = banIds.indexOf(user.id);
if (idx != -1 ) banIds.splice(idx, 1);
cView.localStorage.setItem("gMe",JSON.stringify(cView.logins));
if (typeof nodeHost.parentNode !== "undefined" )
cView.Utils.setChild(nodeHost.parentNode, "up-controls", cView.Drawer.genUpControls(user));
},function(res){
console.log(res);
if (typeof nodeHost.parentNode !== "undefined" )
cView.Utils.setChild(nodeHost.parentNode, "up-controls", cView.Drawer.genUpControls(users));
});
}
,"doBlockCom": function(e){
var cView = document.cView;
var nodeUPC = e.target.getNode(["p" ,"up-controls"]);
var id = cView.contexts[nodeUPC.domain].gUsers.byName[nodeUPC.user].id;
cView.Common.updateBlockList("blockComments" ,nodeUPC.domain, id ,e.target.checked);
cView.Drawer.blockComments( nodeUPC ,e.target.checked);
}
,"doBlockPosts": function(e){
var cView = document.cView;
var nodeUPC = e.target.getNode(["p" ,"up-controls"]);
var id = cView.contexts[nodeUPC.domain].gUsers.byName[nodeUPC.user].id;
cView.Common.updateBlockList("blockPosts" ,nodeUPC.domain, id ,e.target.checked);
cView.Drawer.blockPosts( nodeUPC,e.target.checked );
}
,"setRadioOption": function(e){
var cView = document.cView;
cView.localStorage.setItem(e.target.name, e.target.value );
}
,"unfoldAttImgs": function (e){
var cView = document.cView;
var nodeAtts = cView.Utils.getNode(e.target,["p", "attachments"]);
var nodeImgHost = nodeAtts.cNodes["atts-img"];
if(nodeAtts.cNodes["atts-unfold"].cNodes["unfold-action"].value == "true"){
nodeImgHost.style.flexWrap = "wrap";
for (var idx = 1;idx < nodeImgHost.childNodes.length; idx++){
nodeImgHost.childNodes[idx].hidden = false;
nodeImgHost.childNodes[idx].img.src = nodeImgHost.childNodes[idx].url;
nodeImgHost.childNodes[idx].img.style.height = "auto";
}
nodeAtts.cNodes["atts-unfold"].getElementsByTagName("a")[0].innerHTML = '<i class="fa fa-chevron-up fa-2x"></i>';
nodeAtts.cNodes["atts-unfold"].cNodes["unfold-action"].value = "false";
}else{
nodeImgHost.style.flexWrap = "nowrap";
nodeAtts.cNodes["atts-unfold"].getElementsByTagName("a")[0].innerHTML = '<i class="fa fa-chevron-down fa-2x"></i>';
nodeAtts.cNodes["atts-unfold"].cNodes["unfold-action"].value = "true";
}
}
,"ftClose": function(e){
var cView = document.cView;
var victim =cView.Utils.getNode(e.target,["p","friends-tip"]);
victim.inp.tip = undefined;
victim.parentNode.removeChild(victim);
}
,"selectFeed": function(e){
var cView = document.cView;
var input = e.target.getNode(["p","friends-tip"]).inp;
input.value = e.target.innerHTML;
var event = new Event("click");
input.getNode(["p","new-post-to"],["c","new-feed-add"]).dispatchEvent(event);
}
,"postDirect": function(e){
var cView = document.cView;
var victim =e.target.getNode(["p","new-post"]);
var nodesSenders = victim.getElementsByClassName("new-post-to");
for (var idx = 0; idx<nodesSenders.length; idx++){
var nodeSender = nodesSenders[idx];
var context = cView.contexts[nodeSender.domain];
var input = nodeSender.getNode(["c","new-feed-input"],["c","input"]).value;
if ((input != "") && (typeof context.gUsers.byName[input] !== "undefined")
&& context.gUsers.byName[input].friend
&& (context.gUsers.byName[input].subscriber||context.gUsers.byName[input].type == "group"))
nodeSender.feeds.push(input);
/*
if (nodeSender.feeds.length) cView.Actions.newPost(e);
else alert("should have valid recipients");
*/
}
cView.Actions.newPost(e);
}
,"logout": function(){
var cView = document.cView;
//matrix.ready = 0;
try{matrix.logout();}catch(e){};
cView.localStorage.removeItem("logins");
Object.keys(cView.contexts).forEach(function(domain){
cView.contexts[domain].token = null;
});
cView.Common.saveLogins();
location.assign(gConfig.front);
}
,"newPostRemoveFeed": function(e){
var cView = document.cView;
var nodeP = e.target.parentNode.parentNode;
nodeP.cNodes["new-feed-input"][e.target.idx].disabled = false;
for(var idx = 0; idx < nodeP.feeds.length; idx++){
if(nodeP.feeds[idx] == e.target.oValue){
nodeP.feeds.splice(idx,1);
break;
}
}
e.target.parentNode.removeChild(e.target);
if(nodeP.feeds.length == 0)
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = true;
}
,"newDirectRemoveFeed": function(e){
var cView = document.cView;
var nodeP = cView.Utils.getNode(e.target,["p","new-post-to"]);
var idx = nodeP.feeds.indexOf(e.target.oValue);
if(idx != -1 ) nodeP.feeds.splice(idx,1);
e.target.parentNode.removeChild(e.target);
var input = nodeP.getNode(["c","new-feed-input"],["c", "input"]);
if((nodeP.feeds.length == 0)
&&((input.value == "")||(typeof input.dest[input.value] === "undefined" ) ))
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = true;
}
,"newPostAddFeed": function(e){
var cView = document.cView;
var nodeP = e.target.getNode(["p", "new-post-to"]);
var input = nodeP.getNode(["c","new-feed-input"],["c", "input"]);
input.hidden = false;
if (input.value == "") return;
var feed = input.value;
if((feed != "") && (typeof input.dest[feed] !== "undefined")
&& (nodeP.feeds.indexOf(input.dest[feed]) == -1) ){
nodeP.feeds.push(input.dest[feed]);
var li = cView.gNodes["new-post-feed"].cloneAll();
li.innerHTML = input.dest[feed];
li.oValue = input.dest[feed];
nodeP.cNodes["new-post-feeds"].appendChild(li);
input.value = "";
}
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"newDirectAddFeed": function(e){
var cView = document.cView;
var nodeP = e.target.getNode(["p","new-post-to"]);
var input = nodeP.getNode(["c","new-feed-input"],["c", "input"]);
if (input.value == "") return;
var username = input.dest[input.value];
if (nodeP.feeds.indexOf(username) != -1 ) return;
if(typeof input.tip !== "undefined")
input.tip.parentNode.removeChild(input.tip);
nodeP.feeds.push(username);
var li = cView.gNodes["new-post-feed"].cloneAll();
li.innerHTML = username;
li.oValue = username;
nodeP.cNodes["new-post-feeds"].appendChild(li);
input.value = "";
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"newPostSelect": function(e){
var cView = document.cView;
var option = e.target[e.target.selectedIndex];
if (option.value == "")return;
var nodeP = e.target.parentNode;
var context = cView.contexts[nodeP.domain];
if (option.privateFeed ){
nodeP.isPrivate = true;
var ul = cView.doc.createElement("ul");
ul.className = "new-post-feeds";
nodeP.replaceChild(ul, nodeP.cNodes["new-post-feeds"]);
nodeP.cNodes["new-post-feeds"] = ul;
nodeP.feeds = new Array();
for(var idx = 0; idx < e.target.length; idx++)
e.target[idx].disabled = false;
}
option.disabled = true;
nodeP.feeds.push(option.value);
var li = cView.doc.createElement("li");
if(option.value == context.gMe.users.username)li.innerHTML = "My feed";
else li.innerHTML = "@" + option.value;
li.className = "new-post-feed";
li.oValue = option.value;
li.idx = e.target.selectedIndex;
li.addEventListener("click", cView["Actions"]["newPostRemoveFeed"]);
nodeP.cNodes["new-post-feeds"].appendChild(li);
nodeP.getNode(["p","new-post"],["c","edit-buttons"],["c","edit-buttons-post"]).disabled = false;
}
,"evtUserPopup": function(e){
var cView = document.cView;
var node = e.target; while(typeof node.userid === "undefined")node = node.parentNode;
var nodePost = node.getNode(["p","post"]);
var context = cView.contexts[nodePost.rawData.domain];
var user = context.gUsers[node.userid];
var innerWidth = window.innerWidth;
if(cView.doc.getElementById("userPopup" + context.domain+ node.userid))return;
var nodePopup = cView.Drawer.genUserPopup(node, user);
nodePopup.post = nodePost;
nodePopup.style.opacity = 0;
cView.doc.getElementsByTagName("body")[0].appendChild(nodePopup);
nodePopup.style.top = 0;
nodePopup.style.left = 0;
var width = nodePopup.offsetWidth;
nodePopup.style.top = e.pageY;
nodePopup.style.left = e.pageX;
if(nodePopup.offsetLeft + width > innerWidth){
nodePopup.style.left = "auto";
nodePopup.style.right = "1em";
}
nodePopup.style["z-index"] = 2;
nodePopup.style.opacity = 1;
}
,"upClose": function(e){
var cView = document.cView;
var node = e.target.getNode(["p", "user-popup"]);
node.parentNode.removeChild(node);
}
,"destroy": function(e){
var cView = document.cView;
if (!e.currentTarget.parentNode)return;
if (e.eventPhase != Event.AT_TARGET)return;
e.target.parentNode.removeChild(e.target);
//e.stopPropagation();
}
,"realTimeSwitch": function(e){
var cView = document.cView;
if(e.target.checked )cView.localStorage.setItem("rt",1);
else cView.localStorage.setItem("rt",0);
}
,"goSettings": function (e){
var cView = document.cView;
e.currentTarget.href = gConfig.front+"settings";
}
,"goRequests": function (e){
var cView = document.cView;
e.currentTarget.href = gConfig.front+"requests";
}
,"genBlock": function (e){
var cView = document.cView;
var node = e.target.parentNode;
var nodeUC = e.target.getNode(["p","up-controls"]);
var nodeBlock = cView.gNodes["up-block"].cloneAll();
var context = cView.contexts[nodeUC.domain];
nodeBlock.className = "user-popup";
nodeBlock.user = node.user;
node.appendChild(nodeBlock);
nodeBlock.style.top = e.target.offsetTop;
nodeBlock.style.left = e.target.offsetLeft;
nodeBlock.style["z-index"] = 2;
var chkboxes = nodeBlock.getElementsByTagName("input");
for(var idx = 0; idx < chkboxes.length; idx++){
var list = cView.blocks[chkboxes[idx].value];
if((typeof list !== "undefined")
&& (typeof list[context.domain]!== "undefined")
&& (list[context.domain] != null)
&& (typeof list[context.domain][context.gUsers.byName[nodeUC.user].id] !== "undefined")
)
chkboxes[idx].checked = true;
}
}
,"updateProfile": function (e){
var cView = document.cView;
var nodeProfile = cView.Utils.getNode(e.target,["p","settings-profile"]);
e.target.disabled = true;
nodeProfile.getElementsByClassName("spinner")[0].hidden = false;
var inputs = cView.Utils.getInputsByName(nodeProfile);
var id = inputs["id"].value;
var context = cView.contexts[inputs["domain"].value];
var oUser = context.logins[id].data.users;
oUser.screenName = inputs["screen-name"].value;
oUser.email = inputs["email"].value;
var access = inputs[["access",oUser.domain, oUser.id].join("-")].value;
switch (access){
case "is-private":
oUser.isPrivate = "1";
break;
case "is-protected":
oUser.isProtected = "1";
break;
default:
oUser.isPrivate = "0";
oUser.isProtected = "0";
}
oUser.description = nodeProfile.cNodes["gs-descr"].value;
var nodeMsg = nodeProfile.getElementsByClassName("update-status")[0];
nodeMsg.className = "update-status";
nodeMsg.innerHTML = "";
context.api.updProfile(context.logins[id].token, id, {"user":oUser})
.then(function(res){
e.target.disabled = false;
nodeProfile.getElementsByClassName("spinner")[0].hidden = true;
context.logins[id].data = res;
nodeMsg.classList.add("sr-info");
nodeMsg.innerHTML = "Updated. @"+ oUser.username +"'s feed is <span style='font-weight: bold;'>" + ((oUser.isPrivate == "1")?"private":"public")+ ".</span>";
cView.Common.refreshLogin(id, context);
}
,function(res){
e.target.disabled = false;
nodeProfile.getElementsByClassName("spinner")[0].hidden = true;
nodeMsg.classList.add( "msg-error");
nodeMsg.innerHTML = "Got error: ";
try{
nodeMsg.innerHTML += res.data.err;
}catch(e) {nodeMsg.innerHTML += "unknown error";};
});
}
,"addAcc": function (e){
var cView = document.cView;
var nodePorfiles = e.target.getNode( ["p","accaunts-settings"],["c","settings-profiles"]);
var nodeLogin = cView.gNodes["settings-login"].cloneAll();
nodePorfiles.appendChild(nodeLogin);
document.getElementsByClassName("gs-add-acc")[0].hidden = true;
Object.keys(cView.contexts).forEach(function(domain,num){
var nodeIB = cView.gNodes["input-block"].cloneAll();
var nodeInput = nodeIB.cNodes["ib-input"];
nodeInput.value = domain;
nodeInput.name = "domain";
nodeIB.cNodes["ib-span"].innerHTML = domain;
nodeInput.addEventListener("change",cView.Actions.setDomainInfo);
nodeLogin.cNodes["domains"].appendChild(nodeIB);
if(domain == gConfig.leadDomain){
nodeInput.checked = true;
nodeInput.dispatchEvent(new Event("change"));
}
});
}
,"addProfileLogin": function (e){
var cView = document.cView;
e.target.disabled = true;
var nodeLogin = cView.Utils.getNode(e.target, ["p","settings-login"]);
nodeLogin.getElementsByClassName("spinner")[0].hidden = false;
var inpsLogin = cView.Utils.getInputsByName(nodeLogin);
var context = cView.contexts[inpsLogin["domain"].value];
var userid = null;
var nodeMsg = nodeLogin.cNodes["msg-error"];
context.api.login(
inpsLogin["login-username"].value.trim()
,inpsLogin["login-password"].value.trim()
).then( function(res){
nodeMsg.hidden = true;
userid = res.users.id;
if(!context.ids)context.token = res.authToken;
if(typeof context.logins[userid] !== "undefined"){
cView.doc.getElementsByClassName("gs-add-acc")[0].hidden = false;
nodeLogin.parentNode.removeChild(nodeLogin);
return;
}
context.logins[userid] = new Object();
context.logins[userid].token = res.authToken;
context.logins[userid].domain = context.domain;
if (!context.token)context.token = res.authToken;
cView.Common.saveLogins();
context.getWhoami(res.authToken).then(finish);
} ,function(res){
nodeMsg.hidden = false;
nodeMsg.innerHTML = res.code+" "+ res.data;
nodeLogin.getElementsByClassName("spinner")[0].hidden = true;
e.target.disabled = false;
});
function finish(){
cView.doc.getElementsByClassName("gs-add-acc")[0].hidden = false;
nodeLogin.parentNode.replaceChild(cView.Drawer.genProfile(context.logins[userid].data.users),nodeLogin);
}
}
,"setMainProfile": function(e){
if(!e.target.checked)return;
var cView = document.cView;
var nodeProf = e.target.getNode(["p","settings-profile"]);
var inputs = cView.Utils.getInputsByName(nodeProf);
var id = inputs["id"].value;
var context = cView.contexts[inputs["domain"].value];
context.token = context.logins[id].token;
cView.Common.saveLogins();
}
,"logoutAcc": function(e){
var cView = document.cView;
var nodeProf = cView.Utils.getNode(e.target, ["p","settings-profile"]);
var inputs = cView.Utils.getInputsByName(nodeProf);
var id = inputs["id"].value;
var context = cView.contexts[inputs["domain"].value];
var token = context.logins[id].token;
delete context.logins[id];
nodeProf.parentNode.removeChild(nodeProf);
if(token == context.token){
context.token = null;
var nodesProf = cView.doc.getElementsByClassName("settings-profile");
if (!nodesProf.length) return cView.Actions.logout(e);
for (var idx = 0; idx < nodesProf.length; idx++ ){
var nodeProf = nodesProf[idx];
inputs = cView.Utils.getInputsByName(nodeProf);
if(context.domin != inputs["domain"].value) continue;
id = inputs["id"].value;
inputs["is-main-"+context.domain].checked = true;
context.token = context.logins[id].token;
break;
}
}
cView.Common.saveLogins();
}
,"setRTparams": function (e){
var cView = document.cView;
var value = e.target.value;
e.target.parentNode.getElementsByTagName("span")[0].innerHTML = value + " minutes";
var oRTParams = new Object();
["rt-bump-int", "rt-bump-cd", "rt-bump-d"].forEach(function(id){
oRTParams[id] = cView.doc.getElementById(id).value;
});
cView.localStorage.setItem("rt_params",JSON.stringify(oRTParams) );
}
,"setRTBump": function (e){
var cView = document.cView;
var bump = e.target.checked;
cView.localStorage.setItem("rtbump",bump?1:0);
cView.doc.getElementById("rt-params").hidden = !bump;
}
,"srAccept": function (e){
var cView = document.cView;
cView.Actions.sendReqResp(e.target, "acceptRequest" );
}
,"srReject": function (e){
var cView = document.cView;
cView.Actions.sendReqResp(e.target, "rejectRequest" );
}
,"sendReqResp": function (node, action){
var cView = document.cView;
node.parentNode.hidden = true;
var host = node.parentNode.parentNode;
var context = cView.contexts[host.cNodes["sr-domain"].value];
var spinner = cView.gNodes["spinner"].cloneNode(true);
host.appendChild(spinner);
context.api.reqResp(context.logins[host.cNodes["sr-id"].value].token
,host.cNodes["sr-user"].value
,action
,host.cNodes["sr-reqid"].value
,host.cNodes["sr-type"].value
,context.gUsers[host.cNodes["sr-dest"].value].username
).then(function() {
host.parentNode.removeChild(host);
var nodeSR = cView.doc.getElementById("sr-info");
if(--cView.subReqsCount){
nodeSR.cNodes["sr-info-a"].innerHTML = "You have "
+ cView.subReqsCount
+ " subscription requests to review.";
}else{
nodeSR.hidden = true;
var victim = cView.doc.getElementById("sr-header");
victim.parentNode.removeChild(victim);
}
}
,function(err){
host.removeChild(spinner);
cView.Drawer.makeErrorMsg(err,host);
node.parentNode.hidden = false;
});
}
,"getauth": function (e){
var cView = document.cView;
var context = cView.leadContext;
var oReq = new XMLHttpRequest();
context.api.login(
cView.doc.getElementById("a-user").value.trim()
,cView.doc.getElementById("a-pass").value.trim()
).then(function(data){
cView.Common.setCookie(gConfig.domains[context.domain].tokenPrefix
+ "authToken"
, data.authToken
);
cView.localStorage.setItem( "logins"
,JSON.stringify([{
"domain":context.domain
,"token":data.authToken
}])
);
location.reload();
},function(err){
cView.doc.getElementById("auth-msg").innerHTML = JSON.parse(err.data).err;
});
}
,"showUnfolder":function(e){
var cView = document.cView;
var nodeImgAtt = cView.Utils.getNode(e.target, ["p", "atts-img"]);
e.target.style.height = "auto";
goUnfolder(nodeImgAtt);
}
,"showUnfolderRt":function(e){
var cView = document.cView;
var nodeImgAtt = cView.Utils.getNode(e.target, ["p", "atts-img"]);
cView.Utils.unscroll(function(){
e.target.style.height = "auto";
return nodeImgAtt;
});
cView.Utils.getNode(e.target, ["p", "att-img"]).t.w = e.target.width;
goUnfolder(nodeImgAtt);
}
,"chngAvatar":function(e){
var cView = document.cView;
var Utils = cView.Utils;
var files = e.target.parentNode.cNodes["edit-buttons-upload"].files;
if (!files.length)return;
e.target.disabled = true;
var nodeImg = e.target.getNode(["p","chng-avatar"],["c","sp-avatar-img"]);
nodeImg.src = gConfig.static+"throbber-100.gif";
var inputs = Utils.getInputsByName( e.target.getNode(["p","settings-profile"]));
var id = inputs["id"].value;
var context = cView.contexts[inputs["domain"].value];
var token = context.logins[id].token;
context.api.chngAvatar(token, files[0]).then( function() {
e.target.value = "";
e.target.disabled = false;
context.getWhoami(token).then(function(res){
nodeImg.src = context.logins[id].data.users.profilePictureMediumUrl;
});
});
}
,"addSender": function(e){
var cView = document.cView;
if(document.getElementById("add_sender"))return;
var host = e.target.getNode(["p","add-sender"]);
var nodePopup = cView.Drawer.genAddSender(function(login,context){
if(typeof login === "undefined")return;
var globalId = login.domain + "-" + login.users.id;
if (host.ids.indexOf(globalId) == -1 ) {
host.ids.push(globalId);
cView.updPostTo(login,false, login.users.username);
var victim = document.getElementById("add_sender");
victim.parentNode.removeChild(victim);
regenAttaches(document.getElementsByClassName("post-to")[0]);
}
});
cView.doc.getElementsByTagName("body")[0].appendChild(nodePopup);
nodePopup.className = "user-popup";
nodePopup.style.top = e.pageY;
nodePopup.style.left = e.pageX - nodePopup.clientWidth;
nodePopup.style["z-index"] = 1;
}
,"setSender":function(e){
e.target.getNode(["p","add-sender-dialog"]).id = e.target.id;
}
,"newPostRmSender":function(e){
var host = e.target.getNode(["p","post-to"]);
var ids = document.getElementsByClassName("add-sender")[0].ids;
var globalId = e.target.parentNode.domain + "-" + e.target.parentNode.userid;
ids.splice(ids.indexOf(globalId),1);
host.removeChild(e.target.parentNode);
var rmSenders = host.getElementsByClassName("rm-sender");
if(rmSenders.length == 1)rmSenders[0].hidden = true;
regenAttaches(host);
}
,"unfoldUserDet":function(e){
var cView = document.cView;
document.getElementsByClassName("ud-info")[0].style.display = "flex";
document.getElementsByClassName("ud-fold")[0].hidden = false;
document.getElementsByClassName("ud-unfold")[0].style.display = "none";
cView.Drawer.applyReadMore(document.getElementsByClassName("ud-info")[0]);
}
,"foldUserDet":function(e){
document.getElementsByClassName("ud-info")[0].style.display = "none";
document.getElementsByClassName("ud-fold")[0].hidden = true;
document.getElementsByClassName("ud-unfold")[0].style.display = "block";
}
,"goUserSubs": function(e){
e.target.getNode(["p","uds-subs"]).href =document.location + "/subscriptions";
}
,"goUserSubsc": function(e){
e.target.getNode(["p","uds-subsc"]).href = document.location + "/subscribers";
}
,"goUserComments": function(e){
e.target.getNode(["p","uds-com"]).href = document.location + "/comments";
}
,"goUserLikes": function(e){
e.target.getNode(["p","uds-likes"]).href = document.location +"/likes";
}
,"morePostCtrls":function(e){
if(e.target!=e.currentTarget) return;
var cView = document.cView;
var node = e.target.parentNode;
var nodePost = e.target.getNode(["p","post"]);
var nodeMore = cView.gNodes["adv-cmts"].cloneAll();
nodeMore.user = node.user;
nodeMore.style["z-index"] = 2;
var nodeDisCmt = nodeMore.getElementsByClassName("disable-cmts")[0];
var nodeModCmt = nodeMore.getElementsByClassName("moderate-cmts")[0];
if((typeof nodePost.rawData.commentsDisabled !== "undefined")
&& JSON.parse(nodePost.rawData.commentsDisabled)){
nodeDisCmt.innerHTML = "Enable comments";
nodeDisCmt.action = false;
}else nodeDisCmt.action = true;
if(nodePost.commentsModerated){
nodeModCmt.innerHTML = "Stop moderating comments";
nodeModCmt.action = false;
}else nodeModCmt.action = true;
e.target.appendChild(nodeMore);
cView.Utils.fixPopupPos(nodeMore);
}
,"showDelete": function(e){
var cView = document.cView;
var action = e.target.action;
var nodePost = e.target.getNode(["p","post"]);
nodePost.commentsModerated = action;
var comments = e.target.getNode(["p","post-body"],["c","comments"]).getElementsByClassName("comment");
for(var idx = 0; idx < comments.length; idx++){
var comment = comments[idx];
if (cView.contexts[nodePost.rawData.domain].ids.indexOf(comment.userid) != -1)
continue;
comment.getNode(["c","comment-body"],["c","comment-controls"]).hidden = !action;
}
e.target.innerHTML = action?"Stop moderating comments":"Moderate comments";
e.target.action = !action;
}
,"switchCmts": function(e){
var cView = document.cView;
var nodePost = e.target.getNode(["p","post"]);
var post = nodePost.rawData;
var context = cView.contexts[post.domain];
var spinner = cView.gNodes["spinner"].cloneAll();
var parentNode = e.target.parentNode;
var ctrl = parentNode.replaceChild(spinner, e.target);
context.api.switchCmts(context.logins[post.createdBy].token
,post.id
,e.target.action )
.then(function(res){
post.commentsDisabled = ctrl.action?"1":"0";
ctrl.innerHTML = ctrl.action?"Enable comments":"Disable commnents";
nodePost.getElementsByClassName("cmts-lock-msg")[0].hidden = !ctrl.action;
ctrl.action = !ctrl.action;
parentNode.replaceChild(ctrl, spinner);
try{
parentNode.cNodes["msg-error"].hidden = true;
}catch(e){};
},function(err){
cView.Drawer.makeErrorMsg(err,parentNode);
});
}
,"goSetAccounts": function(e){
e.currentTarget.href = gConfig.front+"settings/accounts";
}
,"goSetAddons": function(e){
e.currentTarget.href = gConfig.front+"settings/addons";
}
,"goSetBlocks": function(e){
e.currentTarget.href = gConfig.front+"settings/blocks";
}
,"goSetCustomUI": function(e){
e.currentTarget.href = gConfig.front+"settings/customui";
}
,"goSetDisplay": function(e){
e.currentTarget.href = gConfig.front+"settings/display";
}
,"setDomainInfo": function(e){
e.target.getNode(["p","settings-login"],["c","info"]).innerHTML = "Log in to "
+ gConfig.domains[e.target.value].msg;
}
,"showRefl": function(e){
var cView = document.cView;
var id = e.target.getNode(["p","reflect-menu-item"],["c","victim-id"]).value;
var metapost = e.target.getNode(["p","metapost"])
var nodesPosts = metapost.getElementsByClassName("post");
for (var idx = 0; idx < nodesPosts.length; idx++)
nodesPosts[idx].hidden = (nodesPosts[idx].id != id);
cView.Drawer.applyReadMore(document.getElementById(id));
var menuItems = metapost.getElementsByClassName("reflect-menu-item");
for (var idx = 0; idx < menuItems.length; idx++){
if (menuItems[idx].cNodes["c","victim-id"].value == id){
menuItems[idx].className = "reflect-menu-item pr-selected";
menuItems[idx].cNodes["star"].hidden = true;
}
else menuItems[idx].className = "reflect-menu-item pr-deselected";
}
}
,"toggleSidebar":function(e){
var sidebar = document.getElementById("sidebar");
var showSb = document.getElementById("show-sidebar");
sidebar.classList.toggle("sidebar-h");
showSb.classList.toggle("hidden");
}
,"setChkboxOption":function(e){
var cView = document.cView;
cView.localStorage.setItem(e.target.value, e.target.checked );
}
,"unfoldReadMore":function(e){
var cView = document.cView;
var wrapper = e.target.getNode(["p","read-more-wrapper"]);
var victim = wrapper.cNodes["content"];
victim.innerHTML = victim.words;
victim.isUnfolded = true;
cView.Utils.setChild(wrapper.parentNode, victim.classList[0],victim );
window.dispatchEvent(new CustomEvent("updNode", {"detail":victim}));
}
,"remBlockingItem":function(e){
var cView = document.cView;
var victim = cView.Utils.getNode(e.target,["p","blocks-item"]);
var domain = victim.getNode(["p","blocks-settings-page"],["c","domain"]).value;
var inputs = cView.Utils.getInputsByName(victim);
switch(inputs.type.value){
case "str":
var strings = cView.blocks.blockStrings[domain];
var idx = strings.indexOf(inputs.val.value);
if(idx != -1) strings.splice(idx, 1);
cView.Common.updateBlockList("blockStrings", domain, inputs.val.value, false);
break;
case "posts":
case "cmts":
cView.Common.updateBlockList(
cView.blockLists[inputs.type.value]
,domain
,inputs.val.value
,false
);
break;
}
victim.parentNode.removeChild(victim);
}
,"addBlockingString":function(e){
var cView = document.cView;
if((e.type != "click")&& (e.which != "13")) return ;
var str = cView.Utils.getInputsByName(e.target.getNode(["p","controls"]))["strToBlock"].value.trim();
var host = e.target.getNode(["p","blocks-settings-page"]);
var domain = host.getNode(["c","domain"]).value;
var item = cView.gNodes["blocks-item"].cloneAll();
var inputs = cView.Utils.getInputsByName(item);
if((typeof cView.blocks.blockStrings[domain] !== "undefined")
&& (cView.blocks.blockStrings[domain].indexOf(str) != -1 ))return;
inputs["type"].value = "str";
inputs["val"].value = str;
item.cNodes["title"].innerHTML = str;
host.getNode(["c","strings"],["c","content"]).appendChild(item);
cView.Common.updateBlockList("blockStrings", domain, str, true);
}
,"copyBlockingStrings": function(e){
var cView = document.cView;
var host = e.target.getNode(["p","blocks-settings-page"]);
var domain = host.getNode(["c","domain"]).value;
cView.tmp = cView.blocks.blockStrings[domain];
var buttons = cView.doc.getElementsByTagName("button");
for (var idx = 0; idx < buttons.length; idx++) {
if(buttons[idx].className == "paste")buttons[idx].disabled = false;
}
}
,"pasteBlockingStrings": function(e){
var cView = document.cView;
var host = e.target.getNode(["p","blocks-settings-page"]);
var domain = host.getNode(["c","domain"]).value;
if(!Array.isArray(cView.blocks.blockStrings[domain]))
cView.blocks.blockStrings[domain] = new Array();
var arr = cView.blocks.blockStrings[domain];
cView.blocks.blockStrings[domain] = arr.concat(
cView.tmp.filter(function (item) { return arr.indexOf(item) < 0; })
);
var buttons = cView.doc.getElementsByTagName("button");
for (var idx = 0; idx < buttons.length; idx++) {
if(buttons[idx].className == "paste")buttons[idx].disabled = true;
}
delete cView.tmp;
cView.Utils.setChild(
host.cNodes["strings"]
,"content"
,cView.Drawer.genBlockStrPage(domain)
);
cView.Common.updateBlockList();
}
,"setHideCups": function(e){
var cView = document.cView;
var nodeCtrl = e.target.getNode(["p" ,"blocks-settings-page-ctrl"]);
cView.localStorage.setItem("addons-linkcups-hide"
,cView.Utils.getInputsByName(nodeCtrl)["hideCups"].checked
);
}
,"toggleHighlightCmts": function(e){
var cView = document.cView;
var node = e.target;
if (node.tagName.toLowerCase() != "a"){
node = cView.Utils
.getNode(node,["p","cmt-author"])
.getElementsByTagName("a")[0];
}
e.stopPropagation();
var nodePost = cView.Utils.getNode(node,["p","post"]);
var domain = nodePost.rawData.domain;
var username = node.href.substr(gConfig.front.length+4+domain.length);
var userid = cView.contexts[domain].gUsers.byName[username].id;
if(typeof userid === "undefined" )return;
var nodesCmts = nodePost.getElementsByClassName("comment");
for (var idx = 0; idx < nodesCmts.length; idx++) {
if(nodesCmts[idx].userid == userid)
nodesCmts[idx]
.classList
.toggle("highlighted");
}
}
,"selectAll": function(e){
e.target.setSelectionRange(0, e.target.value.length);
}
,"foldComments":function(e){
var cView = document.cView;
var nodePost = e.target.getNode(["p","post"]);
var post = nodePost.rawData;
var context = cView.contexts[post.domain];
var host = cView.doc.createElement("div");
host.className = "comments";
host.appendChild(cView.Drawer.genComment.call(context, context.gComments[post.comments[0]]));
var nodeLoad = cView.gNodes["comments-load"].cloneAll();
nodeLoad.getElementsByClassName("num")[0].innerHTML = post.omittedComments + post.comments.length;
host.appendChild(nodeLoad);
host.appendChild(cView.Drawer.genComment.call(context, context.gComments[post.comments[post.comments.length - 1]]));
if (nodePost.rtCtrl.isBeenCommented == true){
var nodeComment = cView.Drawer.genAddComment(context);
host.appendChild(nodeComment);
nodeComment.getElementsByClassName("edit-txt-area")[0].value = nodePost.getElementsByTagName("textarea")[0].value;
}
var refNode = nodePost.getNode(["c","post-body"],["c","many-cmts-ctrl"]);
var refTop = refNode.getBoundingClientRect().top;
cView.Utils.setChild(nodePost.cNodes["post-body"],"comments", host);
cView.Drawer.applyReadMore( host);
window.scrollBy(0,refNode.getBoundingClientRect().top - refTop);
nodePost.getNode(["c","post-body"],["c","many-cmts-ctrl"]).hidden = true;
}
,"submitCuUm": function(e){
var cView = document.cView;
var customFunctions = require("./custom_functions.json");
var item = cView.gNodes["custom-ui-item"].cloneAll(true);
var host = cView.doc.getElementById("custom-ui-um-display")
var slots = cView.Utils.getInputsByName(item);
var inputs = cView.Utils.getInputsByName(cView.doc.getElementById("custom-ui-um-control"));
var functionId = cView.doc.getElementById("cu-um-function").value;
var options = cView.doc.getElementById("cu-um-function").getElementsByTagName("option");
if(functionId == "spacer"){
slots["type"].value = "spacer";
item.cNodes["title"].innerHTML = "•";
host.appendChild(item);
clearCU();
return;
}
for(var idx = 0; idx < options.length; idx++ ) if(options[idx].selected){
options[idx].disabled = true;
break;
}
if ((typeof inputs["label"].value === "undefined")|| (inputs["label"].value == "")){
if((typeof inputs["icon"].value !== "undefined") && inputs["icon"].value != "" ){
slots["val"].value = inputs["icon"].value;
var icon = cView.doc.createElement("i");
icon.className = "fa fa-2x fa-" + inputs["icon"].value;
item.cNodes["title"].appendChild(icon);
}else{
slots["val"].value = customFunctions[functionId].descr;
item.cNodes["title"].innerHTML = customFunctions[functionId].descr;
}
}else{
slots["val"].value = inputs["label"].value;
item.cNodes["title"].innerHTML = inputs["label"].value
.trim().replace(/&/g,"&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
options[0].selected = true;
slots["type"].value = functionId;
item.title = functionId;
host.appendChild(item);
clearCU();
cView.localStorage.setItem(
"custom-ui-upper"
,JSON.stringify(cView.Common.regenCustomUi(host))
);
function clearCU(){
Object.keys(inputs).forEach(function(name){inputs[name].value = ""});
cView.doc.getElementById("cu-um-icon").firstChild.className = "";
};
}
,"customUILabelInput":function(e){
var cView = document.cView;
var inputs = cView.Utils.getInputsByName(cView.doc.getElementById("custom-ui-um-control"));
inputs["icon"].value;
cView.doc.getElementById("cu-um-icon").firstChild.className = "";
}
,"selectIcon": function(e){
if (document.getElementById("selector-fa-dialog")) return;
var cView = document.cView;
var host = e.target.getNode(["p","select-ico"]);
var inputs = cView.Utils.getInputsByName(e.target.getNode(["p","custom-ui-um-control"]));
var dlg = cView.FaSelector.makeSelector(cb);
var innerWidth = window.innerWidth;
dlg.style.opacity = 0;
//cView.doc.getElementsByTagName("body")[0].appendChild(dlg);
host.appendChild(dlg);
dlg.style.top = 0;
dlg.style.left = 0;
var width = dlg.offsetWidth;
dlg.style.top = e.pageY;
dlg.style.left = e.pageX;
if(dlg.offsetLeft + width > innerWidth){
dlg.style.left = "auto";
dlg.style.right = "1em";
}
dlg.style["z-index"] = 2;
dlg.style.opacity = 1;
host.body.appendChild(dlg);
//document.body.appendChild(dlg);
function cb(name){
inputs["icon"].value = name;
inputs["label"].value = "";
host.getNode(["c","cu-um-icon"], ["c","i"]).className = "fa fa-2x fa-" + name;
}
}
,"remCustomUiItem": function(e){
var cView = document.cView;
var victim = e.target.getNode(["p","custom-ui-item"]);
var host = victim.getNode(["p","custom-ui-um-display"]);
victim.parentNode.removeChild(victim);
cView.localStorage.setItem(
"custom-ui-upper"
,JSON.stringify(cView.Common.regenCustomUi(host))
);
var inputs = cView.Utils.getInputsByName(victim);
var options = cView.doc.getElementById("cu-um-function").getElementsByTagName("option");
for(var idx = 0; idx < options.length; idx++ ) if(options[idx].value == inputs.type.value){
options[idx].disabled = false;
break;
}
}
,"notMentions": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications?filter=mentions";
}
,"notSubs": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications?filter=subscriptions";
}
,"notGroups": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications?filter=groups";
}
,"notDirect": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications?filter=directs";
}
,"notBans": function(e){
e.currentTarget.href = gConfig.front+ "filter/notifications?filter=bans";
}
,"postEditPaste": function(e){
if (e.clipboardData.types.indexOf("Files") == -1) return;
Array.prototype.slice.call(e.clipboardData.files).forEach(function(file){
appendAttachment(
e.target.getNode(["p","new-post"])
, file.name
, file
);
});
}
,"summDay": function(e){
var cView = document.cView;
var src = is(cView.summarySource)?cView.summarySource:"";
e.currentTarget.href = gConfig.front+src+"summary/1"
}
,"summWeek": function(e){
var cView = document.cView;
var src = is(cView.summarySource)?cView.summarySource:"";
e.currentTarget.href = gConfig.front+src+"summary/7"
}
,"summMonth": function(e){
var cView = document.cView;
var src = is(cView.summarySource)?cView.summarySource:"";
e.currentTarget.href = gConfig.front+src+"summary/30"
}
,"goMemories": function(e){
var cView = document.cView;
var txtDate = "";
txtDate = e.target.getNode(["p","memories-selector"], ["c", "memories-date"] ).value;
if(txtDate != "")
window.location = gConfig.front+"memories/"+txtDate.replace(/-/g,"");
}
,"acceptCookies": function(){
var cView = document.cView;
cView.Common.setCookie("privacy","accepted");
var nodePriv = cView.doc.getElementById("privacy-popup");
nodePriv.parentNode.removeChild(nodePriv);
}
};
return _Actions;
});
<file_sep>require("./styles/_expanded.css");
<file_sep>"use strict";
define(["./utils", "./freefeed_rt"],function(utils, RtUpdate ){
return function(config){
function get(token, url){
return utils.xhr( {"url":config.serverURL +url ,"token":token });
}
function get2(token, url){
return utils.xhr( {"url":config.serverURLV2 +url ,"token":token });
}
return{
"name": "FreeFeed"
,"protocol":{
"get": get
,"getTimeline": function(token, timeline, skip, mode) {
if (timeline == "filter/best_of") return get2( token
,"bestof" + "?offset="+skip
);
if (timeline == "filter/everything") return get2( token
,"everything" + "?offset="+skip
);
if (timeline == "home"){
var modeQ = "";
if(typeof mode == "string" )
modeQ = "&homefeed-mode="+ mode;
return get2( token
,"timelines/home" + "?offset="+skip + modeQ
);
}
return get2( token
,"timelines/"+ timeline + "?offset="+skip
);
}
,"getSearch": function(token, search, skip) {
return get2( token
,"search?qs=" + search + "&offset="+skip
).then(function(res){
res = JSON.parse(res);
res.timelines = {"id":search};
return res;
});
}
,"getNotifications": function(token, search, skip) {
return get2( token
,"notifications?offset="+skip+(search?("&"+search):"")
).then(function(res){
utils.xhr({
"url": config.serverURLV2
+"users/markAllNotificationsAsRead"
,"method":"post"
,"token": token
,"headers":{"Content-type":"application/json"}
});
return res;
});
}
,"getSummary": function(token,source,interval){
var address = "summary/" +(source?source+"/":"") +interval;
return get2(token ,address);
;
}
,"getMemories": function(token,source,interval, skip){
var address = "timelines/" + source
+"/?created-before="+interval.toISOString()
+"&sort=created"
+"&offset="+skip;
return get2(token ,address);
;
}
,"getPost": function(token, path, arrOptions) {
var id = path.split("/")[1];
var likes = "0";
var cmts = "0";
if(Array.isArray(arrOptions))arrOptions.forEach(function(option){
switch(option){
case "likes":
likes = "all";
break;
case "comments":
cmts = "all";
}
});
var suffix = "?maxComments=" + cmts + "&maxLikes=" + likes;
return get2(token, "posts/"+ id + suffix);
}
,"sendPost": function(token, postdata){
return utils.xhr(
{ "url": config.serverURL + "posts"
,"token": token
,"method": "post"
,"data": JSON.stringify(postdata)
,"headers":{"Content-type":"application/json"}
}
);
}
,"editPost": function(token, id, postdata){
return utils.xhr(
{ "url": config.serverURL + "posts/"+id
,"token": token
,"method": "put"
,"data": JSON.stringify(postdata)
,"headers":{"Content-type":"application/json"}
}
);
}
,"deletePost": function(token, id){
return utils.xhr(
{ "url": config.serverURL + "posts/"+id
,"token": token
,"method": "delete"
}
);
}
,"switchCmts": function(token, id, action){
return utils.xhr(
{ "url":config.serverURL
+"posts/" + id
+ (action?"/disableComments":"/enableComments")
,"token":token
,"method":"post"
}
);
}
,"sendHide": function(token, id, action){
return utils.xhr(
{ "url": config.serverURL
+ "posts/" + id + "/"
+ (action?"hide":"unhide")
,"token": token
,"method": "post"
}
);
}
,"getUser": function(token, req) {return get(token, "users/" + req );}
,"getSubs": function(token, req) {return get(token, "users/" + req );}
,"doBan": function(token, username, action){
return utils.xhr(
{ "url": config.serverURL
+ "users/" + username + "/"
+ (action?"ban":"unban")
,"token": token
,"method": "post"
}
);
}
,"get": function(token, timeline) {return get(token, timeline);}
,"updProfile" : function(token, id, data){
return utils.xhr(
{ "url": config.serverURL + "users/" + id
,"token": token
,"method": "put"
,"data": JSON.stringify(data)
,"headers":{"Content-type":"application/json"}
}
);
}
,"chngAvatar": function (token, file){
var data = new FormData();
data.append( "file",file) ;
return utils.xhr(
{ "url": config.serverURL + "users/updateProfilePicture"
,"token": token
,"method": "post"
,"data": data
}
);
}
,"_getWhoami": function(token){
var whoami = get2( token ,"users/whoami");
var groupReqs = get2( token ,"managedGroups" );
return utils._Promise.all([whoami,groupReqs])
.then(function(res){
var whoami = JSON.parse(res[0]);
if (!Array.isArray(whoami.requests))
whoami.requests = new Array();
if (!Array.isArray(whoami.users.subscriptionRequests))
whoami.users.subscriptionRequests = new Array();
whoami.requests.forEach(function(req){
req.type = "user";
if (whoami.users.subscriptionRequests.indexOf(req.id ) != -1){
req.dest = whoami.users.id;
req.src = req.id;
} else {
req.dest = req.id;
req.src = whoami.users.id;
}
});
var grps = JSON.parse(res[1]);
var grpReqs = new Array();
grps.forEach(function(grp){
grp.requests.forEach(function(req){
req.type = "group";
req.dest = grp.id;
res.src = req.id;
grpReqs.push(req);
whoami.users.subscriptionRequests.push(grp.id);
});
});
whoami.requests = whoami.requests.concat(grpReqs);
return whoami;
});
}
,"login":function(username, password){
var data = "username="+utils.encodeURIForm(username)
+ "&password="+utils.encodeURIForm(password);
return utils.xhr(
{ "url": config.serverURL + "session"
,"headers":{"Content-type":"application/x-www-form-urlencoded"}
,"method": "post"
,"data":data
}
);
}
,"sendLike": function(token, id, action){
return utils.xhr(
{ "url": config.serverURL
+ "posts/" + id + "/"
+ (action?"like":"unlike")
,"token": token
,"method": "post"
}
);
}
,"sendComment": function(token, postdata){
return utils.xhr(
{ "url": config.serverURL + "comments"
,"token": token
,"method": "post"
,"data": JSON.stringify(postdata)
,"headers":{"Content-type":"application/json"}
}
);
}
,"editComment": function(token, id, postdata){
return utils.xhr(
{ "url": config.serverURL + "comments/"+id
,"token": token
,"method": "put"
,"data": JSON.stringify(postdata)
,"headers":{"Content-type":"application/json"}
}
);
}
,"deleteComment": function(token, id){
return utils.xhr(
{ "url": config.serverURL + "comments/"+id
,"token": token
,"method": "delete"
}
);
}
,"reqSub": function(token,username ){
return utils.xhr(
{ "url": config.serverURL
+ "users/" + username
+ "/sendRequest/"
,"token": token
,"method": "post"
}
);
}
,"evtSub": function(token,username, subscribed ){
return utils.xhr(
{ "url": config.serverURL
+ "users/" + username
+ (subscribed?"/unsubscribe":"/subscribe")
,"token": token
,"method": "post"
}
);
}
,"reqResp": function(token, user, action, reqid, type, dest){
var req = (type == "user"? [type + "s", action, user]
:[type + "s", dest, action, user]
).join("/");
return utils.xhr(
{ "url": config.serverURL + req
,"token": token
,"method": "post"
}
);
}
,"sendAttachment": function(token,file, filename){
var data = new FormData();
data.append( "name", "attachment[file]");
data.append( "attachment[file]",file, filename);
return utils.xhr(
{ "url": config.serverURL + "attachments"
,"token": token
,"method": "post"
,"data": data
}
);
}
,"resetDirectsCount":function(token){
return get2( token ,"users/markAllDirectsAsRead");
}
}
,"parse":function (res){
return (typeof res == "string")?JSON.parse(res):res;
}
,"oRT":RtUpdate
};
};
});
<file_sep># pyt-vanilla-html
The master branch is available at <http://myfeed.rocks/b/>
## Setup
You may want to edit `domains.json` for information about supported back ends.
Use `tools/deploy.sh` to collect all the necessary stuff in a desired deployment directory
You can do it manually, with the following steps:
1. Install necessary npm modules: `$ npm install`
1. Run webpack `$ webpack --config config.js` to make a bundle file
1. Copy the files listed in `release.lst` to a deployment directory
1. Optionally you can edit `index.html` and update md5 hash values of `vanilla.js` and `config.json` to prevent caching outdated files
Then put there and edit `config.josn`:
- the path on your server as "front"
- the path to the files as "static"
- the list of back ends you want to serve in "domains"
Then set up the web server to rewrite all the requests to `index.html`, accept those which go to `static`
To have server-side rendering install necessary npm modules: `$ npm install`
Create server-side rendering script `$ webpack --config config_srv.js`
Use the function exported by `vanilla_srv.js` module to handle http requests with `http.createServer`. First parameter is the request, second is the response.
### Example
You put everything in `/var/pyt-vanilla-html` web directory and you want to access it form `/vanilla`
`$ tools/deploy.sh -d /var/pyt-vanilla-html`
Then you add the following to your web server config:
```
...
location ~ /vanilla/ {
add_header Cache-Control no-cache;
rewrite ^/vanilla/s(/.*) /pyt-vanilla-html$1 break;
rewrite ^.* /pyt-vanilla-html/index.htm break;
}
...
```
And `config.json`
```
var gConfig = {
"front":"https://{mydomain}/vainlla/"
, "static":"https://{mydomain}/vainlla/s/"
, "leadDomain": "FreeFeed"
, domains: ["FreeFeed", "MyOtherFF"]
...
```
<file_sep>#!/bin/bash
while getopts ":d:b:p:" opt; do
case $opt in
d)
dest=$OPTARG
;;
b)
backup=$OPTARG
;;
p)
SRVPATH=$OPTARG
;;
esac
done
if [ -z $dest ]
then
echo "Deploy destenation should be set"
echo "usage: $0 -d dest_dir [-b backup_dir] [-p path_on_server]"
exit 1;
fi
if [ ! -d $dest ]
then
mkdir $dest
fi
echo "Will deploy to $dest"
if [ $backup ]
then
echo "Will backup to $backup"
fi
if [ $SRVPATH ]
then
echo "Will serve from $SRVPATH"
else
echo "Will serve from /"
fi
dir=`mktemp -d`
git clone -b master . $dir
cd $dir
npm install
env ___BUILD___=stable_`git rev-parse --short HEAD` ./node_modules/.bin/webpack --config config.js
for file in $(ls *.js *.css *.json); do
MD5=`md5sum $file|awk '{ print $1 }'`
sed -i -e "s/\(.*$file.md5=\)\w*\"/\1$MD5\"/" index.htm
done
if [ $SRVPATH ]
then
SRVPATH=`echo $SRVPATH| sed -e 's%^/%%' -e 's%/$%%'`
sed -i -e "s?/s/?/$SRVPATH/s/?" index.htm
fi
if [ $backup ]
then
if [ ! -d $backup ]
then
mkdir $backup
fi
cp -f $dest/* $backup
fi
cat release.lst | xargs -l -i cp -f "{}" $dest
cd /tmp
rm -rf $dir
<file_sep>"use strict";
define( function(){
function _Common(view){
this.cView = view;
};
_Common.prototype = {
constructor:_Common
,"setCookie": function(name, data){
var cView = this.cView;
//var hostname = window.location.hostname.split(".");
//hostname.reverse();
cView.doc.cookie = name
+"="+data
+";expires=" + new Date(Date.now()+3600000*24*365).toUTCString()
// +"; domain="+ hostname[1] + "." + hostname[0]
+"; path=/"
+";secure";
}
,"getCookie": function(name){
var cView = this.cView;
var arrCookies = cView.doc.cookie.split(";");
var res;
arrCookies.some(function(c){
var cookie = c.split("=");
if(cookie[0].trim() == name ){
res = decodeURIComponent(cookie[1]);
return true;
}
});
return res;
}
,"deleteCookie": function(name){
var cView = this.cView;
var hostname = window.location.hostname.split(".");
hostname.reverse();
var cookie = name
+"=;expires=" + new Date(0).toUTCString()
+"; domain="+ hostname[1] + "." + hostname[0]
+"; path=/";
cView.doc.cookie = cookie;
cookie = name
+"=;expires=" + new Date(0).toUTCString()
+"; path=/";
cView.doc.cookie = cookie;
}
,"addUser": function(user){
var context = this;
var cView = context.cView;
if (typeof context.gUsers[user.id] !== "undefined" ){
var localUser = context.gUsers[user.id];
Object.keys(user).forEach(function(key){
if (user[key] != "")
localUser[key] = user[key];
});
return localUser;
}
var className = "not-my-link";
if (typeof user.screenName === "undefined")
user.screenName = user.username;
(function(screenName){
user.untagScreenName = screenName.replace(/&/g,"&")
.replace(/</g, "<")
.replace(/>/g, ">");
})(user.screenName);
user.domain = context.domain;
if(typeof user.isPrivate !== "undefined")user.isPrivate = JSON.parse(user.isPrivate);
if (cView.mode == null) cView.mode = "screen";
switch(cView.mode){
case "screen":
user.title = user.untagScreenName;
break;
case "screen_u":
if(user.screenName != user.username)
user.title = user.untagScreenName + " <div class=username>(" + user.username + ")</div>";
else user.title = "<div class=username>"+user.username+"</div>";
break;
case "username":
user.title = "<div class=username>"+user.username+"</div>";
}
if(typeof context.logins[user.id] !== "undefined"){
user.my = true;
className = "my-link-"+context.domain+"-"+user.id;
}else{
user.my = false;
className = "not-my-link";
}
user.link = '<a class="'+className
+'" target="_blank" href="' + gConfig.front+"as/"+ context.domain + "/"+ user.username+'">'
+ user.title
+"</a>";
if((typeof user.profilePictureMediumUrl === "undefined")
||(user.profilePictureMediumUrl == ""))
user.profilePictureMediumUrl = gConfig.static+ "default-userpic-48.png";
user.friend = false;
user.subscriber = false;
context.gUsers[user.id] = user;
context.gUsers.byName[user.username] = user;
return user;
}
,"genNodes": function (templates){
var cView = this.cView;
var nodes = new Array();
var nodesByName = new Object();
//oTemplates = JSON.parse(templates);
templates.forEach(function(template) {
if (!template.t)template.t = "div";
var node;
if(template.pt){
node = nodesByName[template.pt].cloneAll();
if(!Array.isArray(template.cl)) template.cl = new Array();
node.className.split(" ").forEach(function(className){
template.cl.push(className);
});
}else node = cView.doc.createElement(template.t);
node.cloneAll = function(){
var newNode = this.cloneNode(true);
genCNodes(newNode, this);
return newNode;
};
if(template.c){
node.className = template.c;
nodesByName[template.c] = node;
}
if(template.cl)template.cl.forEach(function(c){node.classList.add(c);});
if(template.el)
cView.Common.genNodes(template.el).forEach(function(victim){
node.appendChild(victim);
});
if(template.txt) node.innerHTML = template.txt;
if(template.e) node.e = template.e;
var dummy = cView.doc.createElement("span");
if(template.p) for( var p in template.p){
dummy.innerHTML = template.p[p];
try{node[p] = dummy.textContent;}
catch(e){};
}
if(template.style) for( var s in template.style){
try{node.style[s] = template.style[s];}
catch(e){};
}
nodes.push(node);
} );
return nodes;
function genCNodes(node, proto){
node.cNodes = new Object();
node.getNode = function(){
var args = cView.Utils.args2Arr.apply(this,arguments);
args.unshift(node);
return cView.Utils.getNode.apply(node, args);
};
for(var idx = 0; idx < node.children.length; idx++){
genCNodes(node.children[idx], proto.children[idx]);
if(typeof node.children[idx].classList !== "undefined")
node.cNodes[node.children[idx].classList[0]] = node.children[idx];
}
if (typeof proto.e == "undefined" ) return;
Object.keys(proto.e).forEach(function(evt){
var action = proto.e[evt];
node.addEventListener(evt,cView[action[0]][action[1]]);
});
}
}
,"refreshLogin": function(id, context){
var cView = context.cView;
var user = context.logins[id].data.users;
delete context.gUsers[id];
cView.Common.addUser.call(context, user);
var links = cView.doc.getElementsByClassName("my-link-" + context.domain+ "-" + id);
for(var idx = 0; idx< links.length; idx++)
links[idx].outerHTML = user.link;
var login = context.logins[id].data;
if(typeof login.subscribers !== "undefined")
Object.keys(login.subscribers).forEach(function(id){
cView.Common.addUser.call(context, login.subscribers[id]);
});
login.oFriends = new Object();
var oSubscriptions = new Object();
if(typeof login.subscriptions !== "undefined" ){
login.subscriptions.forEach(function(sub){
if(sub.name == "Posts"){
oSubscriptions[sub.id] = sub.user;
}
});
}
if (typeof user.subscriptions !== "undefined"){
user.subscriptions.forEach(function(subid){
var userid = oSubscriptions[subid];
login.oFriends[userid] = true;
})
}
if ((typeof user.subscribers !== "undefined")
&& (typeof user.subscriptions !== "undefined")){
login.subscribers.forEach(cView.Common.addUser,context);
user.subscribers.forEach(function(sub){
cView.Common.addUser.call(context, sub);
context.gUsers[sub.id].subscriber = true;
});
user.subscriptions.forEach(function(subid){
var userid = oSubscriptions[subid];
if (typeof userid !== "undefined") {
if (typeof context.gUsers[userid] !== "undefined")
context.gUsers[userid].friend = true;
}
});
}
cView.Common.saveLogins();
var nodesMenu = document.getElementsByClassName("controls-anon");
if(nodesMenu.length){
var nodeMenu = nodesMenu[0];
cView.Utils.setChild(
nodeMenu.parentNode
,"controls"
,cView.gNodes["controls-login"].cloneAll()
);
}
var nodeSR = cView.doc.getElementById("sr-info");
window.dispatchEvent(new CustomEvent("whoamiUpdated"));
if (!nodeSR) return;
cView.Drawer.updateReqs();
}
,"setIcon": function (ico){
var cView = this.cView;
var linkFavicon = cView.doc.getElementById("favicon");
if (linkFavicon) linkFavicon.parentNode.removeChild(linkFavicon);
linkFavicon = cView.doc.createElement('link');
linkFavicon.id = "favicon";
linkFavicon.type = 'image/x-icon';
linkFavicon.rel = 'shortcut icon';
linkFavicon.href = gConfig.static + ico;
cView.doc.getElementsByTagName('head')[0].appendChild(linkFavicon);
}
,"auth": function (check){
var cView = document.cView;
cView.Common.setIcon("favicon.ico");
var nodeAuth = cView.doc.createElement("div");
nodeAuth.className = "nodeAuth";
nodeAuth.innerHTML ='<div id=auth-msg style="color:red; font-weight: bold;"> </div>'
+'<div style="text-align:center;margin-bottom:.5em;"><h3>'+gConfig.leadDomain +'</h3></div>'
+'<div>' + gConfig.domains[gConfig.leadDomain].msg + '</div>'
+'<form action="javascript:" id=a-form><table><tr><td>Username</td><td><input name="username" id=a-user type="text"></td></tr><tr><td>Password</td><td><input name="password" id=a-pass type="password"></td></tr><tr><td> </td><td><input type="submit" value="Log in" style=" font-size: large; height: 2.5em; width: 100%; margin-top: 1em;" ></td></tr></table></form>';
cView.doc.getElementsByTagName("body")[0].appendChild(nodeAuth);
cView.doc.getElementById("a-form").addEventListener("submit",cView.Actions.getauth);
}
,"updateBlockList": function(tag, domain, value, add){
var cView = document.cView;
if (typeof tag === "undefined")
return cView.localStorage.setItem("blocks", JSON.stringify(cView.blocks));
var context = cView.contexts[domain];
var list = cView.blocks[tag][domain];
var fArray = ["blockStrings"].indexOf(tag) != -1;
if(add){
if ((typeof list === "undefined") || (list == null))
fArray?(list = new Array()):(list = new Object()) ;
fArray?(list.push(value)):(list[value] = context.gUsers[value].username);
}else try{
if (fArray){
var idx = list.indexOf(value);
if(idx != -1)list.splice(idx,1);
}else delete list[value];
}catch(e){};
cView.blocks[tag][domain] = list;
cView.localStorage.setItem("blocks", JSON.stringify(cView.blocks));
}
,"setFrontUrl": function(url){
Object.keys(gConfig.domains).forEach(function(domain){
url = url.replace(
new RegExp("^(.*:\/\/)?("
+gConfig.domains[domain].fronts.join("|")
+")\/(?!as|settings|about|"
+gConfig.domains[domain].urlSkip.join("|")
+")"
)
,gConfig.front+"as/"+domain+"/"
);
});
return url;
}
,"urlsToCanonical": function(text){
Object.keys(gConfig.domains).forEach(function(domain){
text = text.replace(new RegExp(gConfig.front.slice(8)+"as/"+domain)
,gConfig.domains[domain].front
);
});
return text;
}
,"loadGlobals":function(data, context){
var cView = context.cView;
context.ids.forEach(function(id){
cView.Common.addUser.call(context, context.logins[id].data.users);
});
if(data.attachments)data.attachments.forEach(function(attachment){ context.gAttachments[attachment.id] = attachment; });
if(data.comments)data.comments.forEach(function(comment){ context.gComments[comment.id] = comment; });
if(data.users)data.users.forEach(cView.Common.addUser, context);
if(data.groups)data.groups.forEach(cView.Common.addUser, context);
if(data.subscribers) data.subscribers.forEach(cView.Common.addUser, context);
if(data.subscribers && data.subscriptions ){
var subscribers = new Object();
data.subscribers.forEach(function(sub){subscribers[sub.id]=sub;});
data.subscriptions.forEach(function(sub){
if(["Posts", "Directs"].indexOf(sub.name) != -1 ){
var user = context.gUsers[sub.user];
var isPrivate = (sub.mayNotBePublic == true)?true:(user.isPrivate == "1");
context.gFeeds[sub.id] = {
"user":user
,"direct": (sub.name == "Directs")
,"isPrivate": isPrivate
,"isProtected": user.isProtected == "1"
}
}
});
}
}
,"loadLogins":function(){
var cView = this.cView;
var Common = cView.Common;
Object.keys(cView.contexts).forEach(function(domain){
var context = cView.contexts[domain];
var token = Common.getCookie(gConfig.domains[domain].tokenPrefix +"authToken");
if(token){
context.token = token;
context.pending.push(token);
}
});
var txtgMe = cView.localStorage.getItem("logins");
if (txtgMe){
try{
var logins = JSON.parse(txtgMe);
logins.forEach(function(login) {
var domain = login.domain;
var context = cView.contexts[domain];
if(typeof context === "undefined") return;
var pPos = context.pending.indexOf(login.token);
if( pPos != -1)context.pending.splice(pPos,1);
if(login.isMain == true)context.token = login.token;
if (typeof login.data === "undefined"){
context.pending.push(login.token);
return;
}
context.logins[login.data.users.id] = login;
Common.addUser.call(context, login.data.users);
Common.refreshLogin(login.data.users.id, context);
});
}catch(e){
console.log(e);
cView.localStorage.removeItem("logins");
}
}
Object.keys(cView.contexts).forEach(function(domain){
var context = cView.contexts[domain];
if(!context.token){
if(context.ids.length){
context.token = context.logins[context.ids[0]].token;
}else if (context.pending.length)
context.token = context.pending[0];
}
context.p = cView.Utils._Promise.all(
context.pending.map(function(token){
return context.getWhoami(token);
})
);
});
}
,"saveLogins": function(){
var cView = this.cView;
var logins = new Array();
Object.keys(cView.contexts).forEach(function (domain){
var context = cView.contexts[domain];
if(!context.token){
cView.Common.deleteCookie(gConfig.domains[domain].tokenPrefix +"authToken",context.token );
return;
}
cView.Common.setCookie(gConfig.domains[domain].tokenPrefix +"authToken",context.token );
Object.keys(context.logins).forEach(function(id){
context.logins[id].isMain = (context.logins[id].token == context.token);
logins.push(context.logins[id]);
});
});
cView.localStorage.setItem("logins", JSON.stringify(logins));
}
,"calcPostScore":function(post){
var cView = this.cView;
var context = cView.contexts[post.domain];
if (post.domain == gConfig.leadDomain) return 100;
else return 0;
}
,"markMetaMenu": function(nodePost){
var host = nodePost.parentNode;
if ((nodePost.hidden != true) || (host.className != "metapost"))
return;
var menuItems = host.getElementsByClassName("reflect-menu-item");
for(var idx = 0; idx < menuItems.length; idx++)
if (menuItems[idx].cNodes["victim-id"].value == nodePost.id)
menuItems[idx].cNodes["star"].hidden = false;
}
,"metapost":function (posts){
var bumpedAt = posts[0].bumpedAt;
var initPos = posts[0].initPos;
var dups = new Array();
var hidden = true;
posts.forEach(function(post){
if (bumpedAt < post.bumpedAt)bumpedAt = post.bumpedAt;
if (post.isHidden !== true) post.isHidden = false;
if(!dups.some(function(dup){ return (dup.domain == post.domain)&&(dup.id == post.id);}))
dups.push(post);
hidden = hidden && post.isHidden;
});
var ret = {
"type": "metapost"
,"bumpedAt":bumpedAt
,"dups":dups
,"sign":posts[0].sign
,"isHidden":hidden
,"initPos":initPos
};
Object.defineProperty(ret, "idx",{
"get":function(){
return this.index;
}
,"set": function(idx){
this.index = idx;
this.dups.forEach(function(dup){dup.idx = idx;});
}
});
return ret;
}
,"chkBlocked":function(post){
var cView = this.cView;
var context = cView.contexts[post.domain];
var listBlockByUsr = cView.blocks.blockPosts[context.domain];
var listBlockByStr = cView.blocks.blockStrings[context.domain];
if(cView.noBlocks ) return false;
if(cView.blockLonely
&& !(Array.isArray(post.comments) && post.comments.length)
&& !(Array.isArray(post.likes) && post.likes.length)
&& (context.ids.indexOf(post.createdBy) == -1)
) return true;
if( ( typeof listBlockByUsr !== "undefined")
&& ( listBlockByUsr != null)
&& (listBlockByUsr[post.createdBy]
|| post.postedTo.some(function (dest){
var id = context.gFeeds[dest].user.id
return listBlockByUsr[id] && (cView.origin != id);
})
)
) return true;
if ( ( typeof listBlockByStr!== "undefined")
&& ( listBlockByStr != null)
&& listBlockByStr.some(function(str){
return post.body.toLowerCase().indexOf(str.toLowerCase()) != -1;
})
) return true;
return false;
}
,"regenCustomUi": function(host){
var cView = this.cView;
var items = host.getElementsByTagName("il");
var out = new Array();
for(var idx = 0; idx< items.length; idx++ ){
var inputs = cView.Utils.getInputsByName(items[idx]);
if(items[idx].cNodes["title"].getElementsByTagName("i").length) out.push({
"fn":inputs.type.value
,"icon":inputs.val.value
});
else out.push({
"fn":inputs.type.value
,"text":inputs.val.value
});
}
return out;
}
,"regenCounters": function (){
var cView = document.cView;
var directsCount = collectCounters("unreadDirectsNumber");
var notifCount = collectCounters("unreadNotificationsNumber");
cView.doc.getElementById("show-sidebar-directs").hidden = !directsCount && !notifCount;
var style = cView.doc.getElementById("counter-control-style");
var directsStyle = "";
var notifStyle = "";
if(directsCount)
directsStyle = ".directs-control::after{color:red; content:\" +"+directsCount+"\"}";
if(notifCount)
notifStyle = ".notifications-control::after{color:red; content:\" +"+notifCount+"\"}";
style.innerHTML = directsStyle+notifStyle;
cView.Drawer.updateReqs();
function collectCounters(prop){
return Object.keys(cView.contexts).reduce(
function(acc,domain){
if(!cView.contexts[domain].gMe) return acc;
var count = parseInt(
cView.contexts[domain].gMe.users[prop]
);
return acc + (Number.isNaN(count)?0:count);
}
,0);
}
}
};
return _Common;
});
<file_sep>#!/bin/bash
env ___BUILD___="dev_`date +'%F %T'`" ./node_modules/.bin/webpack --config config.js
|
2ecdd41e74bf2e26e3a4dfdf489990545ceac955
|
[
"JavaScript",
"Markdown",
"Makefile",
"Dockerfile",
"Shell"
] | 21
|
Shell
|
SiTLar/pyt-vanilla-html
|
5a98035057a6b02a1c0fdc4d5799709bac66d6b6
|
07e48bad24c6fdcf5c8a3b8b84a80bb5b319b8a7
|
refs/heads/master
|
<file_sep>#Analysis of Culex fitness by vertebrate blood host
#June 11, 2018
#<NAME> and <NAME>
library(lme4)
#use setwd() to set your working directory
Exp1_data <- read.csv("~/Desktop/Mervin-Culex_Fitness_by_Blood/data/Exp1_Host_Blood_Fitness_Study_Replicates.csv", header = T)
#adding column for number eggs per fed female
Exp1_data$No_eggs_per_Fem <- Exp1_data$Total_Egg_Produced/Exp1_data$No_Fed
Fed_only <- subset(Exp1_data, No_Fed > 0)
Fed_only$Trans_No_eggs_per_Fem <- Fed_only$No_eggs_per_Fem + 0.00001 #adding a small number to response so that gamma model works.
#Explore our data with plots
plot(No_eggs_per_Fem ~ Strain, data = Fed_only)#example - fix the outlier UPDATE: fixed
plot(No_eggs_per_Fem ~ Host_Type, data = Fed_only)
plot(No_eggs_per_Fem ~ Treatment, data = Fed_only)
attach(Fed_only)
barplot(tapply(No_eggs_per_Fem, list(Strain, Treatment),mean), main = "Effect of Blood Type Per Treatment", xlab = "Blood Type" , ylab = "Average Eggs per Female", beside = T, ylim = c(0,120), col = NULL)
#Full model comparison
model_Full1_Gau <- lmer(No_eggs_per_Fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full1_Gau)
model_Full1_TransGau <- lmer(Trans_No_eggs_per_Fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full1_TransGau)
model_Full1_Gam <- glmer(Trans_No_eggs_per_Fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only, family = Gamma)
summary(model_Full1_Gam)
model_Full1_LogNorm <- glmer(Trans_No_eggs_per_Fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only, family = gaussian(link = "log"))
summary(model_Full1_LogNorm)
model_Full2_LogNorm <- lmer(log(Trans_No_eggs_per_Fem) ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full2_LogNorm)
model_Full3_LogNorm <- glm(log(Trans_No_eggs_per_Fem) ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full3_LogNorm)
AIC(model_Full1_Gam, model_Full1_TransGau, model_Full1_LogNorm, model_Full2_LogNorm, model_Full3_LogNorm)
BIC(model_Full1_Gam, model_Full1_TransGau, model_Full1_LogNorm, model_Full2_LogNorm, model_Full3_LogNorm)
BIC(model_Full1_Gam, model_Full1_TransGau)
model_Full1 <- lmer(No_eggs_per_Fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full1)
model_Full2 <- lmer(No_eggs_per_Fem ~ 1 + Form*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full2)
model_Full3 <- lmer(No_eggs_per_Fem ~ 1 + Form*Host_Type + (1|Replicate), data = Fed_only)
summary(model_Full3)
model_Full4 <- lmer(No_eggs_per_Fem ~ 1 + Strain*Host_Type + (1|Replicate), data = Fed_only)
summary(model_Full4)
AIC(model_Full1, model_Full2, model_Full3, model_Full4, model_Full2_LogNorm) #model_Full2_LogNorm is best fit
BIC(model_Full1, model_Full2, model_Full3, model_Full4, model_Full2_LogNorm) #again with model_Full2_LogNorm
qqnorm(resid(model_Full2_LogNorm))
#Model Reductions
model_reduced1 <- lmer(log(Trans_No_eggs_per_fem) ~ 1 + Strain+Treatment + (1|Replicate), data = Fed_only)
summary(model_reduced1)
anova(model_Full2_LogNorm, model_reduced1, test = "Chisq") #interaction is important
model_reduced2 <- lmer(log(Trans_No_eggs_per_fem) ~ 1 + Strain + (1|Replicate), data = Fed_only)
summary(model_reduced2)
anova(model_Full2_LogNorm, model_reduced2, test = "Chisq") #including treatment is important
model_reduced3 <- lmer(log(Trans_No_eggs_per_fem) ~ 1 +Treatment + (1|Replicate), data = Fed_only)
summary(model_reduced3)
anova(model_Full2_LogNorm, model_reduced3, test = "Chisq") #strain is important
#So full model is still model_Full2_LogNorm; albeit a saturated model.
anova(model_Full2_LogNorm)
summary(model_Full2_LogNorm)
qqnorm(resid(model_Full2_LogNorm))
qqline(resid(model_Full2_LogNorm))
plot(model_Full2_LogNorm)
# host type instead of treatment ------------------------------------------
model_reduced_4 <- lmer(No_eggs_per_Fem ~ 1 + Strain + Host_Type + (1|Replicate), data = Fed_only)
summary(model_reduced_4)
anova(model_Full4, model_reduced_4, test = "F")
#07162018: put on 1st figure, significant strain by host type interaction and the P-value. <file_sep>#Blood Meal Weight Experiment
#June 21, 2018
#<NAME> and <NAME>
#packages required: ggplot2, plyr, lme4
library(ggplot2); library(plyr); library(lme4); library(MASS); library(lmtest)
#required functions
# Summary Function --------------------------------------------------------
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE),
N = length(x[[col]]))}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
# Multiplot function ------------------------------------------------------
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
# Set Up and Working Directories and Libraries-----------------------------------------
setwd("~/Desktop/Mervin-Culex_Fitness_By_Blood")#Mervin uses this
#setwd("~/Desktop/Culex_Fitness_By_Blood")#Megan uses this
Exp_3_Data <- read.csv(file="./data/Exp3_CSV_Blood_Meal_Weight_Data.csv", header = T)
head(Exp_3_Data)
tail(Exp_3_Data)
#Noticed an outlier for blood imbibed on Evanston (5 mg!), removed it. Suspected human error.
Exp_3_Data_Outlier_Removed <- subset(Exp_3_Data, Blood_Imbibed < 4)
CAL_1 <- subset(Exp_3_Data_Outlier_Removed, Strain == "CAL1")
CAL_1_Goose <- subset(CAL_1, Blood_Type == "Goose")
CAL_1_Bovine <- subset(CAL_1, Blood_Type == "Bovine")
Evanston <- subset(Exp_3_Data_Outlier_Removed,Strain == "Evanston")
Evanston_Bovine <- subset(Evanston, Blood_Type == "Bovine")
Evanston_Goose <- subset(Evanston, Blood_Type == "Goose")
#subsetting the dataset to include only those females that produced eggs
With_eggs <- subset(Exp_3_Data_Outlier_Removed, Eggs_Produced > 0)
CAL1_With_eggs <- subset(With_eggs, Strain == "CAL1")
CAL1_With_eggs_bovine <- subset(CAL1_With_eggs, Blood_Type == "Bovine")
CAL1_With_eggs_goose <- subset(CAL1_With_eggs, Blood_Type == "Goose")
Evanston_With_eggs <- subset(With_eggs, Strain == "Evanston")
Evanston_With_eggs_bovine <- subset(Evanston_With_eggs, Blood_Type == "Bovine")
Evanston_With_eggs_goose <- subset(Evanston_With_eggs, Blood_Type == "Goose")
# Data Summary ------------------------------------------------------------
Exp_3_Data_2 <- data_summary(Exp_3_Data_Outlier_Removed, varname = "Blood_Imbibed", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_2$se <- Exp_3_Data_2$sd / sqrt(Exp_3_Data_2$N)
head(Exp_3_Data_2)
Exp_3_Data_3 <- data_summary(Exp_3_Data_Outlier_Removed, varname = "Eggs_Produced", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_3$se <- Exp_3_Data_3$sd / sqrt(Exp_3_Data_3$N)
head(Exp_3_Data_3)
Exp_3_Data_4 <- data_summary(With_eggs, varname = "Eggs_Produced", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_4$se <- Exp_3_Data_4$sd / sqrt(Exp_3_Data_4$N)
head(Exp_3_Data_4)
#Data Exploration --------------------------------------------
###blood imbibed exploration
# Histograms of Populations In Terms of Blood Imbibed As A Whole ----------
hist(Exp_3_Data_Outlier_Removed$Blood_Imbibed, main = "Blood Imbibed Across Populations", xlab = "Amount Imbibed (mg)", breaks = 12, xlim = c(0, 5))
hist(CAL_1_Bovine$Blood_Imbibed, main = "CAl 1 Imbibed Bovine Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))#adding more break, keep consistent, xaxt
hist(CAL_1_Goose$Blood_Imbibed, main = "CAL 1 Imbibed Goose Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
hist(Evanston_Bovine$Blood_Imbibed, main = "Evanston Imbibed Bovine Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
hist(Evanston_Goose$Blood_Imbibed, main = "Evanston Imbibed Goose Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
#Initial Weight vs. Amount of Blood Imbibed Scatterplots
initial_vs_imbibed_CAL1_main <-ggplot(CAL_1, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for CAL1 Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_main)
initial_vs_imbibed_Evanston_main <-ggplot(Evanston, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_Evanston_main)
###Exploration of factors influencing num Eggs Produced
#Eggs produced by blood imbibed
imbibed_vs_eggs_scatter <- ggplot(With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs(title = "Egg Production versus Blood Imbibed Overall", x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()
print(imbibed_vs_eggs_scatter)
#CAL1 - broken out by blood type
imbibed_vs_eggs_scatter_CAL1_bovine <-ggplot(CAL_1_Bovine, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for CAL1 Bovine", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_CAL1_bovine)
imbibed_vs_eggs_scatter_CAL1_goose <-ggplot(CAL_1_Goose, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for CAL1 Goose", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_CAL1_goose)
#Evanston - broken out by blood type
imbibed_vs_eggs_scatter_Evanston_bovine <-ggplot(Evanston_Bovine, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for Evanston Bovine", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_Evanston_bovine)
imbibed_vs_eggs_scatter_Evanston_goose <-ggplot(Evanston_Goose, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for Evanston Goose", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_Evanston_goose)
#Eggs produced by initial weight
initial_vs_eggs_scatter <- ggplot(With_eggs, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter)
#Broken down by strain.
initial_vs_eggs_scatter_CAL1_main <-ggplot(CAL_1, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for CAL1 Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_CAL1_main)
initial_vs_eggs_scatter_Evanston_main <-ggplot(Evanston, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for Evanston Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_Evanston_main)
# Full Model Exploration -------------------------------------------------------------
model_Full1_Gau <- glm(Blood_Imbibed ~ 1 + Strain*Blood_Type*Initial_Weight, data = Exp_3_Data_Outlier_Removed)
summary(model_Full1_Gau)
qqnorm(resid(model_Full1_Gau))
qqline(resid(model_Full1_Gau))
model_Full1_Gam <- glm(Blood_Imbibed ~ 1 + Strain*Blood_Type*Initial_Weight, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_Full1_Gam)
qqnorm(resid(model_Full1_Gam))
qqline(resid(model_Full1_Gam))
AIC(model_Full1_Gam, model_Full1_Gau)
BIC(model_Full1_Gam, model_Full1_Gau)
#gamma distribution looks the best.
#Model Reduction using gamma dist for Statistical Analysis --------------------------------------------------------
model_red1_Gam <- glm(Blood_Imbibed ~ 1 + Strain*Blood_Type+Initial_Weight, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_red1_Gam)
lrtest(model_red1_Gam, model_Full1_Gam) #no diff between models when initial weight is removed from interaction, so not important
model_red2_Gam <- glm(Blood_Imbibed ~ 1 + Strain*Blood_Type, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_red2_Gam)
lrtest(model_red2_Gam, model_red1_Gam) #no diff between models with initial weight removed altogether, so not important
model_red3_Gam <- glm(Blood_Imbibed ~ 1 + Strain + Blood_Type, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_red3_Gam)
lrtest(model_red3_Gam, model_red2_Gam)
model_red4_Gam <- glm(Blood_Imbibed ~ 1 + Blood_Type, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_red4_Gam)
lrtest(model_red4_Gam, model_red3_Gam) #strain is marginally significant
model_red5_Gam <- glm(Blood_Imbibed ~ 1 + Strain, data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_red5_Gam)
lrtest(model_red3_Gam,model_red5_Gam) #blood type is marginally significant
#Figure 3 for Pub - Amt blood by population and blood type
png(filename = "Figure_3_AmtBlood_AvgEggs.png", units = "px", height = 800, width = 500)
p1 <- ggplot(Exp_3_Data_2, aes(x=Strain, y=Blood_Imbibed, fill=Blood_Type)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=Blood_Imbibed-se, ymax=Blood_Imbibed+se), width=.2,
position=position_dodge(.9)) + labs(title="A", x="Strain", y = "Average Blood Imbibed (mg) + SE", fill = "Blood Type")+
theme_classic() +
theme(axis.text=element_text(size=12),
axis.title=element_text(size=14), plot.title = element_text(face="bold", size = 16)) +
scale_fill_manual(values=c('#999999','#f2f3f4'))
p2 <- ggplot(Exp_3_Data_3, aes(x=Strain, y=Eggs_Produced, fill=Blood_Type)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=Eggs_Produced-se, ymax=Eggs_Produced+se), width=.2,
position=position_dodge(.9)) + labs(title="B", x="Strain", y = "Average Egg Production + SE", fill = "Blood Type")+
theme_classic() +
theme(axis.text=element_text(size=12),
axis.title=element_text(size=14), plot.title = element_text(face="bold", size = 16)) +
scale_fill_manual(values=c('#999999','#f2f3f4'))
multiplot(p1,p2, cols = 1)
dev.off()
#####Initial model selection for egg production analysis
model_Full2_Gau <- glm(Eggs_Produced ~ 1 + Strain*Blood_Type*Blood_Imbibed, data = With_eggs)
summary(model_Full2_Gau)
qqnorm(resid(model_Full2_Gau))
qqline(resid(model_Full2_Gau))
model_Full2_Gam <- glm(Eggs_Produced ~ 1 + Strain*Blood_Type*Blood_Imbibed, data = With_eggs, family = Gamma(link = log))
summary(model_Full2_Gam)
qqnorm(resid(model_Full2_Gam))
qqline(resid(model_Full2_Gam))
model_Full2_Pois <- glm(Eggs_Produced ~ 1 + Strain*Blood_Type*Blood_Imbibed, data = With_eggs, family = poisson)
summary(model_Full2_Pois)
qqnorm(resid(model_Full2_Pois))
qqline(resid(model_Full2_Pois))
model_Full2_nbi <- glm.nb(Eggs_Produced ~ 1 + Strain*Blood_Type*Blood_Imbibed, data = With_eggs)
summary(model_Full2_nbi)
qqnorm(resid(model_Full2_nbi))
qqline(resid(model_Full2_nbi))
AIC(model_Full2_Gam, model_Full2_Gau, model_Full2_Pois, model_Full2_nbi)
BIC(model_Full2_Gam, model_Full2_Gau, model_Full2_Pois, model_Full2_nbi)
#model_Full2_nbi looks best of these according to ICs, no overdispersion. Going to use that one.
##Model Reduction
nbi_red2 <- glm.nb(Eggs_Produced ~ 1 + Strain+Blood_Type*Blood_Imbibed, data = With_eggs)
summary(nbi_red2)
anova(model_Full2_nbi, nbi_red2, test = "Chisq")#strain does not significantly influence as interaction.
nbi_red3 <- glm.nb(Eggs_Produced ~ 1 + Blood_Type*Blood_Imbibed, data = With_eggs)
summary(nbi_red3)
anova(nbi_red2, nbi_red3, test = "Chisq")#strain significantly influences num eggs
nbi_red4 <- glm.nb(Eggs_Produced~ 1 + Strain+Blood_Type+Blood_Imbibed, data = With_eggs)
summary(nbi_red4)
anova(nbi_red2, nbi_red4, test = "Chisq")#Not a significant interaction
exp(coef(nbi_red4))#getting backtransformed model coefficients.
nbi_red5 <- glm.nb(Eggs_Produced~ 1 + Strain+Blood_Imbibed, data = With_eggs)
summary(nbi_red5)
anova(nbi_red4, nbi_red5, test= "Chisq") #blood type matters
nbi_red6 <- glm.nb(Eggs_Produced~ 1 + Strain+Blood_Type, data = With_eggs)
summary(nbi_red6)
anova(nbi_red4, nbi_red6, test = "Chisq") #Amt blood imbibed matters too.
#Figure 4 - Eggs_produced_by blood meal mass
imbibed_vs_eggs_scatter_CAL1_main <- ggplot(CAL1_With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs(title = "A", x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()+ scale_fill_manual(values=c('#cbe432','#2e2fe3')+
theme(axis.text=element_text(size=12),
axis.title=element_text(size=14), plot.title = element_text(face="bold", size = 16)))
imbibed_vs_eggs_scatter_Evanston_main <- ggplot(Evanston_With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs(title = "B", x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()+scale_fill_manual(values=c('#fcba12','#343009') +
theme(axis.text=element_text(size=12),
axis.title=element_text(size=14), plot.title = element_text(face="bold", size = 16)))
png(filename = 'Figure_4_EggsProduced_by_BloodmealMass.png', units="in", width=8, height=5, res=300)
multiplot(imbibed_vs_eggs_scatter_CAL1_main, imbibed_vs_eggs_scatter_Evanston_main)
dev.off()
#Supplementary Figure - eggs produced by initial weight
png(filename = "Supp_Fig_EggsProduced_by_InitialWeight.png", units = "px", height = 900, width = 900)
initial_vs_eggs_scatter_CAL1_bovine <-ggplot(CAL1_With_eggs_bovine, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "CAL1 Bovine", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
initial_vs_eggs_scatter_CAL1_goose <-ggplot(CAL1_With_eggs_goose, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "CAL1 Goose", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
initial_vs_eggs_scatter_Evanston_bovine <- ggplot(Evanston_With_eggs_bovine, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Evanston Bovine", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
initial_vs_eggs_scatter_Evanston_goose <- ggplot(Evanston_With_eggs_goose, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Evanston Goose", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
multiplot(initial_vs_eggs_scatter_CAL1_bovine,initial_vs_eggs_scatter_CAL1_goose,initial_vs_eggs_scatter_Evanston_bovine,initial_vs_eggs_scatter_Evanston_goose, cols=2)
dev.off()
#Supplementary Figure - Blood imbibed by initial weight
initial_vs_imbibed_CAL1_bovine <-ggplot(CAL_1_Bovine, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for CAL1 Bovine", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_bovine)
initial_vs_imbibed_CAL1_goose <-ggplot(CAL_1_Goose, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_goose)
initial_vs_imbibed_Evanston_bovine <-ggplot(Evanston_Bovine, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Bovine", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_Evanston_bovine)
initial_vs_imbibed_Evanston_goose <-ggplot(Evanston_Goose, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Goose", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_goose)
png(filename = "Supp_Fig_BloodImbibed_by_InitialWeight.png", units="px", width=800, height=500)
multiplot(initial_vs_imbibed_CAL1_bovine, initial_vs_imbibed_CAL1_goose, initial_vs_imbibed_Evanston_bovine,initial_vs_imbibed_Evanston_goose, cols = 2)
dev.off()
# Calculating the correlations between num eggs produced and amt blood imbibed -------------------------------------------------------
#Correlation Between Eggs Produced and Blood Imbibed
cor.test(With_eggs$Eggs_Produced, With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs$Eggs_Produced, CAL1_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Eggs_Produced, CAL1_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_goose$Eggs_Produced, CAL1_With_eggs_goose$Blood_Imbibed, method = "pearson")
cor.test(Evanston$Eggs_Produced, Evanston$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Eggs_Produced, Evanston_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_goose$Eggs_Produced, Evanston_With_eggs_goose$Blood_Imbibed, method = "pearson")
#Correlation Between Initial Weight and Eggs Produced
cor.test(With_eggs$Initial_Weight, With_eggs$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs$Initial_Weight, CAL1_With_eggs$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Initial_Weight, CAL1_With_eggs_bovine$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs_goose$Initial_Weight, CAL1_With_eggs_goose$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs$Initial_Weight, Evanston_With_eggs$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Initial_Weight, Evanston_With_eggs_bovine$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs_goose$Initial_Weight, Evanston_With_eggs_goose$Eggs_Produced, method = "pearson")
#Correlation Between Initial Weight and Blood Imbibed
cor.test(With_eggs$Initial_Weight, With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs$Initial_Weight, CAL1_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Initial_Weight, CAL1_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_goose$Initial_Weight, CAL1_With_eggs_goose$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs$Initial_Weight, Evanston_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Initial_Weight, Evanston_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_goose$Initial_Weight, Evanston_With_eggs_goose$Blood_Imbibed, method = "pearson")
<file_sep>#Blood Meal Weight Experiment
#June 21, 2018
#<NAME> and <NAME>
#easier navigation by going to Edit -> Folding -> Collapse All (alt+control+o)
#packages required: ggplot2, plyr, lme4
# Notes -------------------------------------------------------------------
#07/06/2018: noticed an outlier for blood imbibed on Evanston (5 mg!), removed it. Suspected human error.
#07/20/2018: new model is now model_Full4_LogNorm which fits a log normal distribution to our data. Is the intercept what we are considering for significance? If so, interaction, strain, and blood type are all important.
#07/20/2018: started dealing data without the outlier. Note that the outlier made a significant difference. Also, evidence point that the balance was acting funny on the same replicate, where I got a negative number for blood imbibed.
#07/20/2018: looking at qqplot, model_reduced3 looks better than model_Full4_LogNorm
# Set Up and Working Directories and Libraries-----------------------------------------
Exp_3_Data <- read.csv(file="~/Desktop/Mervin-Culex_Fitness_By_Blood/data/Exp3_CSV_Blood_Meal_Weight_Data.csv", header = T)
head(Exp_3_Data)
Exp_3_Data_Outlier_Removed <- subset(Exp_3_Data, Blood_Imbibed < 4)
With_eggs <- subset(Exp_3_Data, Eggs_Produced > 0)
CAL_1 <- subset(Exp_3_Data, Strain == "CAL1")
CAL_1_Goose <- subset(CAL_1, Blood_Type == "Goose")
CAL_1_Bovine <- subset(CAL_1, Blood_Type == "Bovine")
Evanston <- subset(Exp_3_Data,Strain == "Evanston")
Evanston_outlier_removed <- subset(Evanston, Blood_Imbibed < 4)
Evanston_Bovine <- subset(Evanston, Blood_Type == "Bovine")
Evanston_Goose <- subset(Evanston, Blood_Type == "Goose")
Evanston_Goose_Removed_Outlier <-subset(Evanston_Goose, Blood_Imbibed < 4)
CAL1_With_eggs <- subset(With_eggs, Strain == "CAL1")
CAL1_With_eggs_bovine <- subset(CAL1_With_eggs, Blood_Type == "Bovine")
CAL1_With_eggs_goose <- subset(CAL1_With_eggs, Blood_Type == "Goose")
Evanston_With_eggs <- subset(With_eggs, Strain == "Evanston")
Evanston_With_eggs_bovine <- subset(Evanston_With_eggs, Blood_Type == "Bovine")
Evanston_With_eggs_goose <- subset(Evanston_With_eggs, Blood_Type == "Goose")
library(ggplot2); library(plyr); library(lme4)
# Summary Function --------------------------------------------------------
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE),
N = length(x[[col]]))}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
# Data Summary ------------------------------------------------------------
Exp_3_Data_2 <- data_summary(Exp_3_Data, varname = "Blood_Imbibed", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_2$se <- Exp_3_Data_2$sd / sqrt(Exp_3_Data_2$N)
head(Exp_3_Data_2)
Exp_3_Data_3 <- data_summary(Exp_3_Data, varname = "Eggs_Produced", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_3$se <- Exp_3_Data_3$sd / sqrt(Exp_3_Data_3$N)
head(Exp_3_Data_3)
Exp_3_Data_4 <- data_summary(With_eggs, varname = "Eggs_Produced", groupnames = c("Strain", "Blood_Type"))
Exp_3_Data_4$se <- Exp_3_Data_4$sd / sqrt(Exp_3_Data_4$N)
head(Exp_3_Data_4)
# Multiplot function ------------------------------------------------------
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
# http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
# Main Experiment Barplot -------------------------------------------------
p<- ggplot(Exp_3_Data_2, aes(x=Strain, y=Blood_Imbibed, fill=Blood_Type)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=Blood_Imbibed-se, ymax=Blood_Imbibed+se), width=.2,
position=position_dodge(.9)) + labs(title="Effect of Blood Type on Amount Imbibed", x="Strain", y = "Average Blood Imbibed (mg)", fill = "Blood Type")+
theme_classic() +
scale_fill_manual(values=c('#999999','#f2f3f4'))
print(p)
p2<- ggplot(Exp_3_Data_3, aes(x=Strain, y=Eggs_Produced, fill=Blood_Type)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=Eggs_Produced-se, ymax=Eggs_Produced+se), width=.2,
position=position_dodge(.9)) + labs(title="Effect of Blood Type on Eggs Produced", x="Strain", y = "Average Egg Production", fill = "Blood Type")+
theme_classic() +
scale_fill_manual(values=c('#999999','#f2f3f4'))
print(p2)
# Main Experiment Boxplot -------------------------------------------------
#this is used for figure 15
tiff('fig_15_box.tiff', units="in", width=8, height=5, res=300)
box <- ggplot(With_eggs, aes(x=Strain, y= Blood_Imbibed, fill = Blood_Type))+ stat_boxplot(geom = "errorbar")+
theme_classic()+ labs(x = "Strain",
y = "Average Blood Imbibed (mg)", fill = "Blood Type") + scale_fill_manual(values=c('#d61a46','#98ca32'))#set notch to F since notches went outside hinges.
box +geom_boxplot()
dev.off()
#this is used for figure 16
tiff('fig_16_box.tiff', units="in", width=8, height=5, res=300)
box_2 <-ggplot(With_eggs, aes(x=Strain, y= Eggs_Produced, fill = Blood_Type)) + stat_boxplot(geom = "errorbar")+ theme_classic()+ labs(x = "Strain", y = "Average Egg Count", fill = "Blood Type") +
scale_fill_manual(values = c('#fc600a','#1489b8'))#set notch to F since notches went outside hinges.
box_2+geom_boxplot()
dev.off()
# Experiment Boxplot with Jitter ------------------------------------------
box_n_jitter <- ggplot(Exp_3_Data, aes(x= Strain, y= Blood_Imbibed, color = Blood_Type)) + geom_boxplot() + geom_jitter(position = position_jitter(0.1))+
theme_classic()+scale_fill_manual(values=c('#999999','#f2f3f4'))+ labs(title = "Amount of Blood Imbibed per Blood Type per Strain", x = "Strain", y = "Blood Imbibed", color = "Blood Type")
print(box_n_jitter) #unsure if helpful
# Scatterplot Data Exploration --------------------------------------------
#Blood Imbibed vs. Eggs Produced Scatterplots
imbibed_vs_eggs_scatter <- ggplot(With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs(title = "Egg Production versus Blood Imbibed Overall", x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()
print(imbibed_vs_eggs_scatter)
imbibed_vs_eggs_scatter_CAL1_main <- ggplot(CAL1_With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs( x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()+ scale_color_manual(values=c('#cbe432','#2e2fe3'))
print(imbibed_vs_eggs_scatter_CAL1_main) #this is used for figure 17 or 18.
imbibed_vs_eggs_scatter_Evanston_main <- ggplot(Evanston_With_eggs, aes(x=Blood_Imbibed, y=Eggs_Produced, color = Blood_Type, shape = Blood_Type)) + geom_point() +
geom_smooth(method = lm, fullrange = TRUE, se=FALSE) +
labs( x="Blood Imbibed (mg)", y = "Eggs Produced", color = "Blood_Type")+
theme_classic()+scale_color_manual(values=c('#fcba12','#343009'))
print(imbibed_vs_eggs_scatter_Evanston_main) #this is used for figure 19 or 20.
tiff('fig_17.tiff', units="in", width=8, height=5, res=300)
multiplot(imbibed_vs_eggs_scatter_CAL1_main, imbibed_vs_eggs_scatter_Evanston_main)
dev.off() #used for figure 17
imbibed_vs_eggs_scatter_CAL1_bovine <-ggplot(CAL_1_Bovine, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for CAL1 Bovine", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_CAL1_bovine)
imbibed_vs_eggs_scatter_CAL1_goose <-ggplot(CAL_1_Goose, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for CAL1 Goose", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_CAL1_goose)
imbibed_vs_eggs_scatter_Evanston_main <-ggplot(Evanston, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for Evanston Overall", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_Evanston_main)
imbibed_vs_eggs_scatter_Evanston_bovine <-ggplot(Evanston_Bovine, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for Evanston Bovine", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_Evanston_bovine)
imbibed_vs_eggs_scatter_Evanston_goose <-ggplot(Evanston_Goose, aes(x=Blood_Imbibed, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Blood Imbibed for Evanston Goose", x="Blood Imbibed (mg)", y = "Eggs Produced")+
theme_classic()
print(imbibed_vs_eggs_scatter_Evanston_goose)
#Initial Weight vs. Eggs Produced Scatterplots
initial_vs_eggs_scatter <- ggplot(Exp_3_Data, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter)
initial_vs_eggs_scatter_CAL1_main <-ggplot(CAL_1, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for CAL1 Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_CAL1_main)
initial_vs_eggs_scatter_CAL1_bovine <-ggplot(CAL_1_Bovine, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for CAL1 Bovine", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_CAL1_bovine)
initial_vs_eggs_scatter_CAL1_goose <-ggplot(CAL_1_Goose, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for CAL1 Goose", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_CAL1_goose)
initial_vs_eggs_scatter_Evanston_main <-ggplot(Evanston_outlier_removed, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for Evanston Overall", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_Evanston_main)
initial_vs_eggs_scatter_Evanston_bovine <- ggplot(Evanston_Bovine, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for Evanston Bovine", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_Evanston_bovine)
initial_vs_eggs_scatter_Evanston_goose <- ggplot(Evanston_Goose_Removed_Outlier, aes(x=Initial_Weight, y=Eggs_Produced)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Egg Production versus Initial Weight for Evanston Goose", x="Initial Weight (mg)", y = "Eggs Produced")+
theme_classic()
print(initial_vs_eggs_scatter_Evanston_goose)
#Initial Weight vs. Amount of Blood Imbibed Scatterplots
initial_vs_imbibed_main <- ggplot(Exp_3_Data, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_main)
initial_vs_imbibed_CAL1_main <-ggplot(CAL_1, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for CAL1 Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_main)
initial_vs_imbibed_CAL1_bovine <-ggplot(CAL_1_Bovine, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for CAL1 Bovine", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_bovine)
initial_vs_imbibed_CAL1_goose <-ggplot(CAL_1_Goose, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_goose)
initial_vs_imbibed_Evanston_main <-ggplot(Evanston_outlier_removed, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Overall", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_Evanston_main)
initial_vs_imbibed_Evanston_bovine <-ggplot(Evanston_Bovine, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Bovine", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_Evanston_bovine)
initial_vs_imbibed_Evanston_goose <-ggplot(Evanston_Goose, aes(x=Blood_Imbibed, y=Initial_Weight)) + geom_point() +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE, level = 0.95, color = "grey") +
labs(title = "Blood Imbibed versus Initial Weight for Evanston Goose", x="Blood Imbibed (mg)", y = "Initial Weight (mg)")+
theme_classic()
print(initial_vs_imbibed_CAL1_goose)
# Histograms of Populations In Terms of Blood Imbibed As A Whole ----------
hist(Exp_3_Data$Blood_Imbibed, main = "Blood Imbibed Across Populations", xlab = "Amount Imbibed (mg)", breaks = 12, xlim = c(0, 5))
hist( CAL_1_Bovine$Blood_Imbibed, main = "CAl 1 Imbibed Bovine Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))#adding more break, keep consistent, xaxt
hist( CAL_1_Goose$Blood_Imbibed, main = "CAL 1 Imbibed Goose Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
hist( Evanston_Bovine$Blood_Imbibed, main = "Evanston Imbibed Bovine Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
hist( Evanston_Goose_Removed_Outlier$Blood_Imbibed, main = "Evanston Imbibed Goose Blood Distribution", xlab = "Amount Imbibed (mg)", breaks = seq(0,5.5, by =0.5), ylim = c(0,20))
# Full Models -------------------------------------------------------------
model_Full1_Gau <- lmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_Full1_Gau)
model_Full1_TransGau <- lmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_Full1_TransGau)
model_Full1_Gam <- glmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed, family = Gamma)
summary(model_Full1_Gam)
model_Full1_LogNorm <- glmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed, family = gaussian(link = "log"))
summary(model_Full1_LogNorm)
model_Full2_LogNorm <- lmer(log(Blood_Imbibed) ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_Full2_LogNorm)
plot(model_Full2_LogNorm)
qqnorm(resid(model_Full2_LogNorm))
qqline(resid(model_Full2_LogNorm))
model_Full3_LogNorm <- lmer(log(Blood_Imbibed) ~ 1 + Initial_Weight*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_Full3_LogNorm)
model_Full4_LogNorm <- glm(log(Blood_Imbibed) ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_Full4_LogNorm)
AIC(model_Full1_Gam, model_Full1_TransGau, model_Full1_LogNorm, model_Full2_LogNorm, model_Full3_LogNorm, model_Full4_LogNorm)
BIC(model_Full1_Gam, model_Full1_TransGau, model_Full1_LogNorm, model_Full2_LogNorm, model_Full3_LogNorm, model_Full4_LogNorm)
BIC(model_Full1_Gam, model_Full1_TransGau)
plot(model_Full4_LogNorm)
model_full1 <- lmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + Initial_Weight + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_full1)
model_full2 <- lmer(Blood_Imbibed ~ 1 + Strain*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_full2)
anova(model_full2)
qqnorm(model_full2)
model_full3 <- lmer(Blood_Imbibed ~ 1 +Strain*Initial_Weight + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_full3)
model_full4 <- lmer (Blood_Imbibed ~ 1 + Initial_Weight*Blood_Type + (1|Replicate), data = Exp_3_Data_Outlier_Removed)
summary(model_full4)
AIC(model_full1, model_full2, model_full3, model_full4, model_Full4_LogNorm) #model_full2; UPDATE: model_Full4_LogNorm is the best
BIC(model_full1, model_full2, model_full3, model_full4, model_Full4_LogNorm) #again model_full2 best fit; model_FUll4_LogNorm is the best
# Model Reductions --------------------------------------------------------
model_reduced1 <- glm(log(Blood_Imbibed) ~ 1 + Strain + Blood_Type + (1|Replicate), data = Exp_3_Data)
summary(model_reduced1)
anova(model_Full4_LogNorm, model_reduced1, test = "Chisq") #eliminate interaction term; interaction term is important
model_reduced2 <- glm(log(Blood_Imbibed) ~ 1 + Strain + (1|Replicate), data = Exp_3_Data)
summary(model_reduced2)
anova(model_Full4_LogNorm, model_reduced2, test = "Chisq") #Blood_Type is important
model_reduced3 <- glm(log(Blood_Imbibed) ~ 1 + Blood_Type + (1|Replicate), data = Exp_3_Data)
summary(model_reduced3)
anova(model_Full4_LogNorm, model_reduced3, test = "Chisq") #Strain is important
plot(model_reduced3)
#new model is still model_Full4_LogNorm
# Correlation Tests -------------------------------------------------------
#Correlation Between Eggs Produced and Blood Imbibed
cor.test(With_eggs$Eggs_Produced, With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs$Eggs_Produced, CAL1_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Eggs_Produced, CAL1_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_goose$Eggs_Produced, CAL1_With_eggs_goose$Blood_Imbibed, method = "pearson")
cor.test(Evanston$Eggs_Produced, Evanston$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Eggs_Produced, Evanston_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_goose$Eggs_Produced, Evanston_With_eggs_goose$Blood_Imbibed, method = "pearson")
#Correlation Between Initial Weight and Eggs Produced
cor.test(With_eggs$Initial_Weight, With_eggs$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs$Initial_Weight, CAL1_With_eggs$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Initial_Weight, CAL1_With_eggs_bovine$Eggs_Produced, method = "pearson")
cor.test(CAL1_With_eggs_goose$Initial_Weight, CAL1_With_eggs_goose$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs$Initial_Weight, Evanston_With_eggs$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Initial_Weight, Evanston_With_eggs_bovine$Eggs_Produced, method = "pearson")
cor.test(Evanston_With_eggs_goose$Initial_Weight, Evanston_With_eggs_goose$Eggs_Produced, method = "pearson")
#Correlation Between Initial Weight and Blood Imbibed
cor.test(With_eggs$Initial_Weight, With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs$Initial_Weight, CAL1_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_bovine$Initial_Weight, CAL1_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(CAL1_With_eggs_goose$Initial_Weight, CAL1_With_eggs_goose$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs$Initial_Weight, Evanston_With_eggs$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_bovine$Initial_Weight, Evanston_With_eggs_bovine$Blood_Imbibed, method = "pearson")
cor.test(Evanston_With_eggs_goose$Initial_Weight, Evanston_With_eggs_goose$Blood_Imbibed, method = "pearson")
# T-Tests -----------------------------------------------------------------
t.test(Blood_Imbibed~Blood_Type, data = Evanston)
t.test(Blood_Imbibed~Blood_Type, data = CAL_1)
t.test(data= Evanston, Initial_Weight~Blood_Type)
t.test(data = CAL_1, Initial_Weight~Blood_Type)
# ANOVA -------------------------------------------------------------------
#analyzing whether variances are similar, with a nonparametric assumption (Fligner-Killen Test)
fligner.test(Blood_Imbibed ~ Strain, data = Exp_3_Data)
#p-value = 0.02, variance significantly different (ANOVA may not work)
#this is used for Figure 15
anov_model_1 <- aov(Blood_Imbibed~Blood_Type*Strain, data = Exp_3_Data)
summary(anov_model_1)
plot(anov_model_1)
anov_model_1 <- aov(Blood_Imbibed~Blood_Type*Strain, data = Exp_3_Data_Outlier_Removed)
summary(anov_model_1)
#this is used for Figure 16
anov_model_2 <- aov(Eggs_Produced~Blood_Type*Strain, data = With_eggs)
summary(anov_model_2)
plot(anov_model_2)
# 07/16/2018: remove titles of all graphs
#07162018: look at the outliers; for poster, report model results with outliers included but verbally acknowledge how to handle outliers
#07162018: include DF<file_sep>---
title: "*Culex pipiens* egg production depends upon vertebrate blood host species"
author: "<NAME>, and <NAME>."
date: "7/6/2018"
output: github_document
---
####Background####
The *Culex pipiens* species is part of the Culex assemblage. Within the species itself, there exists two major bioforms: form pipiens and form molestus. *Cx. pip* form *pipiens* are aboveground mosquitoes that feed primarily in avian blood, while the *Cx. pip* form *molestus* are underground mosquitoes that feed primarily in mammalian blood. Though host preference has been previously demostrated, the reason as to why these preferences exist is unknown. The purpose of this work is to analyze the effects of different mammalian and avian host blood on the fecundity of above ground and below ground *Cx. pipiens* mosquitoes to see whether mosquitoes produce the most eggs when feeding on their preferred hosts.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
####Analytical Methods
##### Summary function
The function below takes the main data frame and outputs a new dataframe that includes the mean, standard deviation, and number of replicates.
```{r}
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE),
No_Replicates = length(x[[col]]))}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
```
##### Bootstrapping function
```{r}
boot.fn <- function(x, N=5000) {
Int.1 <- replicate(N, mean(sample(x, size= length(x), replace=T)))
Int.CI <- quantile(Int.1, probs=c(0.025,0.975))
Int.CI
}
```
#####Setting up the main dataset
```{r, results = "hide"}
#Mervin uses this
Exp_1_data <- read.csv(file = "~/Desktop/Mervin-Culex_Fitness_By_Blood/data/Exp1_Host_Blood_Fitness_Study_Replicates.csv",header = T)
#Megan uses this
#Exp_1_data <- read.csv(file = "~/Desktop/Culex_Fitness_By_Blood/data/Exp1_Host_Blood_Fitness_Study_Replicates.csv",header = T)
head(Exp_1_data)
Exp_1_data$No_eggs_per_fem <- Exp_1_data$Total_Egg_Produced/Exp_1_data$No_Fed
Fed_only <- subset(Exp_1_data, No_Fed > 0)
str(Fed_only)
Fed_only_mammalian <- subset(Fed_only, Host_Type =="mammalian")
Fed_only_avian <- subset(Fed_only, Host_Type == "avian")
Fed_only_molestus <- subset(Fed_only, Form =="m")
Fed_only_pip <- subset(Fed_only, Form =="p")
Fed_only_mol_bovine <- subset(Fed_only_molestus, Treatment =="Bovine")
Fed_only_mol_rabbit <- subset(Fed_only_molestus, Treatment =="Rabbit")
Fed_only_mol_equine <- subset(Fed_only_molestus, Treatment =="Equine")
Fed_only_mol_goose <- subset(Fed_only_molestus, Treatment =="Goose")
Fed_only_mol_chicken <- subset(Fed_only_molestus, Treatment =="Chix")
Fed_only_mol_turkey <- subset(Fed_only_molestus, Treatment =="Turkey")
Fed_only_pip_bovine <- subset(Fed_only_pip, Treatment =="Bovine")
Fed_only_pip_rabbit <- subset(Fed_only_pip, Treatment =="Rabbit")
Fed_only_pip_equine <- subset(Fed_only_pip, Treatment =="Equine")
Fed_only_pip_goose <- subset(Fed_only_pip, Treatment =="Goose")
Fed_only_pip_chicken <- subset(Fed_only_pip, Treatment =="Chix")
Fed_only_pip_turkey <- subset(Fed_only_pip, Treatment =="Turkey")
```
#####Setting up the libraries needed
```{r echo=T, error = FALSE, results='hide'}
library (lme4)
library(ggplot2)
library(car)
library(plyr)
```
#####Table summary of the data
Table summary with the standard error calculated.
```{r, results= "hide", error=FALSE}
Exp_1_Data_Summary <- data_summary(Fed_only, varname = "No_eggs_per_fem", groupnames = c("Strain", "Treatment"))
Exp_1_Data_Summary$se <- Exp_1_Data_Summary$sd / sqrt(Exp_1_Data_Summary$No_Replicates)
```
```{r}
head(Exp_1_Data_Summary)
```
```{r, results = "hide"}
Exp_1_Data_Host_Type <-data_summary(Fed_only, varname = "No_eggs_per_fem", groupnames = c("Strain", "Host_Type"))
Exp_1_Data_Host_Type$se <- Exp_1_Data_Host_Type$sd / sqrt(Exp_1_Data_Host_Type$No_Replicates)
```
```{r}
head(Exp_1_Data_Host_Type)
```
####Graphs of the Data
#####Average egg production when looking at host type alone
Looking at host type alone, all strains seem to do well when fed avian blood. Error bars represent standard error (alpha = 0.05)
```{r, echo = FALSE}
Host_Type_bar <-ggplot(Exp_1_Data_Host_Type, aes(x=Strain, y=No_eggs_per_fem, fill=Host_Type)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=No_eggs_per_fem-se, ymax=No_eggs_per_fem+se), width=.2,
position=position_dodge(.9)) + labs(x="Strain", y = "Average Eggs", fill = "Host Type")+
theme_classic()+ scale_color_brewer(palette = "Spectral")+theme(text=element_text(family="Calibri"))
print(Host_Type_bar)
```
#####Average egg production per treatment
The graph below summarizes the average egg production for all treatments. Error bars represent standard error(alpha = 0.05)
```{r, echo = FALSE}
whole_data_bar <-ggplot(Exp_1_Data_Summary, aes(x=Strain, y=No_eggs_per_fem, fill=Treatment)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=No_eggs_per_fem-se, ymax=No_eggs_per_fem+se), width=.2,
position=position_dodge(.9)) + labs(x="Strain", y = "Average Eggs", fill = "Treatment")+
theme_classic()+ scale_color_brewer(palette = "Spectral")+theme(text=element_text(family="Calibri"))
print(whole_data_bar)
```
####Linear Model With Mixed Effects for the Data
The linear mixed effects model attempts to explain egg production with respect to strain and treatment, including their interaction and the random effect caused by performing the experiment in replicates over a wide span of time. From our exploratory data, we found that this model in particular was the best considering the AIC and BIC comparisons as well as qqplots. Please see "Exp_1_Exploratory_Data.R" for the additional models tested against this model.
```{r, error = FALSE, results = "hide"}
model_Full1 <- lmer(No_eggs_per_fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
summary(model_Full1)
```
####Statistical Analysis
#####ANOVA
A two-way ANOVA indicates that host and strain are signficant factors that impact egg production. The interaction between host and strain is moderately significant.
```{r}
Host_Anova <- aov(No_eggs_per_fem ~ Host_Type*Strain, data = Fed_only)
summary(Host_Anova)
TukeyHSD(Host_Anova)
```
#####T-Test
Treatments were compared within the *molestus* form. A significant difference was found in the chicken and turkey treatments, with CAL1 having the greatest average egg production for both.
```{r}
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_bovine)
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_chicken)
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_equine)
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_goose)
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_rabbit)
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_turkey)
```
Within the *pipiens* form, a significant difference was found in the bovine, chicken, and equine treatments, with Evanston having the greatest average egg production for those treatments.
```{r}
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_bovine)
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_chicken)
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_equine)
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_goose)
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_rabbit)
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_turkey)
```
####Conclusion
Across strains, both forms seem to produce the most eggs when feed avian blood.<file_sep>*Culex pipiens* egg production depends upon vertebrate blood host species
================
<NAME>, and <NAME>.
7/6/2018
#### Background
The *Culex pipiens* species is part of the Culex assemblage. Within the species itself, there exists two major bioforms: form pipiens and form molestus. *Cx. pip* form pipiens are aboveground mosquitoes that feed primarily in avian blood, while the *Cx. pip* form molestus are underground mosquitoes that feed primarily in mammalian blood. Though host preference has been previously demostrated, the reason as to why these preferences exist is unknown. The purpose of this work is to analyze the effects of different mammalian and avian host blood on the fecundity of above ground and below ground *Cx. pipiens* mosquitoes to see whether mosquitoes produce the most eggs when feeding on their preferred hosts.
#### Analytical Methods
##### Summary function
The function below takes the main data frame and outputs a new dataframe that includes the mean, standard deviation, and number of replicates.
``` r
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE),
No_Replicates = length(x[[col]]))}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
```
##### Bootstrapping function
``` r
boot.fn <- function(x, N=5000) {
Int.1 <- replicate(N, mean(sample(x, size= length(x), replace=T)))
Int.CI <- quantile(Int.1, probs=c(0.025,0.975))
Int.CI
}
```
##### Setting up the main dataset
``` r
#Mervin uses this
#Exp_1_data <- read.csv(file = "~/Desktop/Mervin-Culex_Fitness_By_Blood/data/Exp1_Host_Blood_Fitness_Study_Replicates.csv",header = T)
#Megan uses this
Exp_1_data <- read.csv(file = "~/Desktop/Culex_Fitness_By_Blood/data/Exp1_Host_Blood_Fitness_Study_Replicates.csv",header = T)
head(Exp_1_data)
Exp_1_data$No_eggs_per_fem <- Exp_1_data$Total_Egg_Produced/Exp_1_data$No_Fed
Fed_only <- subset(Exp_1_data, No_Fed > 0)
str(Fed_only)
Fed_only_mammalian <- subset(Fed_only, Host_Type =="mammalian")
Fed_only_avian <- subset(Fed_only, Host_Type == "avian")
Fed_only_molestus <- subset(Fed_only, Form =="m")
Fed_only_pip <- subset(Fed_only, Form =="p")
Fed_only_mol_bovine <- subset(Fed_only_molestus, Treatment =="Bovine")
Fed_only_mol_rabbit <- subset(Fed_only_molestus, Treatment =="Rabbit")
Fed_only_mol_equine <- subset(Fed_only_molestus, Treatment =="Equine")
Fed_only_mol_goose <- subset(Fed_only_molestus, Treatment =="Goose")
Fed_only_mol_chicken <- subset(Fed_only_molestus, Treatment =="Chix")
Fed_only_mol_turkey <- subset(Fed_only_molestus, Treatment =="Turkey")
Fed_only_pip_bovine <- subset(Fed_only_pip, Treatment =="Bovine")
Fed_only_pip_rabbit <- subset(Fed_only_pip, Treatment =="Rabbit")
Fed_only_pip_equine <- subset(Fed_only_pip, Treatment =="Equine")
Fed_only_pip_goose <- subset(Fed_only_pip, Treatment =="Goose")
Fed_only_pip_chicken <- subset(Fed_only_pip, Treatment =="Chix")
Fed_only_pip_turkey <- subset(Fed_only_pip, Treatment =="Turkey")
```
##### Setting up the libraries needed
``` r
library (lme4)
```
## Loading required package: Matrix
``` r
library(ggplot2)
library(car)
library(plyr)
```
##### Table summary of the data
Table summary with the standard error calculated.
``` r
Exp_1_Data_Summary <- data_summary(Fed_only, varname = "No_eggs_per_fem", groupnames = c("Strain", "Treatment"))
Exp_1_Data_Summary$se <- Exp_1_Data_Summary$sd / sqrt(Exp_1_Data_Summary$No_Replicates)
```
``` r
head(Exp_1_Data_Summary)
```
## Strain Treatment No_eggs_per_fem sd No_Replicates se
## 1 CAL1 Bovine 37.02778 4.375066 3 2.525946
## 2 CAL1 Chix 88.69307 19.437639 5 8.692777
## 3 CAL1 Equine 22.61964 19.412873 4 9.706437
## 4 CAL1 Goose 45.80556 40.667720 3 23.479519
## 5 CAL1 Rabbit 45.68750 25.554623 4 12.777312
## 6 CAL1 Turkey 91.13043 4.896422 3 2.826951
``` r
Exp_1_Data_Host_Type <-data_summary(Fed_only, varname = "No_eggs_per_fem", groupnames = c("Strain", "Host_Type"))
Exp_1_Data_Host_Type$se <- Exp_1_Data_Host_Type$sd / sqrt(Exp_1_Data_Host_Type$No_Replicates)
```
``` r
head(Exp_1_Data_Host_Type)
```
## Strain Host_Type No_eggs_per_fem sd No_Replicates se
## 1 CAL1 avian 77.66121 30.10661 11 9.077486
## 2 CAL1 mammalian 34.93745 20.51890 11 6.186682
## 3 CAL2 avian 31.91481 26.79542 9 8.931806
## 4 CAL2 mammalian 21.85000 17.75452 8 6.277170
## 5 Evanston avian 90.99377 37.07249 13 10.282058
## 6 Evanston mammalian 29.54251 24.20256 14 6.468405
#### Graphs of the Data
##### Average egg production when looking at host type alone
Looking at host type alone, all strains seem to do well when fed avian blood. Error bars represent standard errors (alpha = 0.05) 
##### Average egg production per treatment
The graph below summarizes the average egg production for all treatments. Error bars represent standard error (alpha = 0.05) 
#### Linear Model With Mixed Effects for the Data
The linear mixed effects model attempts to explain egg production with respect to strain and treatment, including their interaction and the random effect caused by performing the experiment in replicates over a wide span of time.
``` r
model_Full1 <- lmer(No_eggs_per_fem ~ 1 + Strain*Treatment + (1|Replicate), data = Fed_only)
```
## Warning: 'rBind' is deprecated.
## Since R version 3.2.0, base's rbind() should work fine with S4 objects
``` r
summary(model_Full1)
```
##
## Correlation matrix not shown by default, as p = 24 > 12.
## Use print(x, correlation=TRUE) or
## vcov(x) if you need it
#### Statistical Analysis
##### ANOVA
A two-way ANOVA indicates that host and strain are signficant factors that impact egg production. The interaction between host and strain is moderately significant.
``` r
Host_Anova <- aov(No_eggs_per_fem ~ Host_Type*Strain, data = Fed_only)
summary(Host_Anova)
```
## Df Sum Sq Mean Sq F value Pr(>F)
## Host_Type 1 39232 39232 44.340 2.68e-09 ***
## Strain 3 16070 5357 6.054 0.000879 ***
## Host_Type:Strain 3 6873 2291 2.589 0.058262 .
## Residuals 84 74324 885
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
``` r
TukeyHSD(Host_Anova)
```
## Tukey multiple comparisons of means
## 95% family-wise confidence level
##
## Fit: aov(formula = No_eggs_per_fem ~ Host_Type * Strain, data = Fed_only)
##
## $Host_Type
## diff lwr upr p adj
## mammalian-avian -41.30066 -53.63483 -28.96649 0
##
## $Strain
## diff lwr upr p adj
## CAL2-CAL1 -30.335623 -55.513735 -5.1575109 0.0116231
## Evanston-CAL1 3.595648 -18.798342 25.9896381 0.9747671
## Northfield-CAL1 -18.417152 -41.003669 4.1693654 0.1498164
## Evanston-CAL2 33.931271 9.790749 58.0717933 0.0022515
## Northfield-CAL2 11.918471 -12.400755 36.2376978 0.5752225
## Northfield-Evanston -22.012800 -43.436577 -0.5890227 0.0416862
##
## $`Host_Type:Strain`
## diff lwr upr
## mammalian:CAL1-avian:CAL1 -42.723767 -82.152730 -3.294804
## avian:CAL2-avian:CAL1 -45.746398 -87.308174 -4.184621
## mammalian:CAL2-avian:CAL1 -55.811213 -98.777929 -12.844496
## avian:Evanston-avian:CAL1 13.332555 -24.549567 51.214678
## mammalian:Evanston-avian:CAL1 -48.118707 -85.375576 -10.861839
## avian:Northfield-avian:CAL1 -18.697819 -56.579942 19.184303
## mammalian:Northfield-avian:CAL1 -60.860251 -98.742374 -22.978129
## avian:CAL2-mammalian:CAL1 -3.022631 -44.584408 38.539145
## mammalian:CAL2-mammalian:CAL1 -13.087446 -56.054162 29.879271
## avian:Evanston-mammalian:CAL1 56.056322 18.174200 93.938445
## mammalian:Evanston-mammalian:CAL1 -5.394941 -42.651809 31.861928
## avian:Northfield-mammalian:CAL1 24.025948 -13.856175 61.908070
## mammalian:Northfield-mammalian:CAL1 -18.136484 -56.018607 19.745638
## mammalian:CAL2-avian:CAL2 -10.064815 -54.996728 34.867099
## avian:Evanston-avian:CAL2 59.078953 18.981655 99.176251
## mammalian:Evanston-avian:CAL2 -2.372310 -41.879427 37.134808
## avian:Northfield-avian:CAL2 27.048579 -13.048720 67.145877
## mammalian:Northfield-avian:CAL2 -15.113853 -55.211152 24.983445
## avian:Evanston-mammalian:CAL2 69.143768 27.591984 110.695552
## mammalian:Evanston-mammalian:CAL2 7.692505 -33.290050 48.675060
## avian:Northfield-mammalian:CAL2 37.113394 -4.438391 78.665178
## mammalian:Northfield-mammalian:CAL2 -5.049038 -46.600823 36.502746
## mammalian:Evanston-avian:Evanston -61.451263 -97.067078 -25.835447
## avian:Northfield-avian:Evanston -32.030374 -68.299745 4.238996
## mammalian:Northfield-avian:Evanston -74.192806 -110.462177 -37.923436
## avian:Northfield-mammalian:Evanston 29.420888 -6.194927 65.036703
## mammalian:Northfield-mammalian:Evanston -12.741544 -48.357359 22.874271
## mammalian:Northfield-avian:Northfield -42.162432 -78.431803 -5.893061
## p adj
## mammalian:CAL1-avian:CAL1 0.0241743
## avian:CAL2-avian:CAL1 0.0206755
## mammalian:CAL2-avian:CAL1 0.0028760
## avian:Evanston-avian:CAL1 0.9563752
## mammalian:Evanston-avian:CAL1 0.0031109
## avian:Northfield-avian:CAL1 0.7866774
## mammalian:Northfield-avian:CAL1 0.0000839
## avian:CAL2-mammalian:CAL1 0.9999983
## mammalian:CAL2-mammalian:CAL1 0.9803087
## avian:Evanston-mammalian:CAL1 0.0003819
## mammalian:Evanston-mammalian:CAL1 0.9998179
## avian:Northfield-mammalian:CAL1 0.5069239
## mammalian:Northfield-mammalian:CAL1 0.8114976
## mammalian:CAL2-avian:CAL2 0.9968903
## avian:Evanston-avian:CAL2 0.0004113
## mammalian:Evanston-avian:CAL2 0.9999996
## avian:Northfield-avian:CAL2 0.4253680
## mammalian:Northfield-avian:CAL2 0.9377122
## avian:Evanston-mammalian:CAL2 0.0000412
## mammalian:Evanston-mammalian:CAL2 0.9989931
## avian:Northfield-mammalian:CAL2 0.1150065
## mammalian:Northfield-mammalian:CAL2 0.9999441
## mammalian:Evanston-avian:Evanston 0.0000190
## avian:Northfield-avian:Evanston 0.1236433
## mammalian:Northfield-avian:Evanston 0.0000003
## avian:Northfield-mammalian:Evanston 0.1825578
## mammalian:Northfield-mammalian:Evanston 0.9524450
## mammalian:Northfield-avian:Northfield 0.0115311
##### T-Test
Treatments were compared within the *molestus* form. A significant difference was found in the chicken and turkey treatments, with CAL1 having the greatest average egg production for both.
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_bovine)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 3.1909, df = 2.5114, p-value = 0.0634
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -2.771222 50.293445
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 37.02778 13.26667
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_chicken)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 2.9838, df = 5.0317, p-value = 0.03042
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 5.359572 71.137686
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 88.69307 50.44444
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_equine)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 0.35066, df = 4.6155, p-value = 0.7413
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -25.76612 33.67207
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 22.61964 18.66667
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_goose)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 0.36594, df = 3.8169, p-value = 0.7338
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -74.09839 96.10950
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 45.80556 34.80000
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_rabbit)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 0.25615, df = 1.8355, p-value = 0.8237
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -107.2012 119.5762
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 45.6875 39.5000
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_mol_turkey)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 7.415, df = 2.2884, p-value = 0.01204
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 39.06433 122.19654
## sample estimates:
## mean in group CAL1 mean in group CAL2
## 91.13043 10.50000
Within the *pipiens* form, a significant difference was found in the bovine, chicken, and equine treatments, with Evanston having the greatest average egg production for those treatments.
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_bovine)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 2.5434, df = 5.9165, p-value = 0.04442
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 0.8846409 50.2230212
## sample estimates:
## mean in group Evanston mean in group Northfield
## 41.78821 16.23438
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_chicken)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 2.5592, df = 5.3506, p-value = 0.04763
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 1.01716 134.48232
## sample estimates:
## mean in group Evanston mean in group Northfield
## 91.07784 23.32810
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_equine)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 2.3657, df = 7.5175, p-value = 0.0475
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 0.1469094 20.4725177
## sample estimates:
## mean in group Evanston mean in group Northfield
## 11.80971 1.50000
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_goose)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 0.89086, df = 4.5322, p-value = 0.4178
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -43.40329 87.30222
## sample estimates:
## mean in group Evanston mean in group Northfield
## 100.40965 78.46018
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_rabbit)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = 1.0656, df = 2.4689, p-value = 0.3796
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -43.16524 79.36057
## sample estimates:
## mean in group Evanston mean in group Northfield
## 54.59142 36.49375
``` r
t.test(No_eggs_per_fem~Strain, data = Fed_only_pip_turkey)
```
##
## Welch Two Sample t-test
##
## data: No_eggs_per_fem by Strain
## t = -0.090563, df = 4.726, p-value = 0.9316
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -75.85031 70.77447
## sample estimates:
## mean in group Evanston mean in group Northfield
## 81.47279 84.01071
#### Conclusion
Across strains, both forms seem to produce the most eggs when feed avian blood.
|
761b1dcc8ac529f658a50e906a8f562a61013df2
|
[
"Markdown",
"R",
"RMarkdown"
] | 5
|
R
|
mcadamme/Culex_Fitness_By_Blood
|
88c4edb2bc5892db37c97bff86676ac69b5717ac
|
5a360be9b8cb8252151861d4a7e591ca5e82667f
|
refs/heads/master
|
<repo_name>oyvind-kjerland/Fellespro25<file_sep>/ktn2/TODO.txt
-Chat backlog fungerer ikke
- norske tegn
- logout
- Sjekk at brukernavn har godkjente tegn<file_sep>/README.md
Fellespro25
===========
Fellesprosjekt for gruppe 25
<file_sep>/ktn2/server.py
# -*- coding: utf-8 -*-
import SocketServer
import socket
import json
import re
from datetime import datetime
class CLientHandler(SocketServer.BaseRequestHandler):
def isUserLoggedIn(self,nickname):
return nickname in server.users
def send(self, data):
self.request.send(data)
def isUsernameValid(self,username):
return re.match('^[\w-]+$', username) and len(username) < self.maxUsernameLength
def logoutUser(self):
if self.username not in server.users:
print "User tried to log out, but not logget in"
data = {'response': 'logout', 'error' : 'You are not logged in!'}
data = json.dumps(data)
self.send(data)
return
data = {'response': 'logout', 'username': self.username}
data = json.dumps(data)
self.send(data)
self.removeUser()
def removeUser(self):
if self.username not in server.users:
print "User tried to log out, but not logget inn"
return
del server.users[self.username]
message = self.getDateAndTime() + ' User ' + self.username + ' logged out '
self.printAndAddMessageToBacklog(message)
data = {'response': 'message', 'message' : message}
data = json.dumps(data)
self.sendDataToAllUsers(data)
def printAndAddMessageToBacklog(self,message):
print message
server.backlog.append(message)
def checkMessage(self,message):
if "} {" in message:
print("User type } {. Message Changed.")
index = message.find("} {") + 1
return message[:index] + ' ' + message[index:]
return message
def logInUser(self,username):
server.users[username] = self.request
self.username = username;
data = {'response': 'login', 'username': username , 'messages' : server.backlog}
data = json.dumps(data)
self.send(data)
print(self.getDateAndTime() + ' '+self.ip + ':' + str(self.port) +
' Logged in as: ' + username + '. ' + str(len(server.users)) + ' users online')
message = self.getDateAndTime() + ' ' + username + ' logged in. ' + str(len(server.users)) + ' users online'
data = {'response': 'message', 'message' : message}
data = json.dumps(data)
self.sendDataToAllUsers(data)
def sendDataToAllUsers(self,data):
for username in server.users:
server.users[username].sendall(data)
def getDateAndTime(self):
return datetime.now().strftime("%Y-%m-%d %H:%M")
def broadcastMessage(self,message):
message = self.getDateAndTime() + ' ' + self.username + ': ' + message
self.printAndAddMessageToBacklog(message)
data = {'response': 'message', 'message' : message}
data = json.dumps(data)
self.sendDataToAllUsers(data)
def handle(self):
# Hent IP-adressen til klienten
self.ip = self.client_address[0]
self.username = None
self.port = self.client_address[1]
self.maxUsernameLength = 20
print 'Client connected @' + self.ip + ':' + str(self.port)
while True:
try:
data = self.request.recv(1024)
if not data: break
data = json.loads(data)
if(not data.get('request')): continue
if(data['request'] == 'login'):
newUsername = data['username']
#Is username valid
if self.isUsernameValid(newUsername):
#User can log in
if not self.isUserLoggedIn(newUsername):
self.logInUser(newUsername)
#Username is taken
else:
data = {'response': 'login','error':'Name allready taken!', 'username': newUsername}
data = json.dumps(data)
self.send(data)
print(self.ip + ':' + str(self.port) + " Tried to log in as " + newUsername + ". Username taken")
#Username is not valid
else:
data = {'response': 'login','error':'Username not valid!', 'username': newUsername}
data = json.dumps(data)
self.send(data)
print(self.ip + ':' + str(self.port) + " Tried to log in as " + newUsername + ". Username not valid")
#log out user
elif(data['request'] == 'logout'):
if self.isUserLoggedIn(self.username):
self.logoutUser()
#Recive message and send it to all connected users
elif(data['request'] == 'message'):
if self.isUserLoggedIn(self.username):
message = self.checkMessage(data['message'])
self.broadcastMessage(message)
else:
print(self.ip + ':' + str(self.port) + " Not logged in. Tried to send: " + data['message'] )
data = {'response': 'message', 'error' : 'You are not logged in!'}
data = json.dumps(data)
self.send(data)
except socket.error:
print "User disconnected"
self.removeUser()
break
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
def init(self):
self.backlog = []
self.users = {}
# Kjøres når programmet starter
if __name__ == "__main__":
# Definer host og port for serveren
#HOST = '192.168.3.11'
#HOST = 'localhost'
HOST = '172.16.17.32'
PORT = 9999
# Sett opp serveren
server = ThreadedTCPServer((HOST, PORT), CLientHandler)
server.init()
# Aktiver serveren. Den vil kjøre til den avsluttes med Ctrl+C
server.serve_forever()
<file_sep>/db2/db_raw.sql
create database cal;
use cal;
create table user (
username varchar(15) not null,
password varchar(45) not null,
first_name varchar(45) not null,
last_name varchar(45) not null,
mail varchar(45) not null,
phone char(12) not null,
primary key (username)
);
create table group_table (
groupname varchar(15) not null,
parent_groupname varchar(15),
primary key (groupname),
constraint subgroup foreign key (parent_groupname) references group_table(groupname)
on update cascade
);
create table meetingroom (
roomnumber varchar(45) not null,
capacity int not null,
primary key (roomnumber)
);
create table appointment (
id int not null auto_increment,
starttime datetime not null,
endtime datetime not null,
description varchar(255),
location varchar(45),
responsible_username varchar(15) not null,
roomnumber varchar(45),
primary key (id),
constraint reservation foreign key (roomnumber) references meetingroom(roomnumber)
on delete cascade
on update cascade,
constraint responsible foreign key (responsible_username) references user(username)
on delete cascade
on update cascade
);
create table notification (
id int,
type varchar(15),
description varchar(255),
appointmentId int not null,
primary key (id),
constraint belonging_to foreign key (appointmentId) references appointment(id)
on delete cascade
on update cascade
);
create table user_notification (
notificationId int not null,
username varchar(15) not null,
primary key (notificationId, username),
constraint user_notification_n foreign key (notificationId) references notification(id)
on delete cascade
on update cascade,
constraint user_notification_u foreign key (username) references user(username)
on delete cascade
on update cascade
);
create table participant (
username varchar(45) not null,
id int not null,
status varchar(45),
hsidden boolean,
alarm int,
primary key(username, id),
constraint user_participant foreign key (username) references user(username)
on delete cascade
on update cascade,
constraint appointment_participant foreign key (id) references appointment(id)
on delete cascade
on update cascade
);
create table member (
groupname varchar(15) not null,
username varchar(15) not null,
primary key (groupname, username),
constraint member_username foreign key (username) references user(username)
on delete cascade
on update cascade,
constraint member_of_group foreign key (groupname) references group_table(groupname)
on delete cascade
on update cascade
);
<file_sep>/db2/localhost.sql
-- phpMyAdmin SQL Dump
-- version 3.4.11.1deb2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 20, 2014 at 02:30 PM
-- Server version: 5.5.35
-- PHP Version: 5.4.4-14+deb7u7
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `cal`
--
CREATE DATABASE `cal` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `cal`;
-- --------------------------------------------------------
--
-- Table structure for table `appointment`
--
CREATE TABLE IF NOT EXISTS `appointment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`starttime` datetime NOT NULL,
`endtime` datetime NOT NULL,
`description` varchar(255) DEFAULT NULL,
`location` varchar(45) DEFAULT NULL,
`responsible_username` varchar(15) NOT NULL,
`roomnumber` varchar(45) DEFAULT NULL,
`title` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `reservation` (`roomnumber`),
KEY `responsible` (`responsible_username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=227 ;
--
-- Dumping data for table `appointment`
--
INSERT INTO `appointment` (`id`, `starttime`, `endtime`, `description`, `location`, `responsible_username`, `roomnumber`, `title`) VALUES
(1, '2014-06-13 12:00:00', '2014-03-21 09:00:00', 'test', 'her', 'petterek', '1a', 'avtale'),
(2, '2014-04-13 12:00:00', '2014-04-13 12:20:00', 'ACCEPTED', 'ACCEPTED', 'sims', '3c', 'avtale'),
(3, '2014-04-13 12:00:00', '2014-04-13 12:20:00', 'ACCEPTED', 'ACCEPTED', 'sims', '1b', 'avtale'),
(9, '3914-07-12 13:14:00', '3914-07-12 14:05:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1b', 'avtale'),
(10, '3914-07-12 11:14:00', '3914-07-12 14:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1a', 'avtale'),
(14, '3914-07-12 14:00:00', '3914-07-12 17:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1c', 'Velkommen endret'),
(15, '3914-07-12 17:15:00', '3914-07-12 18:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1c', 'Velkommen endret'),
(16, '3914-07-12 17:25:00', '3914-07-12 18:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1c', 'Velkommen endret'),
(17, '3914-07-12 17:45:00', '3914-07-12 18:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1c', 'Velkommen alle sammen'),
(18, '3914-07-12 17:00:00', '3914-07-12 18:00:00', 'Slottet', 'Ny ansatte er velkomne. Gratis lunsj', 'sims', '1c', 'Velkommen no sammen'),
(20, '3914-07-12 16:45:00', '3914-07-12 18:00:00', 'R-bygget', 'Dette skal fungere', 'hacker', '1c', NULL),
(21, '3914-07-12 16:45:00', '3914-07-12 18:00:00', 'R-bygget', 'Dette skal fungere', 'hacker', '1c', NULL),
(22, '2014-03-20 12:00:00', '2014-03-20 13:00:00', 'asd', 'asd', 'oyvind', 'None', 'Tittel'),
(23, '2014-03-21 00:00:00', '2014-03-21 00:00:00', 'DISBETEZT', '1b', 'petterek', '1b', 'MEin'),
(24, '2014-03-20 01:00:00', '2014-03-20 02:00:00', '', '', 'oyvind', 'None', 'FUN'),
(25, '2014-03-15 12:00:00', '2014-03-15 14:00:00', 'MEMEMEME', '3c', '', '3c', 'MEMEME'),
(26, '2014-03-20 01:00:00', '2014-03-20 02:00:00', '', '', 'oyvind', 'None', 'YAW'),
(27, '2014-03-17 10:00:00', '2014-03-17 12:00:00', 'MØT', '1b', 'petterek', '1b', 'Testerrrr'),
(28, '2014-03-21 14:00:00', '2014-03-21 15:00:00', 'asdasdasd', 'asdasdasd', 'oyvind', 'None', 'Oppfinnsomt navn'),
(29, '2014-03-19 00:00:00', '2014-03-19 01:00:00', '', '', 'oyvind', 'None', 'ITS A PARTY IN THE USA!'),
(30, '2014-03-20 17:00:00', '2014-03-20 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(31, '2014-03-22 12:00:00', '2014-03-22 13:00:00', 'asdasd', 'asdasd', 'oyvind', 'None', 'asdasd'),
(33, '2014-03-22 12:00:00', '2014-03-22 13:00:00', 'awrfawf', 'egegr', '', 'None', 'awrt'),
(34, '2014-03-08 12:00:00', '2014-03-08 13:00:00', 'WEF', 'sdfF', '', 'None', 'wf'),
(35, '2014-03-22 12:00:00', '2014-03-22 13:00:00', 'weqr', 'draerwef', '', 'None', 'hey'),
(36, '2014-03-08 12:00:00', '2014-03-08 13:00:00', 'ef', 'qer', '', 'None', 'j'),
(37, '2014-03-07 12:00:00', '2014-03-07 13:00:00', 'wer', 'wer', '', 'None', 'wrwew'),
(38, '2014-03-21 00:00:00', '2014-03-21 00:00:00', 'df', 'we', '', 'None', 'd'),
(39, '2014-03-13 00:00:00', '2014-03-13 00:00:00', 'fe', 'ef', '', 'None', 'werf'),
(40, '2014-03-13 00:00:00', '2014-03-13 00:00:00', 'werqwe', 'df', '', 'None', 'sdf'),
(41, '2014-03-13 00:00:00', '2014-03-13 00:00:00', 'werqwe', 'df', '', 'None', 'sdf'),
(42, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 's'),
(43, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 's'),
(44, '2014-03-15 00:00:00', '2014-03-15 00:00:00', '', '', '', 'None', '3'),
(47, '2014-03-19 17:00:00', '2014-03-19 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(48, '2014-03-19 17:00:00', '2014-03-19 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(49, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'd'),
(50, '2014-03-19 17:00:00', '2014-03-19 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(51, '2014-03-19 17:00:00', '2014-03-19 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(52, '2014-03-20 02:00:00', '2014-03-20 03:00:00', 'help', 'dfdf', 'iver', 'None', 'test1'),
(53, '2014-03-15 00:00:00', '2014-03-15 00:00:00', '', '', '', 'None', 'Datosjekk'),
(54, '2014-03-19 17:00:00', '2014-03-19 18:00:00', '', '', 'oyvind', 'None', 'OVERLAP'),
(55, '2014-03-20 02:00:00', '2014-03-20 03:00:00', 'help', 'dfdf', 'iver', 'None', 'test1'),
(58, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'sd'),
(59, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'sd'),
(60, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'sd'),
(61, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'sd'),
(65, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(66, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(67, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(68, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(69, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(70, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(71, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(72, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(73, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(74, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(75, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(76, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'wef'),
(79, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'test1'),
(80, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'test1'),
(82, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'test1'),
(84, '2014-03-31 12:00:00', '2014-03-31 01:40:00', 'Yo', 'Her hos meg', 'toresagen', 'None', 'Mote'),
(85, '2014-03-06 12:00:00', '2014-03-06 13:00:00', '', '3c', '', '3c', 'hei'),
(86, '2014-03-15 00:00:00', '2014-03-15 00:00:00', '', '', '', 'None', 'tesy'),
(88, '2014-03-14 00:00:00', '2014-03-14 00:00:00', '', '', '', 'None', 'er'),
(89, '2012-04-08 00:00:00', '2012-04-08 00:00:00', '', '', '', 'None', '2'),
(90, '2012-04-23 00:00:00', '2012-04-23 00:00:00', '', '', '', 'None', 'sdg'),
(92, '2014-03-21 00:00:00', '2014-03-21 00:00:00', 'Null null null', 'Er romm lik null?', '', 'None', 'Her er det ikke noe rom'),
(94, '2014-03-21 03:00:00', '2014-03-21 04:00:00', '', '1a', 'iver', '1a', 'det lange møtet'),
(97, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'hest'),
(99, '2014-03-22 00:00:00', '2014-03-22 12:00:00', '', 'Her', '', 'None', 'hest'),
(101, '2014-03-12 09:00:00', '2014-03-12 10:00:00', '', 'Her', '', 'None', 'hest'),
(102, '2014-03-12 09:00:00', '2014-03-12 10:00:00', 'Her', '', '', 'None', 'hest'),
(107, '2014-03-20 02:00:00', '2014-03-20 03:00:00', '', '', 'oyvind', 'None', 'testist'),
(108, '2014-03-20 02:00:00', '2014-03-20 03:00:00', '', '', 'oyvind', 'None', 'testist'),
(111, '2014-03-21 00:00:00', '2014-03-21 00:00:00', 'Null null null', '2a', '', 'None', 'Her er det '),
(112, '2014-03-17 00:00:00', '2014-03-17 00:00:00', 'Alle i HR er inviterte', '2a', '', '2a', 'Alle i HR'),
(113, '2014-03-17 00:00:00', '2014-03-17 00:00:00', '3c', 'Alle i hr er inviterte', '', 'None', 'Alle i HR'),
(114, '2014-03-25 03:00:00', '2014-03-25 04:00:00', 'testbesk', 'teststed', 'oyvind', 'None', 'test'),
(115, '2014-03-21 12:00:00', '2014-03-21 13:00:00', '', '', 'petterek', 'None', 'ikkememeg'),
(116, '2014-03-21 12:00:00', '2014-03-21 13:00:00', '', '', 'petterek', 'None', 'ikkemedmeg'),
(117, '2014-03-22 00:00:00', '2014-03-22 12:00:00', '', 'Her', '', 'None', 'hest'),
(118, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'hest'),
(120, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'hest'),
(121, '2014-03-17 00:00:00', '2014-03-17 02:00:00', 'Alle i HR ', '3c', '', '3c', 'Alle i HR 2'),
(122, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'hest'),
(123, '2014-03-19 00:00:00', '2014-03-19 00:00:00', '', '2a', '', 'None', 'Hallo?'),
(124, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'hest'),
(126, '2014-03-18 00:00:00', '2014-03-18 00:00:00', '', '', '', 'None', 'invitert Oppdatert'),
(127, '2014-03-18 00:00:00', '2014-03-18 00:00:00', '', '', '', 'None', 'invitert'),
(128, '2014-03-22 12:00:00', '2014-03-22 13:00:00', '', '', '', 'None', 'time'),
(129, '2014-03-22 12:00:00', '2014-03-22 13:00:00', '', '', '', 'None', 'time'),
(130, '2014-03-21 10:00:00', '2014-03-21 11:00:00', '', '', 'petterek', 'None', 'inviterte?'),
(131, '2014-03-21 10:00:00', '2014-03-21 11:00:00', '', '', 'petterek', 'None', 'inviterte?'),
(136, '2014-03-08 00:00:00', '2014-03-08 00:00:00', '', '', '', 'None', 'fdg'),
(137, '2014-03-12 00:00:00', '2014-03-12 00:00:00', '', '', '', 'None', 'sonofmybed'),
(138, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', '', 'None', 'invited'),
(139, '2014-03-22 00:00:00', '2014-03-22 00:00:00', '', '', 'petterek', 'None', 'test2'),
(140, '2014-03-19 00:00:00', '2014-03-19 00:00:00', '', '', '', 'None', 'invited'),
(141, '2014-03-19 00:00:00', '2014-03-19 00:00:00', '', '', '', 'None', 'invited'),
(142, '2014-03-22 00:00:00', '2014-03-22 12:00:00', '', 'Her', '', 'None', 'hest'),
(143, '2014-03-22 00:00:00', '2014-03-22 12:00:00', '', 'Her', '', 'None', 'hest'),
(144, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'sjekkdizshit'),
(145, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', '', 'None', 'sjekkdizshit'),
(146, '2014-03-18 00:00:00', '2014-03-18 00:00:00', '', '', '', 'None', 'invitert'),
(147, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', 'oyvind', 'None', 'asd'),
(148, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', 'oyvind', 'None', 'asd2'),
(149, '2014-03-24 00:00:00', '2014-03-24 00:00:00', '', '', '', 'None', 'miawf'),
(150, '2014-03-13 00:00:00', '2014-03-13 00:00:00', '', '', '', 'None', 'sadfasf'),
(151, '2014-03-21 08:00:00', '2014-03-21 09:00:00', '', '', '', 'None', 'yoyoyoyo'),
(152, '2014-03-18 00:00:00', '2014-03-18 00:00:00', '', '', 'petterek', 'None', 'HEYHEY'),
(153, '2014-03-21 08:00:00', '2014-03-21 09:00:00', '', '', '', 'None', 'STAHP'),
(155, '2014-03-19 00:00:00', '2014-03-19 00:00:00', '', '', '', 'None', 'mail mote'),
(156, '2014-03-20 02:00:00', '2014-03-20 03:00:00', '', '', 'petterek', 'None', 'test1'),
(157, '2014-03-20 02:00:00', '2014-03-20 03:00:00', '', '', 'petterek', 'None', 'test1'),
(159, '2014-03-21 02:00:00', '2014-03-21 03:00:00', '', '', 'petterek', 'None', 'Test'),
(161, '2014-03-01 00:00:00', '2014-03-01 00:00:00', '', '', 'petterek', 'None', 'test'),
(162, '2014-03-03 00:00:00', '2014-03-03 00:00:00', '', '', 'petterek', 'None', 'TEST1'),
(166, '2014-03-19 06:00:00', '2014-03-19 07:00:00', '', '', '', 'None', 'tiem'),
(167, '2014-03-19 00:00:00', '2014-03-19 00:00:00', 'heisann', 'hei', '', 'None', 'tiem'),
(168, '2014-03-27 00:00:00', '2014-03-27 03:00:00', 'Hei', '2a', '', '2a', 'Ukesmøte'),
(169, '2014-03-21 00:00:00', '2014-03-21 09:00:00', 'Heisann alle', '3c', '', '3c', 'HEST'),
(170, '2014-03-06 00:00:00', '2014-03-06 09:08:00', 'Møte nå', '3c', '', '3c', 'Møte med alle'),
(171, '2014-03-19 04:00:00', '2014-03-19 05:00:00', '', '', 'petterek', 'None', 'copynop'),
(172, '2014-03-17 05:00:00', '2014-03-17 06:00:00', '', '', 'petterek', 'None', 'nopypl0x?'),
(173, '2014-03-17 05:00:00', '2014-03-17 06:00:00', '', '', 'petterek', 'None', 'nopypl0x?'),
(174, '2014-03-31 00:00:00', '2014-03-31 09:06:00', 'Heisann', '2a', '', '2a', 'Møte med nye folk'),
(175, '2014-03-18 01:00:00', '2014-03-18 02:00:00', '', '', 'petterek', 'None', 'coplylox?'),
(176, '2014-03-18 01:00:00', '2014-03-18 02:00:00', '', '', 'petterek', 'None', 'coplylox?'),
(177, '2014-03-18 02:00:00', '2014-03-18 03:00:00', '', '', 'petterek', 'None', 'hawfjawf'),
(178, '2014-03-18 02:00:00', '2014-03-18 03:00:00', '', '', 'petterek', 'None', 'hawfjawf'),
(179, '2014-03-20 05:00:00', '2014-03-20 06:00:00', '', '', '', 'None', 'teaaam'),
(180, '2014-03-20 00:00:00', '2014-03-20 07:00:00', 'Partzy', 'The place', 'toresagen', 'None', 'Fest'),
(181, '2014-03-20 00:00:00', '2014-03-20 07:00:00', 'Partzy', 'The place', 'toresagen', 'None', 'Fest'),
(182, '2014-03-20 00:00:00', '2014-03-20 07:00:00', 'Partzy', 'The place', 'toresagen', 'None', 'Fest'),
(183, '2014-03-20 05:00:00', '2014-03-20 06:00:00', '', '', '', 'None', 'teaaam'),
(184, '2014-03-14 00:00:00', '2014-03-14 00:00:00', 'sdfgsadf', 'sdfgsa', 'toresagen', 'None', 'yo yo yo yo'),
(185, '2014-03-19 11:00:00', '2014-03-19 12:00:00', '', '', 'petterek', 'None', 'test1'),
(186, '2014-03-22 06:00:00', '2014-03-22 07:00:00', '', '', 'iver', 'None', 'YAYAYAYA'),
(187, '2014-03-19 00:00:00', '2014-03-19 23:00:00', 'Yo, ta med masse drikke', 'Slottet', 'toresagen', 'None', 'Fest'),
(188, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', 'petterek', 'None', 'test1'),
(189, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', 'petterek', 'None', 'test2'),
(190, '2014-03-22 06:00:00', '2014-03-22 07:00:00', '', 'None', '', 'None', 'ice-T'),
(191, '2014-03-30 00:00:00', '2014-03-30 00:00:00', 'GETOVERHIER', '', 'petterek', 'None', 'emails'),
(192, '2014-03-18 03:00:00', '2014-03-18 04:00:00', '', '1b', 'iver', '1b', 'MMI'),
(193, '2014-03-28 02:00:00', '2014-03-28 03:00:00', 'GETOVERHIER', '', 'petterek', 'None', 'aqrwf'),
(194, '2014-03-18 03:00:00', '2014-03-18 04:00:00', '', '1b', 'iver', '1b', 'MMI'),
(195, '2014-03-28 02:00:00', '2014-03-28 03:00:00', 'GETOVERHIER', '', 'petterek', 'None', 'emmmaiillss'),
(196, '2014-03-28 02:00:00', '2014-03-28 03:00:00', 'GETOVERHIER', '', 'petterek', 'None', 'emmmaiillss'),
(197, '2014-03-28 02:00:00', '2014-03-28 03:00:00', 'GETOVERHIER', '', 'petterek', 'None', 'emmmaiillss'),
(198, '2014-03-07 00:00:00', '2014-03-07 00:00:00', '', '', 'petterek', 'None', 'werwer'),
(199, '2014-03-18 00:00:00', '2014-03-18 02:00:00', 'komm komm', 'kom komm', 'toresagen', 'None', 'heisann sveisann'),
(200, '2014-03-21 00:00:00', '2014-03-21 00:00:00', '', '', 'petterek', 'None', 'selfie'),
(201, '2014-03-21 07:00:00', '2014-03-21 08:00:00', '', '', 'petterek', 'None', 'selfie'),
(202, '2014-03-21 02:00:00', '2014-03-21 03:00:00', '', '', 'petterek', 'None', 'emailsss'),
(203, '2014-03-27 00:00:00', '2014-03-27 00:00:00', '', '', 'petterek', 'None', 'emaaaaailssss'),
(204, '2014-03-20 08:00:00', '2014-03-20 09:00:00', '', '', 'oyvind', 'None', 'title'),
(205, '3914-07-12 16:45:00', '3914-07-12 18:00:00', 'R-bygget', 'Mail Testing', 'hacker', '1c', 'Mail testing'),
(206, '2014-03-23 05:00:00', '2014-03-23 06:00:00', '', '3c', 'oyvind', 'None', 'testing'),
(207, '2014-03-23 05:00:00', '2014-03-23 06:00:00', '', '3c', 'oyvind', '3c', 'romtest'),
(208, '2014-03-11 04:00:00', '2014-03-11 08:00:00', 'BOLLE', '2a', 'iver', '2a', 'bolle'),
(209, '2014-03-18 10:00:00', '2014-03-18 11:00:00', '', '', 'oyvind', 'None', 'testing'),
(210, '2014-03-22 18:00:00', '2014-03-22 23:59:00', '<NAME>', '<NAME>', 'iver', '3c', '<NAME>'),
(211, '2014-03-17 04:00:00', '2014-03-17 05:00:00', '2a', '<NAME>', 'steinarsagen', 'None', 'He<NAME>or'),
(212, '2014-03-21 06:00:00', '2014-03-21 07:00:00', '', 'None', '', 'None', '2131'),
(213, '2014-03-19 02:00:00', '2014-03-19 03:00:00', '<NAME>', 'her', 'oyvind', 'None', 'Invite test'),
(219, '2014-03-20 00:00:00', '2014-03-20 00:00:00', '', '', 'steinarsagen', 'None', 'MailFail2'),
(220, '2014-03-20 00:00:00', '2014-03-20 00:00:00', 'Heisann', '2a', '', '2a', 'heisann'),
(223, '2014-03-19 05:00:00', '2014-03-19 06:00:00', '', '', 'oyvind', 'None', 'invite 6'),
(224, '2014-03-17 00:00:00', '2014-03-17 00:00:00', '', '', 'steinarsagen', 'None', 'invitation'),
(225, '2014-03-21 12:00:00', '2014-03-21 13:00:00', '<3 MMI', '2a', 'oyvind', '2a', 'MMI'),
(226, '2014-03-21 07:00:00', '2014-03-21 08:00:00', '', '', 'oyvind', 'None', 'invite 7');
-- --------------------------------------------------------
--
-- Table structure for table `group_table`
--
CREATE TABLE IF NOT EXISTS `group_table` (
`groupname` varchar(15) NOT NULL,
`parent_groupname` varchar(15) DEFAULT NULL,
PRIMARY KEY (`groupname`),
KEY `subgroup` (`parent_groupname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `group_table`
--
INSERT INTO `group_table` (`groupname`, `parent_groupname`) VALUES
('Alle', NULL),
('HR', NULL),
('Kommunikasjon', NULL),
('PR', NULL),
('Sjefer', NULL),
('Slaver', NULL),
('Sleipner', NULL),
('Troll', NULL),
('Vaktmestere', NULL),
('Senior ansatt', 'Faste ansatte'),
('Faste ansatte', 'Troll'),
('Vikarer', 'Troll');
-- --------------------------------------------------------
--
-- Table structure for table `meetingroom`
--
CREATE TABLE IF NOT EXISTS `meetingroom` (
`roomnumber` varchar(45) NOT NULL,
`capacity` int(11) NOT NULL,
PRIMARY KEY (`roomnumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `meetingroom`
--
INSERT INTO `meetingroom` (`roomnumber`, `capacity`) VALUES
('1a', 2),
('1b', 5),
('1c', 3),
('2a', 10),
('3c', 7),
('none', 0);
-- --------------------------------------------------------
--
-- Table structure for table `member`
--
CREATE TABLE IF NOT EXISTS `member` (
`groupname` varchar(15) NOT NULL,
`username` varchar(15) NOT NULL,
PRIMARY KEY (`groupname`,`username`),
KEY `member_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `member`
--
INSERT INTO `member` (`groupname`, `username`) VALUES
('HR', '123'),
('Troll', '123'),
('Alle', '1234'),
('HR', '1234'),
('Alle', '444434'),
('Alle', '44444'),
('Alle', 'Det lange navne'),
('HR', 'Det lange navne'),
('Troll', 'Det lange navne'),
('Vikarer', 'Det lange navne'),
('Alle', 'finnen'),
('HR', 'finnen'),
('Alle', 'hacker'),
('HR', 'hacker'),
('Alle', 'iver'),
('Troll', 'iver'),
('Vikarer', 'iver'),
('Alle', 'mongobollefjes'),
('HR', 'mongobollefjes'),
('Alle', 'oyvind'),
('HR', 'oyvind'),
('Alle', 'petterek'),
('Slaver', 'petterek'),
('Alle', 'sims'),
('Sleipner', 'sims'),
('Troll', 'sims'),
('Alle', 'steinarsagen'),
('HR', 'testern2'),
('Alle', 'testuer'),
('Alle', 'TheMainMan'),
('Slaver', 'TheMainMan'),
('Troll', 'TheMainMan'),
('Alle', 'toresagen'),
('Slaver', 'toresagen'),
('Troll', 'toresagen'),
('Alle', 'toretorell'),
('Troll', 'toretorell'),
('Alle', 'yokuhuma'),
('Troll', 'yokuhuma');
-- --------------------------------------------------------
--
-- Table structure for table `notification`
--
CREATE TABLE IF NOT EXISTS `notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(15) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`appointmentId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `belonging_to` (`appointmentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;
--
-- Dumping data for table `notification`
--
INSERT INTO `notification` (`id`, `type`, `description`, `appointmentId`) VALUES
(19, 'REMINDER', 'Reminder for ''Velkommen endret'' at 17:15', 15),
(20, 'REMINDER', 'Meeting soon, bitch', 10),
(22, 'REMINDER', 'I hate meetings', 1),
(26, 'NORMAL', 'You have been invited to invite test 2', 1),
(27, 'NORMAL', 'You have been invited to invite4', 1),
(28, 'NORMAL', 'You have been invited to invite5', 1),
(29, 'NORMAL', 'You have been invited to invite 6', 1);
-- --------------------------------------------------------
--
-- Table structure for table `participant`
--
CREATE TABLE IF NOT EXISTS `participant` (
`username` varchar(45) NOT NULL,
`id` int(11) NOT NULL,
`status` varchar(45) DEFAULT NULL,
`hsidden` tinyint(1) DEFAULT NULL,
`alarm` int(11) DEFAULT NULL,
PRIMARY KEY (`username`,`id`),
KEY `appointment_participant` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `participant`
--
INSERT INTO `participant` (`username`, `id`, `status`, `hsidden`, `alarm`) VALUES
('', 85, 'ACCEPTED', 0, 0),
('', 92, 'ACCEPTED', 0, 0),
('', 97, 'ACCEPTED', 0, 0),
('', 99, 'ACCEPTED', 0, 0),
('', 101, 'ACCEPTED', 0, 0),
('', 102, 'INVITED', 0, 0),
('', 111, 'ACCEPTED', 0, 0),
('', 113, 'ACCEPTED', 0, 0),
('', 117, 'ACCEPTED', 0, 0),
('', 118, 'ACCEPTED', 0, 0),
('', 120, 'ACCEPTED', 0, 0),
('', 121, 'ACCEPTED', 0, 0),
('', 122, 'ACCEPTED', 0, 0),
('', 124, 'ACCEPTED', 0, 0),
('', 126, 'ACCEPTED', 0, 0),
('', 127, 'ACCEPTED', 0, 0),
('', 128, 'ACCEPTED', 0, 0),
('', 129, 'ACCEPTED', 0, 0),
('', 136, 'ACCEPTED', 0, 0),
('', 137, 'ACCEPTED', 0, 0),
('', 138, 'ACCEPTED', 0, 0),
('', 140, 'ACCEPTED', 0, 0),
('', 141, 'ACCEPTED', 0, 0),
('', 142, 'ACCEPTED', 0, 0),
('', 143, 'ACCEPTED', 0, 0),
('', 144, 'ACCEPTED', 0, 0),
('', 145, 'ACCEPTED', 0, 0),
('', 146, 'ACCEPTED', 0, 0),
('', 149, 'ACCEPTED', 0, 0),
('', 150, 'ACCEPTED', 0, 0),
('', 151, 'ACCEPTED', 0, 0),
('', 153, 'ACCEPTED', 0, 0),
('', 155, 'ACCEPTED', 0, 0),
('', 166, 'ACCEPTED', 0, 0),
('', 167, 'ACCEPTED', 0, 0),
('', 168, 'ACCEPTED', 0, 0),
('', 169, 'ACCEPTED', 0, 0),
('', 170, 'ACCEPTED', 0, 0),
('', 174, 'ACCEPTED', 0, 0),
('', 179, 'ACCEPTED', 0, 0),
('', 183, 'ACCEPTED', 0, 0),
('', 190, 'ACCEPTED', 0, 0),
('', 212, 'ACCEPTED', 0, 0),
('', 220, 'ACCEPTED', 0, 0),
('123', 15, 'ACCEPTED', 0, 30),
('123', 112, 'INVITED', 0, 0),
('123', 113, 'INVITED', 0, 0),
('123', 120, 'INVITED', 0, 0),
('123', 121, 'INVITED', 0, 0),
('123', 126, 'INVITED', 0, 0),
('123', 204, 'INVITED', 0, 0),
('1234', 112, 'INVITED', 0, 0),
('1234', 113, 'INVITED', 0, 0),
('1234', 121, 'INVITED', 0, 0),
('1234', 126, 'INVITED', 0, 0),
('1234', 208, 'INVITED', 0, 0),
('1234', 220, 'INVITED', 0, 0),
('444434', 208, 'INVITED', 0, 0),
('444434', 220, 'INVITED', 0, 0),
('44444', 208, 'INVITED', 0, 0),
('44444', 220, 'INVITED', 0, 0),
('Det lange navne', 28, 'INVITED', 0, 0),
('Det lange navne', 99, 'INVITED', 0, 0),
('Det lange navne', 112, 'INVITED', 0, 0),
('Det lange navne', 113, 'INVITED', 0, 0),
('Det lange navne', 114, 'INVITED', 0, 0),
('Det lange navne', 121, 'INVITED', 0, 0),
('Det lange navne', 126, 'INVITED', 0, 0),
('Det lange navne', 204, 'INVITED', 0, 0),
('Det lange navne', 208, 'INVITED', 0, 0),
('Det lange navne', 220, 'INVITED', 0, 0),
('finnen', 9, 'INVITED', 0, 0),
('finnen', 15, 'INVITED', 0, 0),
('finnen', 113, 'INVITED', 0, 0),
('finnen', 121, 'INVITED', 0, 0),
('finnen', 126, 'INVITED', 0, 0),
('finnen', 208, 'INVITED', 0, 0),
('finnen', 220, 'INVITED', 0, 0),
('hacker', 84, 'INVITED', 0, 0),
('hacker', 113, 'INVITED', 0, 0),
('hacker', 121, 'INVITED', 0, 0),
('hacker', 126, 'INVITED', 0, 0),
('hacker', 205, 'ACCEPTED', 0, 0),
('hacker', 208, 'INVITED', 0, 0),
('hacker', 220, 'INVITED', 0, 0),
('iver', 1, 'ACCEPTED', 0, 32),
('iver', 9, 'ACCEPTED', 0, 10),
('iver', 15, 'ACCEPTED', 0, 10),
('iver', 16, 'INVITED', 0, 39),
('iver', 52, 'INVITED', 0, 0),
('iver', 94, 'ACCEPTED', 0, 0),
('iver', 114, 'INVITED', 0, 0),
('iver', 169, 'DECLINED', 0, 0),
('iver', 186, 'ACCEPTED', 0, 0),
('iver', 192, 'ACCEPTED', 0, 0),
('iver', 194, 'ACCEPTED', 0, 0),
('iver', 208, 'ACCEPTED', 0, 0),
('iver', 210, 'ACCEPTED', 0, 0),
('iver', 220, 'INVITED', 0, 0),
('iver', 225, 'INVITED', 0, 0),
('mongobollefjes', 112, 'INVITED', 0, 0),
('mongobollefjes', 113, 'INVITED', 0, 0),
('mongobollefjes', 121, 'INVITED', 0, 0),
('mongobollefjes', 126, 'INVITED', 0, 0),
('mongobollefjes', 208, 'INVITED', 0, 0),
('mongobollefjes', 220, 'INVITED', 0, 0),
('oyvind', 25, 'INVITED', 0, 0),
('oyvind', 52, 'INVITED', 0, 0),
('oyvind', 84, 'INVITED', 0, 0),
('oyvind', 94, 'DECLINED', 0, 0),
('oyvind', 107, 'ACCEPTED', 0, 0),
('oyvind', 108, 'ACCEPTED', 0, 0),
('oyvind', 113, 'INVITED', 0, 0),
('oyvind', 114, 'ACCEPTED', 0, 0),
('oyvind', 121, 'INVITED', 0, 0),
('oyvind', 126, 'ACCEPTED', 0, 0),
('oyvind', 147, 'ACCEPTED', 0, 0),
('oyvind', 148, 'ACCEPTED', 0, 0),
('oyvind', 204, 'ACCEPTED', 0, 0),
('oyvind', 206, 'ACCEPTED', 0, 0),
('oyvind', 207, 'ACCEPTED', 0, 0),
('oyvind', 208, 'INVITED', 0, 0),
('oyvind', 209, 'ACCEPTED', 0, 0),
('oyvind', 213, 'ACCEPTED', 0, 0),
('oyvind', 220, 'INVITED', 0, 0),
('oyvind', 223, 'ACCEPTED', 0, 0),
('oyvind', 225, 'ACCEPTED', 0, 0),
('oyvind', 226, 'ACCEPTED', 0, 0),
('petterek', 115, 'ACCEPTED', 0, 0),
('petterek', 116, 'ACCEPTED', 0, 0),
('petterek', 130, 'ACCEPTED', 0, 0),
('petterek', 131, 'ACCEPTED', 0, 0),
('petterek', 139, 'ACCEPTED', 0, 0),
('petterek', 152, 'ACCEPTED', 0, 0),
('petterek', 156, 'ACCEPTED', 0, 0),
('petterek', 157, 'ACCEPTED', 0, 0),
('petterek', 159, 'ACCEPTED', 0, 0),
('petterek', 161, 'ACCEPTED', 0, 0),
('petterek', 162, 'ACCEPTED', 0, 0),
('petterek', 171, 'ACCEPTED', 0, 0),
('petterek', 172, 'ACCEPTED', 0, 0),
('petterek', 173, 'ACCEPTED', 0, 0),
('petterek', 175, 'ACCEPTED', 0, 0),
('petterek', 176, 'ACCEPTED', 0, 0),
('petterek', 177, 'ACCEPTED', 0, 0),
('petterek', 178, 'ACCEPTED', 0, 0),
('petterek', 185, 'ACCEPTED', 0, 0),
('petterek', 188, 'ACCEPTED', 0, 0),
('petterek', 189, 'ACCEPTED', 0, 0),
('petterek', 191, 'ACCEPTED', 0, 0),
('petterek', 193, 'ACCEPTED', 0, 0),
('petterek', 195, 'ACCEPTED', 0, 0),
('petterek', 196, 'ACCEPTED', 0, 0),
('petterek', 197, 'ACCEPTED', 0, 0),
('petterek', 198, 'ACCEPTED', 0, 0),
('petterek', 200, 'ACCEPTED', 0, 0),
('petterek', 201, 'ACCEPTED', 0, 0),
('petterek', 202, 'ACCEPTED', 0, 0),
('petterek', 203, 'ACCEPTED', 0, 0),
('petterek', 208, 'INVITED', 0, 0),
('petterek', 219, 'INVITED', 0, 0),
('petterek', 220, 'INVITED', 0, 0),
('petterek', 224, 'ACCEPTED', 0, 0),
('sims', 1, 'ACCEPTED', 0, 20),
('sims', 10, 'DECLINED', 0, 10),
('sims', 15, 'DECLINED', 0, 10),
('sims', 84, 'INVITED', 0, 0),
('sims', 101, 'INVITED', 0, 0),
('sims', 102, 'INVITED', 0, 0),
('sims', 208, 'INVITED', 0, 0),
('sims', 209, 'INVITED', 0, 0),
('sims', 220, 'INVITED', 0, 0),
('sims', 224, 'ACCEPTED', 0, 0),
('sims1', 15, 'ACCEPTED', 0, 45),
('steinarsagen', 208, 'ACCEPTED', 0, 0),
('steinarsagen', 211, 'ACCEPTED', 0, 0),
('steinarsagen', 219, 'ACCEPTED', 0, 0),
('steinarsagen', 220, 'INVITED', 0, 0),
('steinarsagen', 224, 'ACCEPTED', 0, 0),
('testern2', 28, 'INVITED', 0, 0),
('testern2', 113, 'INVITED', 0, 0),
('testern2', 121, 'INVITED', 0, 0),
('testern2', 126, 'INVITED', 0, 0),
('testuer', 84, 'INVITED', 0, 0),
('testuer', 97, 'INVITED', 0, 0),
('testuer', 126, 'INVITED', 0, 0),
('testuer', 127, 'INVITED', 0, 0),
('testuer', 130, 'INVITED', 0, 0),
('testuer', 140, 'INVITED', 0, 0),
('testuer', 149, 'INVITED', 0, 0),
('testuer', 150, 'INVITED', 0, 0),
('testuer', 208, 'INVITED', 0, 0),
('testuer', 220, 'INVITED', 0, 0),
('TheMainMan', 84, 'INVITED', 0, 0),
('TheMainMan', 99, 'INVITED', 0, 0),
('TheMainMan', 102, 'INVITED', 0, 0),
('TheMainMan', 122, 'INVITED', 0, 0),
('TheMainMan', 140, 'INVITED', 0, 0),
('TheMainMan', 144, 'INVITED', 0, 0),
('TheMainMan', 152, 'INVITED', 0, 0),
('TheMainMan', 204, 'INVITED', 0, 0),
('TheMainMan', 208, 'INVITED', 0, 0),
('TheMainMan', 220, 'INVITED', 0, 0),
('toresagen', 84, 'INVITED', 0, 0),
('toresagen', 102, 'INVITED', 0, 0),
('toresagen', 129, 'INVITED', 0, 0),
('toresagen', 150, 'ACCEPTED', 0, 0),
('toresagen', 180, 'ACCEPTED', 0, 0),
('toresagen', 181, 'ACCEPTED', 0, 0),
('toresagen', 182, 'ACCEPTED', 0, 0),
('toresagen', 184, 'ACCEPTED', 0, 0),
('toresagen', 187, 'ACCEPTED', 0, 0),
('toresagen', 199, 'ACCEPTED', 0, 0),
('toresagen', 200, 'INVITED', 0, 0),
('toresagen', 208, 'HIDDEN', 0, 0),
('toresagen', 209, 'ACCEPTED', 0, 0),
('toresagen', 211, 'ACCEPTED', 0, 0),
('toresagen', 213, 'INVITED', 0, 0),
('toresagen', 220, 'INVITED', 0, 0),
('toresagen', 223, 'INVITED', 0, 0),
('toresagen', 226, 'DECLINED', 0, 0),
('toretorell', 84, 'INVITED', 0, 0),
('toretorell', 97, 'INVITED', 0, 0),
('toretorell', 124, 'INVITED', 0, 0),
('toretorell', 130, 'INVITED', 0, 0),
('toretorell', 131, 'INVITED', 0, 0),
('toretorell', 140, 'INVITED', 0, 0),
('toretorell', 144, 'INVITED', 0, 0),
('toretorell', 208, 'INVITED', 0, 0),
('toretorell', 220, 'INVITED', 0, 0),
('yokuhuma', 200, 'INVITED', 0, 0),
('yokuhuma', 208, 'INVITED', 0, 0),
('yokuhuma', 220, 'INVITED', 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`username` varchar(15) NOT NULL,
`password` varchar(45) NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`mail` varchar(45) NOT NULL,
`phone` char(12) NOT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`username`, `password`, `first_name`, `last_name`, `mail`, `phone`) VALUES
('', '<PASSWORD>', '', '', '', ''),
('123', '123', '123', '123', '123', '123'),
('1234', '<PASSWORD>', '1234', '1234', '1234', '1234'),
('444434', '<PASSWORD>', '<PASSWORD>', 'aasen', '<EMAIL>', '87654321'),
('44444', 'e10adc3949ba59abbe56e057f20f883e', 'ivar', 'aasen', '<EMAIL>', '87654321'),
('abc', '900150983cd24fb0d6963f7d28e17f72', 'abc', 'abc', 'abc', '123'),
('Det lange navne', '', 'Lang', 'Navnet', 'Nei takk', '123345'),
('finnen', '6f8ad1ab4f8baa6ebdcbd5f0a1aab558', 'finn', 'kr', '<EMAIL>', '12345678'),
('hacker', '202cb962ac59075b964b07152d234b70', 'Hack', 'Hackersen', '<EMAIL>', '13375658'),
('iver', '906d0b46c6953f905598aa15308694ad', 'iver', 'egge', '<EMAIL>', ''),
('mongobollefjes', '202cb962ac59075b964b07152d234b70', 'Mongo', 'Bollefjes', '<EMAIL>', '13375658'),
('oyvind', '81dc9bdb52d04dc20036dbd8313ed055', 'Øyvind', 'Kjerland', '<EMAIL>', '12345678'),
('petteree', '333', 'Ekern', 'Petter', '123@3333', '345345'),
('petterek', '202cb962ac59075b964b07152d234b70', 'Petter', 'Ekern', '@@@', '23234235'),
('sims', '123', 'Simen', 'Selseng', '<EMAIL>', '123123123'),
('sims1', '465', '123', '123', '<EMAIL>', '123345'),
('steinarsagen', '202cb962ac59075b964b07152d234b70', 'Steinar', 'Sagen', '<EMAIL>', '14365658'),
('testern', 'gullrot', 'Test', 'Testersen', '<EMAIL>', '3333333'),
('testern2', 'gullrot', 'Test', 'Testersen', '<EMAIL>', '43327928'),
('testuer', 'user', 'hei', 'sann', 'mail', '1234'),
('TheMainMan', 'e10adc3949ba59abbe56e057f20f883e', 'ivar', 'aasen', '<EMAIL>', '87654321'),
('toresagen', '202cb962ac59075b964b07152d234b70', 'Tore', 'Sagen', '<EMAIL>', '123123123'),
('toretorell', '202cb962ac59075b964b07152d234b70', 'Tore', 'Torell', '<EMAIL>', '14365658'),
('yokuhuma', '202cb962ac59075b964b07152d234b70', 'Poke', 'Mon', '<EMAIL>', '13375658');
-- --------------------------------------------------------
--
-- Table structure for table `user_notification`
--
CREATE TABLE IF NOT EXISTS `user_notification` (
`notificationId` int(11) NOT NULL,
`username` varchar(15) NOT NULL,
PRIMARY KEY (`notificationId`,`username`),
KEY `user_notification_u` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user_notification`
--
INSERT INTO `user_notification` (`notificationId`, `username`) VALUES
(19, '123'),
(20, '123'),
(22, '123'),
(19, 'sims1'),
(22, 'sims1'),
(29, 'toresagen');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `appointment`
--
ALTER TABLE `appointment`
ADD CONSTRAINT `reservation` FOREIGN KEY (`roomnumber`) REFERENCES `meetingroom` (`roomnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `responsible` FOREIGN KEY (`responsible_username`) REFERENCES `user` (`username`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `group_table`
--
ALTER TABLE `group_table`
ADD CONSTRAINT `subgroup` FOREIGN KEY (`parent_groupname`) REFERENCES `group_table` (`groupname`) ON UPDATE CASCADE;
--
-- Constraints for table `member`
--
ALTER TABLE `member`
ADD CONSTRAINT `member_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `member_of_group` FOREIGN KEY (`groupname`) REFERENCES `group_table` (`groupname`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `notification`
--
ALTER TABLE `notification`
ADD CONSTRAINT `belonging_to` FOREIGN KEY (`appointmentId`) REFERENCES `appointment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `participant`
--
ALTER TABLE `participant`
ADD CONSTRAINT `user_participant` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `appointment_participant` FOREIGN KEY (`id`) REFERENCES `appointment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `user_notification`
--
ALTER TABLE `user_notification`
ADD CONSTRAINT `user_notification_n` FOREIGN KEY (`notificationId`) REFERENCES `notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `user_notification_u` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/ktn2/chatinterface.py
import curses
from curses import wrapper
from client import Client
from threading import Lock
import time
import sys
class ChatInterface:
def __init__(self):
#HOST = '172.16.58.3'
HOST = '172.16.58.3'
#HOST = 'localhost'
PORT = 9999
# Initialiser klienten
self.client = Client()
self.client.setListener(self)
# Start klienten
self.client.start(HOST, PORT)
self.loginDelay = 3
self.queueSize = 20
self.messageQueue = []
self.queueLock = Lock()
self.stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
self.isRunning = True
wrapper(self.main)
def shutDown(self):
self.isRunning = False
curses.nocbreak()
self.stdscr.keypad(0)
curses.echo()
def main(self, stdscr):
# Clear screen
self.stdscr = stdscr
stdscr.clear()
curses.echo()
while self.isRunning:
if self.client.isLoggedIn():
stdscr.clear()
with self.queueLock:
self.showMessages()
stdscr.addstr(self.queueSize,0,"---------------")
stdscr.addstr(self.queueSize+1,0,"Input message: ")
if(not self.isRunning):
break
message = stdscr.getstr()
self.client.checkMessage(message)
stdscr.refresh()
# Client is not logged in, ask for login
else:
stdscr.clear()
stdscr.addstr(self.queueSize,0,"---------------")
stdscr.addstr(self.queueSize+1,0,"Input username: ")
nick = stdscr.getstr()
# Try to login
self.client.login(nick)
self.stdscr.clear()
self.stdscr.refresh()
time.sleep(self.loginDelay)
stdscr.refresh()
def clearMessages(self):
self.messageQueue = []
def addMessage(self, message):
with self.queueLock:
if len(self.messageQueue) == self.queueSize:
self.messageQueue.pop(0)
self.messageQueue.append(message)
self.showMessages()
def showMessages(self):
y, x = self.stdscr.getyx()
for i in xrange(0,len(self.messageQueue)):
lengde = len(self.messageQueue[i])
self.stdscr.move(i,0)
self.stdscr.clrtoeol()
if("Logged in as " in self.messageQueue[i][0:14]):
self.stdscr.addstr(i,0,self.messageQueue[i], curses.color_pair(3))
continue
self.stdscr.addstr(i,0,self.messageQueue[i][0:16], curses.color_pair(2))
if("logged in." in self.messageQueue[i]):
self.stdscr.addstr(i,16,self.messageQueue[i][16:lengde], curses.color_pair(1))
else:
self.stdscr.addstr(i,16,self.messageQueue[i][16:lengde])
self.stdscr.move(y,x)
self.stdscr.refresh()
if __name__ == "__main__":
chatInterface = ChatInterface()<file_sep>/ktn2/client.py
# -*- coding: utf-8 -*-
import socket
import json
from MessageWorker import ReceiveMessageWorker
import sys
class Client(object):
def __init__(self):
# Initialiser en tilkobling
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.messageWorker = ReceiveMessageWorker(self, self.connection)
self.loggedIn = False
self.listener = None
def setListener(self, listener):
self.listener = listener
def start(self, host, port):
# Start tilkoblingen
self.connection.connect((host, port))
# Start MessageWorker
self.messageWorker.start()
def isLoggedIn(self):
return self.loggedIn
def checkMessage(self,message):
if message == 'logout':
data = {'request': 'logout'}
data = json.dumps(data)
self.send(data)
else:
self.sendMessage(message)
def sendMessage(self, message):
# Konstruer et JSON objekt som som skal
# sendes til serveren
data = {'request': 'message', 'message': message}
# Lag en streng av JSON-objektet
data = json.dumps(data)
self.send(data)
def printDebugMessage(self,message):
self.listener.addMessage(message)
# Lag en metode for å sende en melding til serveren
def send(self, data):
self.connection.send(data)
def dataReceived(self, data):
if not data: return
data = json.loads(data)
if(data.get('error')):
error = data['error']
self.listener.addMessage(error)
elif not self.loggedIn:
if(data.get('response')):
if(data['response'] == 'login'):
self.listener.addMessage('Logged in as ' + data['username'])
self.loggedIn = True
self.showBackLog(data['messages'])
#backlog = data['messages']
#self.printBacklog(backlog)
elif self.loggedIn:
if(data.get('response')):
if(data['response'] == 'message'):
self.listener.addMessage(data['message'])
elif(data['response'] == 'logout'):
#Stopper alt
self.loggedIn = False;
self.listener.shutDown()
self.messageWorker.shutdown()
self.connection.close()
self.listener.addMessage('You logged out')
sys.exit()
def showBackLog(self,messages):
for message in messages:
self.listener.addMessage(message)
def login(self, nick):
data = {'request': 'login', 'username': nick}
data = json.dumps(data)
self.send(data)
<file_sep>/ktn2/MessageWorker.py
'''
KTN-project 2013 / 2014
Python daemon thread class for listening for events on
a socket and notifying a listener of new messages or
if the connection breaks.
'''
from threading import Thread
class ReceiveMessageWorker(Thread):
def __init__(self, listener, connection):
# Initialize super class
super(ReceiveMessageWorker, self).__init__()
# Set thread as daemon to make python shut down properly on exit
self.daemeon = True
self.isRunning = True
self.listener = listener
self.connection = connection
def shutdown(self):
self.isRunning = False
def splitAndSendMessage(self,data):
array = data.split("}{")
for linje in array:
updatedLine = linje
if not linje[0] == '{':
updatedLine = '{' + updatedLine
if not linje[-1] == '}':
updatedLine = updatedLine + '}'
self.listener.dataReceived(updatedLine)
def run(self):
while self.isRunning:
data = self.connection.recv(1024)
if not data: continue
self.splitAndSendMessage(data)
#self.listener.dataReceived(data)
|
9269b5baabd68875b5ee651b6eb4a15822f4f82b
|
[
"Markdown",
"SQL",
"Python",
"Text"
] | 8
|
Text
|
oyvind-kjerland/Fellespro25
|
76af1694bafd276fac4b603d9d12224e8a5fdf28
|
adbf1f7307b842e70a303b0cce0a204705f75452
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
namespace ExcelWorld
{
public partial class Ribbon1
{
public Form1 form1;
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void startButton_Click(object sender, RibbonControlEventArgs e)
{
// どうやらGlobalsを通して呼ぶみたいだけれど、そんなstaticおじさんみたいな手段しかないのってどうよ?
Globals.ThisAddIn.HelloWorld();
}
private void editButton_Click(object sender, RibbonControlEventArgs e)
{
if (form1 == null || form1.IsDisposed)
{
form1 = new Form1();
form1.Visible = !form1.Visible;
}
}
}
}
|
d4625b5800905c40b6906ef5fd77c57af7e997f8
|
[
"C#"
] | 1
|
C#
|
nrapmed/ExcelWorld
|
f1f95fbe1dc5aefc23b59c58aae974db7293d36d
|
5efb576e7f4835ab18c9d69354c8eb86a7f79483
|
refs/heads/master
|
<repo_name>Kyryn/MultiColorSTL2<file_sep>/js/stl.js
var container = document.getElementById('container');
var W = 500, H = 400;
// window.innerWidth, window.innerHeight ;
var scene = new THREE.Scene();
scene.background = new THREE.Color(0xEEEEEE);
var camera = new THREE.PerspectiveCamera(75, W / H, 1, 1000);
// camera.position.set(3, 0.15, 20);
camera.position.z = 200;
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(W, H);
// renderer.setPixelRatio( window.devicePixelRatio );
// renderer.gammaInput = true;
// renderer.gammaOutput = true;
// renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.rotateSpeed = 0.05;
controls.dampingFactor = 0.1;
controls.enableZoom = true;
// controls.autoRotate = true;
// controls.autoRotateSpeed = .75;
// controls.addEventListener( 'change', render );
// scene.add(new THREE.HemisphereLight(0x443333, 0x111122));
// var ambientLight = new THREE.AmbientLight( 0x0f0f0f );
// scene.add( ambientLight );
// var loader = new THREE.ThreeMFLoader();
// loader.load( '/stl/grinder.3mf', function ( object ) {
//
// console.log("3mf model loading",object);
//
// object.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) ); // z-up conversion
// object.traverse( function ( child ) {
// child.castShadow = true;
// } );
// scene.add( object );
// // render();
// } );
var mesh;
var loader = new THREE.STLLoader();
// loader.load('/stl/test1.stl', function (geometry) {
// loader.load('/stl/bf4.stl', function (geometry) {
// loader.load('/stl/BT4 80per.stl', function (geometry) {
// loader.load('/stl/BT4 8020per.stl', function (geometry) {
loader.load('/stl/BT4 8080per.stl', function (geometry) {
console.log('Load', geometry);
geometry.center()
// var material = new THREE.MeshPhongMaterial({color: 0xff5533, specular: 0x111111, shininess: 200});
// var material = new THREE.MeshStandardMaterial({
var material = new THREE.MeshBasicMaterial({
// var material = new THREE.MeshLambertMaterial({
side: THREE.DoubleSide,
// color: 0xF5F5F5,
// flatShading: true,
// combine:THREE.MixOperation,
color: 0xffffff,
// shininess: 0,
vertexColors: THREE.VertexColors
})
mesh = new THREE.Mesh(geometry, material);
// mesh.position.set( 0, - 0.25, 0.6 );
// mesh.scale.set(0.5, 0.5, 0.5);
mesh.rotation.set(-Math.PI / 2, 0, 0);
// mesh.castShadow = true;
// mesh.receiveShadow = true;
updateColors();
scene.add(mesh);
console.log(mesh);
});
var animate = function () {
requestAnimationFrame(animate);
// if (mesh) {
// mesh.rotation.x += 0.01;
// mesh.rotation.y += 0.01;
// }
controls.update();
renderer.render(scene, camera);
};
animate();
function getColorbyConfig(zindex) {
var tempxolor = '#000000';
for (var i = 0; i < config.length; i++) {
var maxlimit = config[i][0];
tempxolor = config[i][1];
if (zindex < maxlimit) {
return tempxolor;
}
}
return tempxolor;
}
function updateColors(newconfig = null) {
if(newconfig){
config = newconfig;
}
if(!mesh){
return false
}
var mgeometry = mesh.geometry;
var positions = mgeometry.attributes.position;
var colors = [];
console.log('Update color', config, mgeometry.boundingBox.min.z);
for (var i = 0; i < positions.count; ++i) {
var zval = positions.getZ(i) - mgeometry.boundingBox.min.z;
var zvalpercent = ( zval / (mgeometry.boundingBox.max.z - mgeometry.boundingBox.min.z) ) * 100;
var color = new THREE.Color(getColorbyConfig(zvalpercent))
colors.push(color.r, color.g, color.b);
// colors.setXYZ( i, color.r, color.g, color.b );
}
// colors.needsUpdate = true;
mgeometry.addAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
return true;
}<file_sep>/js/app.js
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
items: typs['trips'],
colors: barvy,
};
if (window.location.hash.startsWith('#config')) {
console.log(window.location);
this.state.items = JSON.parse(window.location.hash.slice(8).replace(/'/g, '"'))
// console.log(this.state.items);
// window.location.hash = ''
}
this.updatemodel();
}
componentDidMount() {
this.createslider()
}
updatemodel() {
console.log('ubdate by', this.state.items);
window.location.hash = this.getConfStr();
updateColors(this.state.items);
}
// changenum(i, val) {
// let items = this.state.items;
// items[i][0] = val;
// this.setState({items: items});
//
// this.updatemodel()
// this.createslider()
//
// }
changecolor(i, val) {
let items = this.state.items;
items[i][1] = val;
this.setState({items: items});
this.updatemodel()
this.createslider()
}
getConfStr() {
return 'config=' + JSON.stringify(this.state.items).replace(/"/g, "'");
}
render() {
let {items, colors} = this.state;
let confstr = window.origin + '#' + this.getConfStr();
return (
<div>
<div style={{height: '500px'}}>
{
items.slice(0).reverse().map((item, index) =>
<div style={{padding: 0}} key={items.length - index - 1}>
{/*<input value={item[0]} type="number" disabled*/}
{/*onChange={(event) => this.changenum(items.length - index - 1, event.target.value)}/>*/}
<div style={{
margin: '5px 0',
background: '#CCCCCC',
position: 'absolute',
top: 5 * (100 - item[0])
}}>
{
colors.map((color, indexc) =>
<button onClick={ () => this.changecolor(items.length - index - 1, color)}
key={indexc}
title={color}
style={{
cursor: 'pointer', background: color,
padding: '8px 10px', margin: '8px',
border: item[1] == color ? '2px solid black' : '2px solid white'
}}
/>
)
}
</div>
</div>
)
}
</div>
Odkaz na aktuální model:<br/>
<a href={confstr} target="_blank">{confstr} </a>
</div>
)
}
sliderOptions = {
range: {
'min': 0,
'max': 100
},
step: 5,
start: [20],
// ... must be at least 300 apart
margin: 5,
// connect: [true,true,true, true, true,true,true,true,true],
// Put '0' at the bottom of the slider
direction: 'rtl',
orientation: 'vertical',
// Move handle on tap, bars are draggable
behaviour: 'tap-drag',
tooltips: true,
// format: wNumb({
// decimals: 0
// }),
// Show a scale with the slider
pips: {
mode: 'steps',
stepped: true,
density: 4
}
};
createslider() {
var range = window.document.getElementById('range');
console.log('range', range);
if (range.noUiSlider) {
range.noUiSlider.destroy();
}
let items = this.state.items;
let self = this;
let options = this.sliderOptions;
options.start = items.slice(0, -1).map(i => i[0])
options.connect = Array(items.length).fill(true)
noUiSlider.create(range, options);
var connect = range.querySelectorAll('.noUi-connect');
for (var i = 0; i < items.length; i++) {
console.log(connect[i]);
connect[i].style.background = items[i][1]
}
range.noUiSlider.on('change', function (vals) {
console.log('vals', vals);
vals.forEach((val, index) => {
items[index][0] = val;
})
items[vals.length][0] = 100
self.setState({
items: items
})
self.updatemodel()
})
}
}
ReactDOM.render(<Square />,
document.getElementById('reactapp')
);
// initslider();
function initslider() {
}
|
f19b55708bca22c8815a829edf2116ba7b35ca9c
|
[
"JavaScript"
] | 2
|
JavaScript
|
Kyryn/MultiColorSTL2
|
3c0bf7082e79f6952d12b778e1303b66bd0dcb68
|
26b03677ef79068eb61933eaf9a34c1b9487871d
|
refs/heads/master
|
<repo_name>coolxx/zhentiyidong<file_sep>/js/index.js
$(function(){
if($(window).width()<720){
(function (win,doc){
function change(){
doc.documentElement.style.fontSize=20*doc.documentElement.clientWidth/360+'px';
}
change();
win.addEventListener('resize',change,false);
})(window,document);
}
$(window).resize(function(){
if($(window).width()<720){
(function (win,doc){
function change(){
doc.documentElement.style.fontSize=20*doc.documentElement.clientWidth/360+'px';
}
change();
win.addEventListener('resize',change,false);
})(window,document);
}
})
$('.m4-btn p').click(function () {
$('.m4-btn p').removeClass('on3').eq($(this).index()).addClass('on3');
$('.m4-show').hide().eq($(this).index()).show()
})
$('.btn2-box1 p').toggle(function () {
$('.btn2-box1 ul').addClass('nam1')
},function () {
$('.btn2-box1 ul').removeClass('nam1')
})
$('.btn2-box2 p').toggle(function () {
$('.btn2-box2 ul').addClass('nam2')
},function () {
$('.btn2-box2 ul').removeClass('nam2')
})
$('.btn2-box1 li').each(function (index) {
$(this).click(function () {
$('.btn2-box1 li').removeClass('on4').eq(index).addClass('on4');
$('.btn-show1').hide().eq(index).show()
})
})
$('.btn2-box2 li').each(function (index) {
$(this).click(function () {
$('.btn2-box2 li').removeClass('on4').eq(index).addClass('on4');
$('.btn-show2').hide().eq(index).show()
})
})
$('.foot em').click(function(){
$('.foot').hide()
$('.open').show()
})
$('.open').click(function(){
$(this).hide()
$('.foot').show()
})
var oH=$('nav').outerHeight(true)
$('nav a').each(function(index){
$(this).click(function(){
var h=$('.md').eq(index).position().top-oH;
$('nav a').css('color','#fff').eq(index).css('color','#ffe400');
$('body,html').animate({'scrollTop':h},300)
})
})
})
|
5ff798871d1a7b4e4149a2673948f268c54f3b96
|
[
"JavaScript"
] | 1
|
JavaScript
|
coolxx/zhentiyidong
|
0ab54e7e7db1a73b55fd4ca68e13a7c0a114f31e
|
68c3042155ae0824f417deac7c61a5c23a7362b8
|
refs/heads/master
|
<file_sep>package com.mipl.rxandroiddemo.activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.mipl.rxandroiddemo.MainActivity;
import com.mipl.rxandroiddemo.R;
import com.mipl.rxandroiddemo.databinding.ActivitySelectionBinding;
/**
* Created by <NAME> on 1/8/2018.
*/
public class SelectionActivity extends AppCompatActivity implements View.OnClickListener{
private ActivitySelectionBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_selection);
binding.btnTextviewExample.setOnClickListener(this);
binding.btnRetrofitExample.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_textview_example:
startActivity(new Intent(SelectionActivity.this, MainActivity.class));
break;
case R.id.btn_retrofit_example:
break;
}
}
}
|
56962488d1c58740e4521bcc428a0d9bd6e56dee
|
[
"Java"
] | 1
|
Java
|
ranasaha1212/RxJava-RxAndroid-Demo
|
aa95370d48a250a605a126c5f5dc64288d2594c6
|
dd891ccabeaa0cd10d38d4c70f3308359fd5908b
|
refs/heads/master
|
<file_sep>package com.vanniktech.rxriddles
import com.vanniktech.rxriddles.solutions.Riddle12Solution
import com.vanniktech.rxriddles.tools.RxRule
import io.reactivex.Observable
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/** Solution [Riddle12Solution] */
class Riddle1003CustomObservable {
@get:Rule
val rxRule = RxRule()
@Test
fun `Simple observable creation`() {
val o = Observable.create<Int> { }
assertThat(o.test().hasSubscription())
}
@Test
fun `Simple observable creation with single Int pushed to the stream`() {
val o = Observable.create<Int> { emitter ->
emitter.onNext(1)
emitter.onComplete()
}
o.test()
.assertSubscribed()
.assertValues(1)
.assertComplete()
.assertNoErrors()
}
/**
* https://medium.com/@vanniktech/testing-rxjava-code-made-easy-4cc32450fc9a
*/
@Test
fun `Same as above but simplier`() {
Observable.just(1)
.test()
.assertResult(1)
}
@Test
fun shouldCreateFromArray() {
Observable.fromArray("a", "b")
.doOnNext(System.out::println)
.test()
.assertResult("a", "b")
}
@Test
fun shouldCreateFromJust() {
Observable.just("a", "b")
.doOnNext(System.out::println)
.test()
.assertResult("a", "b")
}
@Test
fun shouldCreateFromCreate() {
Observable.create<String> { emitter ->
emitter.onNext("a")
emitter.onNext("b")
}
.doOnNext(System.out::println)
.test()
.assertNotComplete()
}
// create vs subscribe (when code runs) vs defer
// code in create is executed after subscription
@Test
fun shouldRunWhenSubscribed() {
val counter = AtomicInteger()
val observable = Observable.create<Long> { emitter ->
System.out.println("Observable is created")
for (i in 1..10) {
System.out.println("counter: ${counter.incrementAndGet()}")
emitter.onNext(System.currentTimeMillis() % 100)
}
System.out.println("End of emission (no onComplete)")
}
System.out.println("TIME before subscriptions: ${System.currentTimeMillis() % 100}")
observable
.doOnNext {
System.out.println("1: [$it]")
}
.test()
.assertNotComplete()
observable
.doOnNext {
System.out.println("2: [$it]")
}
.test()
.assertNotComplete()
observable
.doOnNext {
System.out.println("3: [$it]")
}
.test()
.assertNotComplete()
}
@Test
fun shouldRunWhenSubscribedWithOnComplete() {
val counter = AtomicInteger()
val observable = Observable.create<Long> { emitter ->
System.out.println("Observable is created")
for (i in 1..10) {
System.out.println("counter: ${counter.incrementAndGet()}")
emitter.onNext(System.currentTimeMillis() % 100)
}
System.out.println("End of emission >> onComplete")
emitter.onComplete()
}
System.out.println("TIME before subscriptions: ${System.currentTimeMillis() % 100}")
observable
.doOnNext {
System.out.println("1: [$it]")
}
.test()
.assertComplete()
observable
.doOnNext {
System.out.println("2: [$it]")
}
.test()
.assertComplete()
observable
.doOnNext {
System.out.println("3: [$it]")
}
.test()
.assertComplete()
}
@Test
fun shouldRunWhenSubscribedWithOnCompleteAndJust() {
val counter = AtomicInteger()
val observable = Observable.fromArray(getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime(), getCurrentTime())
System.out.println("TIME before subscriptions: ${getCurrentTime()}")
observable
.doOnNext {
System.out.println("1: [$it]")
}
.test()
.assertComplete()
observable
.doOnNext {
System.out.println("2: [$it]")
}
.test()
.assertComplete()
observable
.doOnNext {
System.out.println("3: [$it]")
}
.test()
.assertComplete()
}
private fun getCurrentTime(): Long {
val time = System.currentTimeMillis() % 1000
System.out.println("getCurrentTime(): $time")
return time
}
@Test
fun shouldDelayButDoesnt1() {
val counter = AtomicInteger()
val observable = Observable.create<Int> { emitter ->
System.out.println("Observable is created")
for (i in 1..3) {
val currentCount = counter.getAndIncrement()
System.out.println("Emitting counter: $currentCount")
emitter.onNext(currentCount)
}
System.out.println("End of emission >> onComplete")
emitter.onComplete()
}
System.out.println("Counter before subscriptions: ${counter.getAndIncrement()}")
// HERE IS DELAY FOR FLAT MAPPED OBSERVABLE
val o = observable
.flatMap { t -> Observable.just(t).delay(10, TimeUnit.MILLISECONDS) }
.test()
o.assertEmpty()
o.assertNotComplete()
rxRule.advanceTimeBy(10, TimeUnit.MILLISECONDS)
o.assertResult(1, 2, 3)
}
@Test
fun shouldDelaySubscriptionButNotIndividualEmissions() {
val counter = AtomicInteger()
val observable = Observable.create<Int> { emitter ->
System.out.println("Observable is created")
for (i in 1..3) {
val currentCount = counter.getAndIncrement()
System.out.println("Emitting counter: $currentCount")
emitter.onNext(currentCount)
}
System.out.println("End of emission >> onComplete")
emitter.onComplete()
}
System.out.println("Counter before subscriptions: ${counter.getAndIncrement()}")
val o = observable
.delay(10, TimeUnit.MILLISECONDS)
.delaySubscription(10, TimeUnit.MILLISECONDS)
.test()
o.assertEmpty()
o.assertNotComplete()
rxRule.advanceTimeBy(20, TimeUnit.MILLISECONDS)
o.assertResult(1, 2, 3)
}
class SomeClass {
private var value: String = "EMPTY"
fun setValue(value: String) {
this.value = value
}
fun getObservable(): Observable<String> {
return Observable.just(value)
}
fun getObservableFromCreate(): Observable<String> {
return Observable.create { emitter ->
emitter.onNext(value)
emitter.onComplete()
}
}
}
@Test
fun shouldReturnEmptyUsingJust() {
val instance = SomeClass()
val observable = instance.getObservable()
instance.setValue("VALUE !")
observable.subscribe(System.out::println)
}
@Test
fun shouldReturnValueUsingCreate() {
val instance = SomeClass()
val observable = instance.getObservableFromCreate()
instance.setValue("VALUE !")
observable.subscribe(System.out::println)
}
}
<file_sep>package com.vanniktech.rxriddles
import com.vanniktech.rxriddles.solutions.Riddle12Solution
import io.reactivex.Observable
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
/** Solution [Riddle12Solution] */
class Riddle1002ErrorHandlingTest {
private var subscribeCounter = AtomicInteger(0)
private val observable = Observable.create<Int> {
subscribeCounter.getAndIncrement()
it.onNext(1)
it.onError(RuntimeException())
it.onNext(3)
}
@Before
fun setup() {
subscribeCounter = AtomicInteger(0)
}
@Test
fun `items after on error will be skipped`() {
observable
.onErrorResumeNext(Observable.just(2))
.test()
.assertResult(1, 2)
}
@Test
fun `onComplete will be called and last item won't pass the stream`() {
observable
.onErrorResumeNext(Observable.just(2))
.doOnError {
System.out.println("doOnError: $it")
}
.subscribe(
{ System.out.println("onNext: $it") },
{ System.out.println("onError: $it") },
{ System.out.println("onComplete!") }
)
}
@Test
fun `retry not working with onErrorResumeNext`() {
observable
.onErrorResumeNext(Observable.just(2)) // This calls on complete and retry is not working!
.retry(2)
.subscribe(
{ System.out.println("onNext: $it") },
{ System.out.println("onError: $it") },
{ System.out.println("onComplete!") }
)
assertThat(subscribeCounter.get()).isEqualTo(1) // <<< 1 = no retries !
}
@Test
fun `onErrorResumeNext calling onComplete after retries`() {
observable
.retry(2) // without "times" it retries forever
.onErrorResumeNext(Observable.just(2)) // This calls on complete and retry is not working!
.subscribe(
{ System.out.println("onNext: $it") },
{ System.out.println("onError: $it") },
{ System.out.println("onComplete!") }
)
assertThat(subscribeCounter.get()).isEqualTo(3)
}
@Test
fun `doOnError no influence on retry`() {
observable
.doOnError { System.out.println("doOnError: $it") } // doesn't influence retry, can be earlier
.retry(2) // without "times" it retries forever
.subscribe(
{ System.out.println("onNext: $it") },
{ System.out.println("onError: $it") },
{ System.out.println("onComplete!") }
)
assertThat(subscribeCounter.get()).isEqualTo(3)
}
@Test
fun `handle simple error with switchmap`() {
Observable
.just(true, false, true)
.switchMap { returnedStatus ->
if (returnedStatus) {
Observable.just("OK")
} else {
Observable.just("ERROR !")
}
}
.doOnNext { System.out.println("doOnNext: $it") }
.test()
}
@Test
fun `handle simple error with flatmap same as switchmap`() {
Observable
.just(true, false, true)
.flatMap { returnedStatus ->
if (returnedStatus) {
Observable.just("OK")
} else {
Observable.just("ERROR !")
}
}
.doOnNext { System.out.println("doOnNext: $it") }
.test()
}
}
<file_sep>package com.vanniktech.rxriddles
import io.reactivex.Observable
import org.junit.Test
class Riddle1001FlatmapTest {
@Test
@Throws(Exception::class)
fun `Flat mapping observable of observables into one observable with all elements`() {
Observable
.just(Observable.just(1, 2), Observable.just(3, 4), Observable.just(5, 6))
.flatMap {
it
}
.doOnNext { it -> System.out.println("doOnNext: $it") }
.subscribe()
}
@Test
@Throws(Exception::class)
fun `Flat mapping as calling other function and merging into one observable with all elements`() {
val observable = Observable.just("a", "b")
Observable
.just(1, 2, 3)
// .doOnNext { it -> System.out.println("doOnNext: $it") }
.flatMap {
observable
}
.doOnNext { it -> System.out.println("doOnNext: $it") }
.subscribe()
}
@Test
@Throws(Exception::class)
fun `Flat mapping as calling other function and merging into one observable with all elements combined`() {
val otherItems = Observable.just("a", "b")
Observable
.just(1, 2, 3)
// .doOnNext { it -> System.out.println("doOnNext: $it") }
.flatMap { originalItem ->
otherItems.map { originalItem.toString() + it }
}
.doOnNext { it -> System.out.println("doOnNext: $it") }
.subscribe()
}
}<file_sep>package com.vanniktech.rxriddles
import io.reactivex.Observable
object Riddle18 {
/**
* Return an Observable that mirrors either the [first] or [second] Observable
* depending on whoever emits or terminates first.
*
* Use case: You have multiple sources and want to get the data from either one and then be
* consistent and not switch between multiple sources.
*/
fun solve(first: Observable<Int>, second: Observable<Int>): Observable<Int> =
// Observable.amb(listOf(first, second))
Observable.ambArray(first, second)
// given two or more source Observables, emit all of the items from only the first of these
// Observables to emit an item
}
<file_sep>package com.vanniktech.rxriddles
import io.reactivex.Observable
import java.util.concurrent.TimeUnit
object Riddle36 {
/**
* Return an Observable that only emits items from [source] if there isn't another
* emission before [milliseconds] has passed.
*
* Debounce: only emit an item from an Observable if a particular timespan has passed
* without it emitting another item
*
* Use case: You want the user-input to trigger a search request for the entered text
* but only when no changes have been made for a pre-determined time to avoid unnecessary requests.
*/
fun solve(source: Observable<String>, milliseconds: Long): Observable<String> = source
.debounce(milliseconds, TimeUnit.MILLISECONDS)
}
<file_sep>package com.vanniktech.rxriddles
import io.reactivex.Observable
object Riddle4 {
/**
* Implement a toggle mechanism. Initially we want to return false.
* Every time [source] emits, we want to negate the previous value.
*
* Use case: Some button that can toggle two states. For instance a switch between White & Dark theme.
*/
fun solve(source: Observable<Unit>): Observable<Boolean> {
// In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses.
// If the lambda is the only argument to that call, the parentheses can be omitted entirely.
return source.scan(false) { initialValue, _ -> !initialValue }
// return source.scan(false, BiFunction { t1, t2 -> !t1 })
}
}
|
b8c11b3fbe5e151d1ffddcdf31ba4bd1e9a271fd
|
[
"Kotlin"
] | 6
|
Kotlin
|
mbachorski/RxRiddles
|
62f1f4a18a9a8282d2cd7a8c4b4d44c22ce2aea9
|
102c0501848a74127f3c7b3d5ea773f75807753c
|
refs/heads/master
|
<repo_name>hwanderlust/js-beatles-loops-lab-bootcamp-prep-000<file_sep>/index.js
function theBeatlesPlay(musicians,instruments) {
var a = [];
var b = musicians.length
var i;
for (i = 0; i < b; i++) {
a.push(musicians[i] +" plays " + instruments[i]);
}
return a;
}
function johnLennonFacts(facts) {
var i=0;
while(i<facts.length) {
facts[i]=facts[i] + "!!!";
i++;
}
return facts
}
function iLoveTheBeatles(num) {
var foo = [];
do {foo.push("I love the Beatles!")
i++;
}
while (i<=15);
return foo
}
/*
var test = [];
test.push(`I love the Beatles!`);
console.log(test);
for (i=0;i<15;i++) {
test.push(`I love the Beatles! ${i}`);
}
console.log(test);
*/
var i=0;
var test2 = [];
do {test2.push(`I love the Beatles!`);
i++;
}
while (i<=7)
console.log(test2);
|
192de58bf711da40735da216bcf3cf69d2485f2c
|
[
"JavaScript"
] | 1
|
JavaScript
|
hwanderlust/js-beatles-loops-lab-bootcamp-prep-000
|
590a1f5c08404d9f68979d9bdcbb7f364cce8bef
|
9f18fb5c363218db839865d6a032c1739c5e8b59
|
refs/heads/main
|
<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import math
import xml.etree.ElementTree as ET
from Analysis import *
from matplotlib import pyplot as plt
class TrackV2:
def __init__(self, im, x, y, samplerate, name, ellipse=None):
# Raw data
self.imageobject = im
self.x = np.array(x)
self.y = np.array(y)
self.xypairs = np.array([np.array([xc, yc]) for xc, yc in zip(self.x, self.y)])
self.name = name
self.samplerate = float(samplerate)
self.timeaxis = np.array(range(len(x))) * self.samplerate
# Two dimensional statistics
self.twodspeed = np.sum(np.sqrt(np.diff(self.x) ** 2 + np.diff(self.y) ** 2)) / (
len(np.diff(self.y)) * self.samplerate)
self.twodposition = np.array([np.sqrt(np.square(p[0]) + np.square(p[1])) for p in self.xypairs])
self.msd = self.msd_calc(self.xypairs)
self.msd_alpha, _ = slope_and_mse(np.log10(np.arange(1, 20) * 3), np.log10(self.msd[1:20]))
# Ellipse and 3D stats
self._ellipse = ellipse
self.xy_ellipse = None
self.xellipse = None
self.yellipse = None
self.z = None
self.unwrapped = None
# Velocities and other data
# Initialize it always as an empty list or dicts
# Load method SHOULD check if data existed previously
self.bruteforce_velo = []
self.bruteforce_phi = []
self.muggeo_velo = []
self.muggeo_phi = []
self.muggeo_params = {}
self.manual_phi = []
self.manual_velo = []
self.disp_velo = []
if self._ellipse is not None:
self.update()
@property
def ellipse(self):
return self._ellipse
# This allows me to update the measurements ONLY when the ellipse value is assigned to anything except None
@ellipse.setter
def ellipse(self, new_value):
self._ellipse = new_value
if new_value:
self.update()
else:
return
@classmethod
def generator_xml(cls, xmlfile, image):
classlist = []
root = ET.parse(xmlfile).getroot()
srate = root.attrib['frameInterval']
counter = 0
for children in root:
tempx = []
tempy = []
for grandchildren in children:
tempx.append(float(grandchildren.attrib['x'])) # list of x coords
tempy.append(float(grandchildren.attrib['y'])) # list of y coords
classlist.append(cls(image, tempx, tempy, srate, str(xmlfile).split('/')[-1][:-4] + f"_{counter}"))
counter += 1
return classlist
def update(self):
# Called if ellipse attr is set or if loaded with a non None ellipse attr
# Calculates all 3D stuff plus displacement velocity which is fast to do
self.xy_ellipse = self.closest_ellipse_points()
self.xellipse, self.yellipse = np.array(list(zip(*self.xy_ellipse)))
self.z = self.calculatez()
self.unwrapped = self.unwrapper()
self.disp_velo = displacement(self)
def closest_ellipse_points(self):
# Ellipse center, semi axes and angle to x axis
center = np.array([self._ellipse['x0'], self._ellipse['y0']])
smmajor = self._ellipse['major'] / 2
smminor = self._ellipse['minor'] / 2
ang = np.deg2rad(self._ellipse['angle'])
# Translate and rotate ellipse to be centered at (0,0) with major axis horizontal
translated = [x - center for x in self.xypairs]
rotated_and_translated = [self.rot2d(-1 * ang).dot(t) for t in translated]
# Solve closest point problem
ellipsepoints = [self.solve(smmajor, smminor, point) for point in rotated_and_translated]
# Undo rotation and translation
return np.array([self.rot2d(ang).dot(p) + center for p in ellipsepoints])
def unwrapper(self):
# center referencial
x = self.xellipse - self._ellipse['x0']
y = self.yellipse - self._ellipse['y0']
z = self.z - 0
angles_to_x = np.arctan2(y, x)
for idx, val in enumerate(angles_to_x):
if 0 <= val <= np.pi:
continue
else:
angles_to_x[idx] = np.pi + (np.pi + val)
rawperimeter = angles_to_x * self._ellipse['major'] / 2
turns = 0
perimeter = []
# Wrap turns
for idx, val in enumerate(angles_to_x):
if idx == 0:
perimeter.append(val * self._ellipse['major'] / 2)
else:
prevval = angles_to_x[idx - 1]
if 0 < val < np.pi / 2 and 1.5 * np.pi < prevval < 2 * np.pi:
turns += 2 * np.pi
perimeter.append(val * (self._ellipse['major'] / 2) + turns * (self._ellipse['major'] / 2))
elif 1.5 * np.pi < val < 2 * np.pi and 0 < prevval < np.pi / 2:
turns -= 2 * np.pi
perimeter.append(val * (self._ellipse['major'] / 2) + turns * (self._ellipse['major'] / 2))
else:
perimeter.append(val * (self._ellipse['major'] / 2) + turns * (self._ellipse['major'] / 2))
perimeter = np.array(perimeter)
rawperimeter = np.array(rawperimeter)
return perimeter
def calculatez(self):
major = self._ellipse['major']
ang = np.deg2rad(self._ellipse['angle'])
zcoord = []
for idx, pair in enumerate(self.xy_ellipse):
distance = np.linalg.norm(np.array(pair)-np.array([self._ellipse['x0'],self._ellipse['y0']]))
sqrarg = (major/2) ** 2 - distance ** 2
temporaryZ = np.sqrt(sqrarg)
# Be careful with sign of the Z coordinate!
# In a referential centered at the ellipse with major axis colinear to xaxis
pair_c = pair - np.array([self._ellipse['x0'],self._ellipse['y0']])
pair_c_r = self.rot2d(-1 * ang).dot(pair_c)
Zsign = np.sign(pair_c_r[1])
zcoord.append(temporaryZ * Zsign)
return np.array(zcoord)
@staticmethod
def msd_calc(r):
shifts = np.arange(len(r))
msds = np.zeros(shifts.size)
for i, shift in enumerate(shifts):
diffs = r[:-shift if shift else None] - r[shift:]
sqdist = np.square(diffs).sum(axis=1)
msds[i] = sqdist.mean()
return msds
@staticmethod
def solve(semi_major, semi_minor, p):
"""
These cryptic (yet genius) lines of code were taken verbatim from
https://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/
This implements a method to calculate the ellipse point that is closer to a given point p
It works by using the evolute of the ellipse (ex, ey the center of curvature) to locally approximate
the ellipse to a circle! Then we just iterate the method 3-4 times to yield the final point.
The current implementation NEEDS an ellipse centered at (0,0) with horizontal major axis.
"""
# center
px = abs(p[0])
py = abs(p[1])
# constant
t = math.pi / 4
# axis, a is horizontal
a = semi_major
b = semi_minor
# 3 iterations
for x in range(0, 3):
x = a * math.cos(t)
y = b * math.sin(t)
ex = (a * a - b * b) * math.cos(t) ** 3 / a
ey = (b * b - a * a) * math.sin(t) ** 3 / b
rx = x - ex
ry = y - ey
qx = px - ex
qy = py - ey
r = math.hypot(ry, rx)
q = math.hypot(qy, qx)
delta_c = r * math.asin((rx * qy - ry * qx) / (r * q))
delta_t = delta_c / math.sqrt(a * a + b * b - x * x - y * y)
t += delta_t
t = min(math.pi / 2, max(0, t))
return math.copysign(x, p[0]), math.copysign(y, p[1])
@staticmethod
def rot2d(angle):
s, c = np.sin(angle), np.cos(angle)
return np.array([[c, -s], [s, c]])
<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import tkinter as tk
import numpy as np
from scipy.stats import linregress
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
# Class that inherits root window class from tk
class ManualSectioning(tk.Toplevel):
def __init__(self, tracks):
super().__init__() # init of tk.Tk()
# End product, velocity of track sections
self.section_velocity = []
# Configure root window
self.wm_title("Manual sectioning")
self.title("Manual sectioning")
self.geometry('600x600')
# Store clicks
self.clicks = []
# Store current plotted track
self.current_track = 0
# Store all tracks
self.alltracks = tracks
# Store canvas for updating
self.canvas = None
# final dictionary for all clicks
self.clickdata = {}
# Window has two frames
self.init_plot()
self.init_buttons()
def init_plot(self):
frame_plot = tk.Frame(self)
frame_plot.pack(fill='both', expand=True)
fig = Figure()
# INSERT FIRST GRAPH
canvas = FigureCanvasTkAgg(fig, master=frame_plot)
self.canvas = canvas
SR = self.alltracks[self.current_track].samplerate
y = self.alltracks[self.current_track].unwrapped
x = np.array(range(len(y))) * SR
smoothedy = self.smoothing(y, int((len(y) * 10) // 100))
smoothedx = np.array(range(len(smoothedy))) * SR + 0.05 * x[-1]
ax = fig.add_subplot()
ax.plot(x, y, color='r')
ax.plot(smoothedx, smoothedy, color='k')
ax.set_xlabel("Time (sec)")
ax.set_ylabel("Position (mm)")
ax.set_title(self.alltracks[self.current_track].name)
canvas.draw()
canvas.get_tk_widget().pack(fill='both', expand=True)
# INSERT MATPLOTLIB TOOLBAR
toolbar = NavigationToolbar2Tk(canvas, frame_plot)
toolbar.update()
# INSERT CLICKING EVENT HANDLER
canvas.mpl_connect("button_press_event", self.clickGraph)
def init_buttons(self):
frame_buttons = tk.Frame(self)
frame_buttons.pack(fill='x')
ALLDONE_button = tk.Button(master=frame_buttons, text="Next track", command=self.nexttrack)
ALLDONE_button.pack(side='left', fill='x', expand=True)
UNDO_button = tk.Button(master=frame_buttons, text="Undo", command=self.undo)
UNDO_button.pack(side='left', fill='x', expand=True)
QUIT_button = tk.Button(master=frame_buttons, text="QUIT", command=self.quit)
QUIT_button.pack(side='left', fill='x', expand=True)
def clickGraph(self, event):
if event.inaxes is not None:
ax = self.canvas.figure.axes[0]
ax.axvline(x=event.xdata, color='r')
self.canvas.draw()
self.clicks.append(event.xdata)
else:
print("OUTSIDE")
def nexttrack(self):
# Store previous data:
self.clickdata[self.alltracks[self.current_track].name] = self.clicks
# reset clicks
self.clicks = []
# Delete graph
ax = self.canvas.figure.axes[0]
ax.lines = []
if len(self.alltracks) == self.current_track + 1:
self.finishup()
else:
# Next graph
self.current_track += 1
SR = self.alltracks[self.current_track].samplerate
y = self.alltracks[self.current_track].unwrapped
x = np.array(range(len(y))) * SR
smoothedy = self.smoothing(y, int((len(y) * 10) // 100))
smoothedx = np.array(range(len(smoothedy))) * SR + 0.05 * x[-1]
ax.plot(x, y, color='r')
ax.plot(smoothedx, smoothedy, color='k')
ax.set_title(self.alltracks[self.current_track].name)
self.canvas.draw()
def undo(self):
if not self.clicks:
print("No lines")
else:
ax = self.canvas.figure.axes[0]
ax.lines.pop(-1)
self.canvas.draw()
self.clicks.pop(-1)
def finishup(self):
# Everything will be done in the bg
self.quit()
self.destroy()
for idx, tr in enumerate(self.alltracks):
delimiter = self.findclosest_idx(self.clickdata[tr.name], tr)
self.alltracks[idx].manual_sections = delimiter
SR = tr.samplerate
rawy = tr.unwrapped
rawx = np.array(range(len(rawy))) * SR
y = self.smoothing(rawy, int((len(rawy) * 10) // 100))
x = np.array(range(len(y))) * SR + 0.05 * rawx[-1]
if not delimiter.size:
m, b = self.slope(x, y)
self.alltracks[idx].manual_velo.append(np.abs(m) * 1000)
self.section_velocity.append(m * 1000)
# plt.plot(x, x * m + b)
else:
m, b = self.slope(x[0:delimiter[0]], y[0:delimiter[0]])
# plt.plot(x[0:delimiter[0]], x[0:delimiter[0]] * m + b)
self.section_velocity.append(m * 1000)
self.alltracks[idx].manual_velo.append(np.abs(m) * 1000)
for idx2, d in enumerate(delimiter):
if d == delimiter[-1]:
m, b = self.slope(x[d:-1], y[d:-1])
# plt.plot(x[d:-1], x[d:-1] * m + b)
self.section_velocity.append(m * 1000)
self.alltracks[idx].manual_velo.append(np.abs(m) * 1000)
else:
nextd = delimiter[idx2 + 1]
m, b = self.slope(x[d:nextd], y[d:nextd])
self.section_velocity.append(m * 1000)
self.alltracks[idx].manual_velo.append(np.abs(m) * 1000)
# plt.plot(x[d:next], x[d:next] * m + b)
# plt.show()
# save histogram
self.section_velocity = np.abs(self.section_velocity)
@staticmethod
def findclosest_idx(clickarray, trackobject):
# Click data is not real data; transform click data into indices
if not clickarray:
return np.array([])
indexes = []
SR = trackobject.samplerate
y = trackobject.unwrapped
x = np.array(range(len(y))) * SR
for value in clickarray:
idx = (np.abs(x - value)).argmin()
indexes.append(idx)
return np.sort(indexes)
@staticmethod
def slope(x, y):
s, b, r_value, p_value, std_err = linregress(x, y)
return s, b
@staticmethod
def smoothing(unsmoothed, windowsize):
smoothed = np.convolve(unsmoothed, np.ones(windowsize) / windowsize, mode='valid')
return smoothed
if __name__ == '__main__':
app = ManualSectioning()
app.mainloop()
<file_sep>import os
from functools import cache, partial
from tkinter import Tk
from tkinter import filedialog
import pandas as pd
from ipywidgets import Dropdown, interactive, fixed, Accordion, IntSlider, SelectMultiple, BoundedIntText, Button, Output, IntRangeSlider
from IPython.display import display
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec
import seaborn as sns
from scipy.optimize import minimize
from tracks import *
def gaussian(v, mu, sigma):
return (1/(sigma*np.sqrt(2*np.pi))) * np.exp(-0.5*((v-mu)/sigma)**2)
def twogaussian(v, p1, mu1, sig1, mu2, sig2):
return gaussian(v, mu1, sig1)*p1 + gaussian(v, mu2, sig2)*(1-p1)
def lognormal(v, mu, sigma):
return (1/(v*sigma*np.sqrt(2*np.pi))) * np.exp(-(np.log(v)-mu)**2/(2*sigma**2))
def twolognormal(v, p1, mu1, sig1, mu2, sig2):
return lognormal(v, mu1, sig1)*p1 + lognormal(v, mu2, sig2)*(1-p1)
def residues(x, *args):
x_data = args[0]
y_data = args[1]
func = args[2]
return np.sum((y_data - func(x_data, *x))**2)
def build_bin_centers(bins):
centerbins = []
for idx, bini in enumerate(bins):
if bini == bins[-1]:
continue
else:
centerbins.append((bins[idx + 1] + bins[idx]) / 2)
return np.array(centerbins)
def FileLoader(folder, root):
display(f"Loading {folder}...")
folder = os.path.join(root, folder)
filedump = os.path.join(folder, "DataDump.npy")
Tracks = readfile(filedump)
display(f"Loaded a total of {len(Tracks)} tracks")
return Tracks
@cache
def readfile(f):
old_objs = np.load(f, allow_pickle=True)
newobjs = []
for idx, t in enumerate(old_objs):
newobjs.append(TrackV2(t.imageobject, t.x, t.y, t.samplerate, t.name, t.ellipse))
if hasattr(t, 'bruteforce_velo'):
newobjs[-1].bruteforce_velo = t.bruteforce_velo
newobjs[-1].bruteforce_phi = t.bruteforce_phi
if hasattr(t, 'muggeo_velo'):
newobjs[-1].muggeo_velo = t.muggeo_velo
newobjs[-1].muggeo_phi = t.muggeo_phi
newobjs[-1].muggeo_params = t.muggeo_params
if hasattr(t, 'manual_velo'):
newobjs[-1].manual_velo = t.manual_velo
newobjs[-1].manual_phi = t.manual_phi
return np.array(newobjs)
def loadall(rootdirectory, output, ev):
with output:
for f in os.listdir(rootdirectory):
FileLoader(f, rootdirectory)
def showStats(tr):
angles = np.rad2deg(np.arccos([i.ellipse['minor']/i.ellipse['major'] for i in tr]))
plt.figure()
plt.hist(angles, density=False)
plt.xlabel("Angle in degrees")
plt.ylabel("Frequency")
plt.xlim((0,90))
plt.show()
return 0
def Update_Graphs(angle_threshold, major_threshold, all_tracks):
plt.close('all')
all_angles = np.rad2deg(np.arccos([i.ellipse['minor'] / i.ellipse['major'] for i in all_tracks]))
all_diameter = np.array([i.ellipse['major']*1000 for i in all_tracks])
filtered_tracks = []
for idx,tr in enumerate(all_tracks):
if (all_angles[idx]<angle_threshold[1] and all_angles[idx]>angle_threshold[0]) and (all_diameter[idx]<major_threshold[1] and all_diameter[idx]>major_threshold[0]):
filtered_tracks.append(tr)
filtered_tracks = np.array(filtered_tracks)
print(
f"n = {len(filtered_tracks)} (out of {len(all_tracks)} ({(len(filtered_tracks) / len(all_tracks)) * 100:.1f}%))\n\n")
angles = np.rad2deg(np.arccos([i.ellipse['minor'] / i.ellipse['major'] for i in filtered_tracks]))
diameter = np.array([i.ellipse['major']*1000 for i in filtered_tracks])
displacement_velo = [np.average(tr.disp_velo) for tr in filtered_tracks]
brute_velo = [tr.bruteforce_velo for tr in filtered_tracks]
brute_sections = [len(tr.bruteforce_phi) for tr in filtered_tracks]
mug_velo = [tr.muggeo_velo for tr in filtered_tracks]
mug_sections = [len(tr.muggeo_phi) for tr in filtered_tracks]
print(f"Displacement: {np.nanmean(displacement_velo):.2f} +- {np.nanstd(displacement_velo):.2f} nm/s \n")
print(f"Brute force sectioning: {np.average(np.hstack(brute_velo)):.2f} +- {np.std(np.hstack(brute_velo)):.2f} nm/s")
print(f"\t Average number of sections of {np.average(brute_sections):.2f} \n")
print(f"Muggeo et al sectioning: {np.nanmean(np.hstack(mug_velo)):.2f} +- {np.nanstd(np.hstack(mug_velo)):.2f} nm/s")
print(f"\t Average number of sections of {np.nanmean(mug_sections):.2f} \n")
##############################################################################################################################################
fig = plt.figure("Velocity Distributions", figsize=(10,5))
gs = GridSpec(1,2, figure=fig, width_ratios=(1,1))
ax1 = fig.add_subplot(gs[0,0])
ax1.hist(displacement_velo, label="Displacement", alpha=0.5, density=True, bins='auto')
pdf, bins, _ = ax1.hist(np.hstack(brute_velo), label="Brute force", alpha=0.5, density=True, bins='auto')
ax1.hist(np.hstack(mug_velo), label="Muggeo et al", alpha=0.5, density=True, bins='auto')
ax1.set_ylabel("Probability Density Function")
ax1.set_xlabel("Velocity (nm/s)")
ax1.legend()
ax2 = fig.add_subplot(gs[0,1])
ax2.hist(displacement_velo, label="Displacement", alpha=0.5, density=True, bins='auto')
ax2.hist(np.hstack(brute_velo), label="Brute force", alpha=0.5, density=True, bins='auto')
ax2.hist(np.hstack(mug_velo), label="Muggeo et al", alpha=0.5, density=True, bins='auto')
ax2.set_ylabel("Probability Density Function")
ax2.set_xlabel("Velocity (nm/s)")
ax2.set_xscale('log')
ax2.legend()
plt.tight_layout()
plt.show()
##############################################################################################################################################
# FITTING ON BRUTE_FORCE
cbins = build_bin_centers(bins)
# ONE GAUSSIAN FITTING
one_g = minimize(fun=residues, x0=[10,4], args=(cbins, pdf, gaussian), bounds=((0, np.inf), (0, np.inf)))
# TWO GAUSSIAN FITTING
two_g = minimize(fun=residues, x0=[0.5,10,4,2,2], args=(cbins, pdf, twogaussian), bounds=((0, 1),(0, np.inf),(0, np.inf),(0, np.inf),(0, np.inf)))
# ONE LOG-NORMAL FITTING
one_lg = minimize(fun=residues, x0=[1,0.5], args=(cbins, pdf, lognormal), bounds=((-np.inf, np.inf), (1e-5, np.inf)))
# TWO LOG-NORMAL FITTING
two_lg = minimize(fun=residues, x0=[0.5,1,0.5,2,0.5], args=(cbins, pdf, twolognormal), bounds=((0, 1),(-np.inf, np.inf),(1e-5, np.inf),(-np.inf, np.inf),(1e-5, np.inf)))
fig = plt.figure("Fitted Velocity Distributions", figsize=(15,10))
gs = GridSpec(2,2, figure=fig, width_ratios=(1,1), height_ratios=(1,0.2))
fig.suptitle(f"Angle={angle_threshold}º, Diameter={major_threshold} nm ")
ax1 = fig.add_subplot(gs[0,0])
ax1.hist(np.hstack(brute_velo), label="Brute force", alpha=0.1, density=True, bins='auto', color='k')
ax1.plot(cbins, pdf, '--k')
ax1.plot(cbins, gaussian(cbins,*one_g.x), label='Unimodal Normal')
ax1.plot(cbins, twogaussian(cbins, *two_g.x), label='Bimodal Normal')
ax1.set_ylabel("Probability Density Function")
ax1.set_xlabel("Velocity (nm/s)")
ax1.set_title("Gaussians")
ax1.legend()
ax2 = fig.add_subplot(gs[0,1])
ax2.hist(np.hstack(brute_velo), label="Brute force", alpha=0.1, density=True, bins='auto', color='k')
ax2.plot(cbins, pdf, '--k')
ax2.plot(cbins, lognormal(cbins,*one_lg.x), label='Unimodal LogNormal')
ax2.plot(cbins, twolognormal(cbins, *two_lg.x), label='Bimodal LogNormal')
ax2.set_ylabel("Probability Density Function")
ax2.set_xlabel("Velocity (nm/s)")
ax2.set_title("Log-Normals")
ax2.legend()
ax3 = fig.add_subplot(gs[1,0])
onegstr = f"One Gaussian: $\mu$={one_g.x[0]:.2f}, $\sigma=${one_g.x[1]:.2f}, SSE={residues(one_g.x,cbins,pdf,gaussian):.2e}"
twogstr = f"Two Gaussian: {100*two_g.x[0]:.2f}% $\mu_1$={two_g.x[1]:.2f}, $\sigma_1$={two_g.x[2]:.2f} \n {100-100*two_g.x[0]:.2f}% $\mu_2$={two_g.x[3]:.2f}, $\sigma_2$={two_g.x[4]:.2f} \n SSE={residues(two_g.x,cbins,pdf,twogaussian):.2e}"
ax3.text(0.5,0.7, onegstr, size=12, ha="center", va="center", bbox=dict(boxstyle="round",ec='k',fc='tab:grey'), wrap=False)
ax3.text(0.5,0.3, twogstr, size=12, ha="center", va="center", bbox=dict(boxstyle="round",ec='k',fc='tab:grey'), wrap=False)
ax3.axis('off')
ax4=fig.add_subplot(gs[1,1])
onelgstr = f"One LogNormal: $\mu$={one_lg.x[0]:.2f}, $\sigma=${one_lg.x[1]:.2f}, SSE={residues(one_lg.x,cbins,pdf,lognormal):.2e}"
twolgstr = f"Two LogNormal: {100*two_lg.x[0]:.2f}% $\mu_1$={two_lg.x[1]:.2f}, $\sigma_1$={two_lg.x[2]:.2f} \n {100-100*two_lg.x[0]:.2f}% $\mu_2$={two_lg.x[3]:.2f}, $\sigma_2$={two_lg.x[4]:.2f} \n SSE={residues(two_lg.x,cbins,pdf,twolognormal):.2e}"
ax4.text(0.5,0.7, onelgstr, size=12, ha="center", va="center", bbox=dict(boxstyle="round",ec='k',fc='tab:grey'), wrap=False)
ax4.text(0.5,0.3, twolgstr, size=12, ha="center", va="center", bbox=dict(boxstyle="round",ec='k',fc='tab:grey'), wrap=False)
ax4.axis('off')
plt.tight_layout()
plt.show()
print(f"One Gaussian: mu={one_g.x[0]:.2f}, sigma={one_g.x[1]:.2f}, SSE={residues(one_g.x,cbins,pdf,gaussian):.2e}")
print(f"Two Gaussian: {100*two_g.x[0]:.2f}% mu={two_g.x[1]:.2f}, sigma={two_g.x[2]:.2f} \n",
f" {100-100*two_g.x[0]:.2f}% mu={two_g.x[3]:.2f}, sigma={two_g.x[4]:.2f} \n",
f" SSE={residues(two_g.x,cbins,pdf,twogaussian):.2e}")
print(f"One LogNormal: mu={one_lg.x[0]:.2f}, sigma={one_lg.x[1]:.2f}, SSE={residues(one_lg.x,cbins,pdf,lognormal):.2e}")
print(f"Two LogNormal: {100*two_lg.x[0]:.2f}% mu={two_lg.x[1]:.2f}, sigma={two_lg.x[2]:.2f} \n",
f" {100-100*two_lg.x[0]:.2f}% mu={two_lg.x[3]:.2f}, sigma={two_lg.x[4]:.2f} \n",
f" SSE={residues(two_lg.x,cbins,pdf,twolognormal):.2e}")
##############################################################################################################################################
fig2 = plt.figure("Effect of angle", figsize=(10,10))
gs = GridSpec(2,2, figure=fig2, width_ratios=(1,1), height_ratios=(1,1))
ax1 = fig2.add_subplot(gs[0,0])
ax1.scatter(x=angles, y=displacement_velo, label="Displacement")
ax1.scatter(x=angles, y=[np.average(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax1.scatter(x=angles, y=[np.average(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax1.set_ylabel("Average Velocity (nm/s)")
ax1.set_xlabel("Angle (deg)")
ax1.legend()
ax2 = fig2.add_subplot(gs[0,1])
ax2.scatter(x=angles, y=[np.std(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax2.scatter(x=angles, y=[np.std(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax2.set_ylabel("Standard deviation (nm/s)")
ax2.set_xlabel("Angle (deg)")
ax2.legend()
ax3 = fig2.add_subplot(gs[1,0])
ax3.scatter(x=angles, y=brute_sections, label="Brute force", c='k', marker='*')
ax3.scatter(x=angles, y=mug_sections, label="Muggeo et al", c='r', marker='+')
ax3.set_ylabel("Number of sections")
ax3.set_xlabel("Angle (deg)")
ax3.legend()
plt.tight_layout()
plt.show()
##############################################################################################################################################
##############################################################################################################################################
fig3 = plt.figure("Effect of diameter", figsize=(10,10))
gs = GridSpec(2,2, figure=fig3, width_ratios=(1,1), height_ratios=(1,1))
ax1 = fig3.add_subplot(gs[0,0])
ax1.scatter(x=diameter, y=displacement_velo, label="Displacement")
ax1.scatter(x=diameter, y=[np.average(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax1.scatter(x=diameter, y=[np.average(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax1.set_ylabel("Average Velocity (nm/s)")
ax1.set_xlabel("Diameter (nm)")
ax1.legend()
ax2 = fig3.add_subplot(gs[0,1])
ax2.scatter(x=diameter, y=[np.std(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax2.scatter(x=diameter, y=[np.std(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax2.set_ylabel("Standard deviation (nm/s)")
ax2.set_xlabel("Diameter (nm)")
ax2.legend()
ax3 = fig3.add_subplot(gs[1,0])
ax3.scatter(x=diameter, y=brute_sections, label="Brute force", c='k', marker='*')
ax3.scatter(x=diameter, y=mug_sections, label="Muggeo et al", c='r', marker='+')
ax3.set_ylabel("Number of sections")
ax3.set_xlabel("Diameter (nm)")
ax3.legend()
plt.tight_layout()
plt.show()
##############################################################################################################################################
##############################################################################################################################################
fig4 = plt.figure("Effect of track length", figsize=(10,10))
gs = GridSpec(2,2, figure=fig4, width_ratios=(1,1), height_ratios=(1,1))
ax1 = fig4.add_subplot(gs[0,0])
ax1.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=displacement_velo, label="Displacement")
ax1.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=[np.average(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax1.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=[np.average(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax1.set_xlabel("Length of track (#)")
ax1.set_ylabel("Velocity (nm/s)")
ax1.legend()
ax2 = fig4.add_subplot(gs[0,1])
ax2.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=[np.std(i) for i in brute_velo], label="Brute force", c='k', marker='*')
ax2.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=[np.std(i) for i in mug_velo], label="Muggeo et al", c='r', marker='+')
ax2.set_xlabel("Length of track (#)")
ax2.set_ylabel("Standard deviation (nm/s)")
ax2.legend()
ax3 = fig4.add_subplot(gs[1,0])
ax3.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=brute_sections, label="Brute force", c='k', marker='*')
ax3.scatter(x=[len(tr.unwrapped) for tr in filtered_tracks], y=mug_sections, label="Muggeo et al", c='r', marker='+')
ax3.set_xlabel("Length of track (#)")
ax3.set_ylabel("Number of sections")
ax3.legend()
plt.tight_layout()
plt.show()
##############################################################################################################################################
def ViolinComparison(conditions, root, anglethresh):
if len(conditions) == 0:
print("Select file(s) to load")
return
print("Please wait...")
anglethresh = int(anglethresh)
final_brute = pd.DataFrame({'Condition' : [], 'Velocity (nm/s)':[], 'Protein':[]})
final_mug = pd.DataFrame({'Condition' : [], 'Velocity (nm/s)':[], 'Protein':[]})
final_disp = pd.DataFrame({'Condition' : [], 'Velocity (nm/s)':[], 'Protein':[]})
analyzed = []
# Iterate through conditions
for c in conditions:
if c in analyzed:
print(f"{c} already analyzed")
continue
# Initialize velocity dicts
databrute = {}
datamug = {}
datadisp = {}
# Load divIB AND ftsW
# To facilitate and make code more readable when you load a condition
# make it so ftsW is always first
if 'ftsW' in c:
hue = c.replace('ftsW', 'divIB')
elif 'divIB' in c:
c, hue = c.replace('divIB', 'ftsW'), c
conditionname = c.replace('_ftsW','')
# readfile function is lru cached
print(f"Loading {c}")
ftswc = readfile(os.path.join(os.path.join(root,c), "DataDump.npy"))
print(f"Loading {hue}")
divibc = readfile(os.path.join(os.path.join(root,hue), "DataDump.npy"))
analyzed.append(c)
analyzed.append(hue)
print(f"Filtering tracks...")
anglearr = np.rad2deg(np.arccos([i.ellipse['minor']/i.ellipse['major'] for i in ftswc]))
filtered_ftsw = ftswc[anglearr <= anglethresh]
anglearr = np.rad2deg(np.arccos([i.ellipse['minor']/i.ellipse['major'] for i in divibc]))
filtered_divib = divibc[anglearr <= anglethresh]
disp_ftsw = [np.average(tr.disp_velo) for tr in filtered_ftsw]
brute_ftsw = [tr.bruteforce_velo for tr in filtered_ftsw]
mug_ftsw = [tr.muggeo_velo for tr in filtered_ftsw]
disp_divib = [np.average(tr.disp_velo) for tr in filtered_divib]
brute_divib = [tr.bruteforce_velo for tr in filtered_divib]
mug_divib = [tr.muggeo_velo for tr in filtered_divib]
print(f"Saving velocities...")
databrute['Velocity (nm/s)'] = np.hstack([np.hstack(brute_ftsw), np.hstack(brute_divib)])
databrute['Condition'] = [conditionname] * len(databrute['Velocity (nm/s)'])
databrute['Protein'] = ['FtsW'] * len(np.hstack(brute_ftsw)) + ['DivIB'] * len(np.hstack(brute_divib))
final_brute = pd.concat([final_brute, pd.DataFrame(data=databrute)])
datamug['Velocity (nm/s)'] = np.hstack([np.hstack(mug_ftsw), np.hstack(mug_divib)])
datamug['Condition'] = [conditionname] * len(datamug['Velocity (nm/s)'])
datamug['Protein'] = ['FtsW'] * len(np.hstack(mug_ftsw)) + ['DivIB'] * len(np.hstack(mug_divib))
final_mug = pd.concat([final_mug, pd.DataFrame(datamug)])
datadisp['Velocity (nm/s)'] = np.hstack([np.hstack(disp_ftsw), np.hstack(disp_divib)])
datadisp['Condition'] = [conditionname] * len(datadisp['Velocity (nm/s)'])
datadisp['Protein'] = ['FtsW'] * len(np.hstack(disp_ftsw)) + ['DivIB'] * len(np.hstack(disp_divib))
final_disp = pd.concat([final_disp, pd.DataFrame(datadisp)])
print("Done!")
final_all = pd.concat([final_brute, final_mug, final_disp], keys=["Brute Force", "Muggeo et al", "Displacement"])
final_all['Method'] = final_all.index.get_level_values(0)
g = sns.catplot(x="Condition", y="Velocity (nm/s)", hue="Protein", col='Method', data=final_all, kind="violin", split=False, cut=0, scale='count', scale_hue='False', inner='quartile', palette='Set2', col_wrap=2, sharex=False, aspect=1.5)
plt.ylim((0,30))
plt.show()
return final_all<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import tkinter as tk
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
from matplotlib import patches
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from PIL import Image, ImageEnhance
from tracks import *
# Class inheriting toplevel windows from tk
class DrawingEllipses(tk.Toplevel):
def __init__(self, rawdata):
super().__init__() # toplevel init
# Configuring window
self.wm_title("Drawing Ellipses")
self.title("Drawing Ellipses")
self.geometry("700x700")
self.pxmax = tk.IntVar()
self.pxmin = tk.IntVar()
self.msd_alpha = tk.DoubleVar()
self.msd_text = tk.StringVar()
# To store clicks
self.x_clicks = []
self.y_clicks = []
# Store current canvas to update the image
self.canvas = None
# Store raw data, xml file path and image objects
self.rawdata = rawdata
# To store ellipses
self.x0 = None
self.y0 = None
self.minor = None
self.major = None
self.angle = None
self.elidict = [None] * len(rawdata)
# Store currently plotted TRACK
self.current_track = 0
# Final result
self.track_classes = None
self.rejects = None
# Window has two frames
self.init_sliders()
self.init_label()
self.init_plot()
self.init_buttons()
tk.messagebox.showinfo(title="IMPORTANT", message="ALWAYS DRAW THE MAJOR AXIS FIRST")
def init_sliders(self):
frame_slider = tk.Frame(self)
frame_slider.pack(side=tk.RIGHT)
max_slider = tk.Scale(master=frame_slider, command=self.update_max, from_=2 ** 8, to=0, variable=self.pxmax,
orient=tk.VERTICAL, label="Max", length=150)
max_slider.pack(side=tk.RIGHT)
min_slider = tk.Scale(master=frame_slider, command=self.update_min, from_=0, to=2 ** 8, variable=self.pxmin,
orient=tk.VERTICAL, label="Min", length=150)
min_slider.pack(side=tk.LEFT)
def init_label(self):
frame_label = tk.Frame(self)
frame_label.pack(side=tk.BOTTOM)
msd_label = tk.Label(master=frame_label, textvariable=self.msd_text, pady=10)
msd_label.pack(side=tk.BOTTOM)
def update_min(self, _):
self.redraw_graph(pxmax=self.pxmax.get(), pxmin=self.pxmin.get())
def update_max(self, _):
self.redraw_graph(pxmax=self.pxmax.get(), pxmin=self.pxmin.get())
def init_plot(self):
frame_plot = tk.Frame(self)
frame_plot.pack(fill='both', expand=True)
fig = Figure()
# FIRST GRAPH
self.canvas = FigureCanvasTkAgg(fig, master=frame_plot)
image = self.rawdata[self.current_track].imageobject
image = np.asarray(image)
normalized = (image.astype(np.uint16) - image.min()) * 255.0 / (image.max() - image.min())
image = normalized.astype(np.uint8)
x = np.array(self.rawdata[self.current_track].x) / 0.08 # TODO UM TO NM
y = np.array(self.rawdata[self.current_track].y) / 0.08 # TODO UM TO NM
ax = fig.add_subplot()
ax.imshow(image, cmap='gray')
# ax.plot(x, y, color='r')
ax.set_xlabel("x coordinates (px)")
ax.set_ylabel("y coordinates (px)")
ax.set_xlim((np.average(x) - 30, np.average(x) + 30))
ax.set_ylim((np.average(y) - 30, np.average(y) + 30))
cumulative_disp = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(cumulative_disp.min(), cumulative_disp.max())
lc = LineCollection(segments, cmap='rainbow', norm=norm)
lc.set_array(cumulative_disp)
lc.set_linewidth(2)
line = ax.add_collection(lc)
self.canvas.draw()
self.canvas.get_tk_widget().pack(fill='both', expand=True)
# Toolbar
toolbar = NavigationToolbar2Tk(self.canvas, frame_plot)
toolbar.update()
# Event handler
self.canvas.mpl_connect("button_press_event", self.clickGraph)
# Connect msd calculations to variables
self.msd_alpha.set(self.rawdata[self.current_track].msd_alpha)
self.msd_text.set(f"MSD alpha is {self.msd_alpha.get():2f} \n A value bigger than 1 corresponds to "
f"directional motion \n Smaller OR equal to 1 corresponds to diffusive motion")
def clickGraph(self, event):
if event.inaxes is not None:
print(event.xdata, event.ydata)
ax = self.canvas.figure.axes[0]
xclick = event.xdata
yclick = event.ydata
self.x_clicks.append(xclick)
self.y_clicks.append(yclick)
# First two points are major axis
if len(self.x_clicks) == 1:
ax.scatter(self.x_clicks[0], self.y_clicks[0], facecolors='none', edgecolors='k')
self.canvas.draw()
if len(self.x_clicks) == 2:
self.major = np.sqrt(
(self.x_clicks[0] - self.x_clicks[1]) ** 2 + (self.y_clicks[0] - self.y_clicks[1]) ** 2)
self.x0 = np.mean(self.x_clicks)
self.y0 = np.mean(self.y_clicks)
yangle = np.max(np.array(self.y_clicks) - self.y0)
xangle = np.array(self.x_clicks[np.argmax(np.array(self.y_clicks) - self.y0)]) - self.x0
self.angle = np.arctan2(yangle, xangle)
ax.scatter(self.x_clicks[1], self.y_clicks[1], facecolors='none', edgecolors='k')
ax.plot(self.x_clicks, self.y_clicks, '--k')
ax.scatter(self.x0, self.y0, facecolors='none', edgecolors='k')
self.canvas.draw()
if len(self.x_clicks) == 3:
self.minor = np.sqrt((self.x_clicks[2] - self.x0) ** 2 + (self.y_clicks[2] - self.y0) ** 2) * 2
if self.minor > self.major:
self.minor, self.major = self.major, self.minor
eli = patches.Ellipse((self.x0, self.y0), self.major, self.minor, np.rad2deg(self.angle), fill=False,
edgecolor='black', alpha=0.3)
ax.add_patch(eli)
ax.scatter(self.x_clicks[2], self.y_clicks[2], facecolors='none', edgecolors='k')
self.canvas.draw()
else:
pass
else:
print("Outside")
def init_buttons(self):
frame_buttons = tk.Frame(self)
frame_buttons.pack(fill='x')
ALLDONE_button = tk.Button(master=frame_buttons, text="Next track", command=self.nexttrack)
ALLDONE_button.pack(side='left', fill='x', expand=True)
UNDO_button = tk.Button(master=frame_buttons, text="Undo", command=self.undo)
UNDO_button.pack(side='left', fill='x', expand=True)
IGNORE_BUTTON = tk.Button(master=frame_buttons, text="Discard", command=self.discard)
IGNORE_BUTTON.pack(side='left', fill='x', expand=True)
QUIT_button = tk.Button(master=frame_buttons, text="QUIT", command=self.destroy)
QUIT_button.pack(side='left', fill='x', expand=True)
def nexttrack(self):
if not self.x_clicks or not len(self.x_clicks) == 3:
return 0
self.x_clicks = []
self.y_clicks = []
# Check if we have more tracks otherwise finish up the gui
if self.rawdata[-1] == self.rawdata[self.current_track]:
self.elidict[self.current_track] = {'x0': self.x0 * 0.08, 'y0': self.y0 * 0.08, 'major': self.major * 0.08,
'minor': self.minor * 0.08, 'angle': np.rad2deg(self.angle)}
self.finishup()
else:
self.elidict[self.current_track] = {'x0': self.x0 * 0.08, 'y0': self.y0 * 0.08, 'major': self.major * 0.08,
'minor': self.minor * 0.08, 'angle': np.rad2deg(self.angle)}
self.current_track += 1
self.redraw_graph()
def discard(self):
self.x_clicks = []
self.y_clicks = []
if self.rawdata[-1] == self.rawdata[self.current_track]:
self.elidict[self.current_track] = None
self.finishup()
else:
self.elidict[self.current_track] = None
self.current_track += 1
self.redraw_graph()
def undo(self):
if not self.x_clicks and self.current_track > 0:
self.current_track -= 1
self.redraw_graph()
else:
self.x_clicks = []
self.y_clicks = []
self.redraw_graph()
def redraw_graph(self, pxmin=0, pxmax=2 ** 8):
ax = self.canvas.figure.axes[0]
ax.lines = []
ax.images = []
ax.patches = []
ax.collections = []
image = self.rawdata[self.current_track].imageobject
image = np.asarray(image)
normalized = (image.astype(np.uint16) - image.min()) * 255.0 / (image.max() - image.min())
image = normalized.astype(np.uint8)
x = np.array(self.rawdata[self.current_track].x) / 0.08
y = np.array(self.rawdata[self.current_track].y) / 0.08
ax.imshow(image, cmap="gray", vmin=pxmin, vmax=pxmax)
# ax.plot(x, y, color='r')
ax.set_xlim((np.average(x) - 30, np.average(x) + 30))
ax.set_ylim((np.average(y) - 30, np.average(y) + 30))
cumulative_disp = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(cumulative_disp.min(), cumulative_disp.max())
lc = LineCollection(segments, cmap='rainbow', norm=norm)
lc.set_array(cumulative_disp)
lc.set_linewidth(2)
line = ax.add_collection(lc)
self.canvas.draw()
self.msd_alpha.set(self.rawdata[self.current_track].msd_alpha)
self.msd_text.set(
f"MSD alpha is {self.msd_alpha.get():2f} \n A value bigger than 1 corresponds to directional motion \n "
f"Smaller OR equal to 1 corresponds to diffusive motion")
def finishup(self):
for idx, tr in enumerate(self.rawdata):
self.rawdata[idx].ellipse = self.elidict[idx]
self.track_classes = [r for i, r in enumerate(self.rawdata) if self.elidict[i]]
self.rejects = [r for i, r in enumerate(self.rawdata) if not self.elidict[i]]
self.quit()
self.destroy()
<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import tkinter as tk
from PIL import Image
from DrawingGUI import DrawingEllipses
from AnGUI import analysisGUI
from tracks import *
from matplotlib import pyplot as plt
# Class that inherits root window class from tk
class ellipseGUI(tk.Tk):
def __init__(self):
super().__init__() # init of tk.Tk
# Configure root window
self.wm_title("IO Window")
self.title("IO Window")
self.geometry('350x75')
# List of track related objects
self.TrackList = []
self.NumberOfImages = tk.IntVar()
self.FinalTracks = []
# Text for number of tracks loaded and respective track name
self.LabelText = tk.StringVar()
self.LabelText.set(f"{self.NumberOfImages.get()} files loaded")
# Main window has two frames
# left side for input related stuff; right for output and
self.init_input()
self.init_output()
def init_input(self):
frame_input = tk.Frame(self)
frame_input.pack(fill='both', expand=True, side='left')
XML_button = tk.Button(master=frame_input, text="Load Trackmate .xml file", command=self.load_xml)
XML_button.pack(fill='x')
ANALYSIS_button = tk.Button(master=frame_input, text="Draw Ellipses", command=self.drawing_button)
ANALYSIS_button.pack(fill='x', expand=True)
def init_output(self):
frame_output = tk.Frame(self)
frame_output.pack(fill='both', expand=True, side='right')
status_text = tk.Label(master=frame_output, textvariable=self.LabelText)
status_text.pack(side='top', fill='both')
def load_xml(self):
xml = tk.filedialog.askopenfilename(initialdir="C:", title="Select Trackmate xml file")
if not xml[-3:] == "xml":
tk.messagebox.showerror(title="XML", message="File extension must be .xml")
else:
tk.messagebox.showinfo(title="Load image", message="Please load the corresponding image file")
image = []
while not image:
image = self.load_image(xml)
self.TrackList = np.append(self.TrackList, TrackV2.generator_xml(xml, image))
self.NumberOfImages.set(len(self.TrackList))
self.LabelText.set(f"{self.NumberOfImages.get()} images loaded")
def load_image(self, xmlpath):
imgdir = xmlpath
imgpath = tk.filedialog.askopenfilename(initialdir=imgdir, title="Select image file")
im = Image.open(imgpath)
return im
def drawing_button(self):
drawing_window = DrawingEllipses(self.TrackList)
drawing_window.grab_set()
self.wait_window(drawing_window)
self.FinalTracks = drawing_window.track_classes
self.destroy()
analysisapp = analysisGUI(self.FinalTracks, drawing_window.rejects, "DataDump")
analysisapp.mainloop()
if __name__ == '__main__':
pass<file_sep>matplotlib==3.4.3
numpy==1.20.3
openpyxl==3.0.9
pandas==1.3.4
Pillow==8.4.0
scipy==1.7.1
seaborn==0.11.2
tqdm==4.63.0
jupyterlab==3.3.2
ipywidgets==7.6.5<file_sep>"""
SPT_Tool 2021
<NAME> @ BCB lab ITQB
"""
import tkinter as tk
from EllipseGUI import ellipseGUI
from loadGUI import loadNPY
from BatchGUI import batchNPY
# Class that inherits root window class from tk
class ChooseWindow(tk.Tk):
"""
GUI window responsible for the choosing what input method to use
- .csv predrawn ellipse from fiji
- draw ellipses in-situ
- load previous analyzed data to compare or reanalyze
- batch load npys for several analysis
"""
def __init__(self):
super().__init__() # init of tk.Tk
self.wm_title("Methods")
self.title("Methods")
self.geometry('250x180')
status_text = tk.Label(master=self, text="Choose how to input ellipse data")
status_text.pack(side='top', fill='both')
ELLIPSE_button = tk.Button(master=self, text="Draw Ellipses (xml + tif)", command=self.ellipse)
ELLIPSE_button.pack(side='top', fill='both')
LOAD_button = tk.Button(master=self, text="Load single .npy data)", command=self.loadnpy)
LOAD_button.pack(side='top', fill='both')
BATCH_button = tk.Button(master=self, text="Batch analysis of .npy files", command=self.batchnpy)
BATCH_button.pack(side='top', fill='both')
def ellipse(self):
"""
Open next GUI window for inputting xml and drawing ellipse
"""
self.destroy()
gui = ellipseGUI()
gui.mainloop()
def loadnpy(self):
"""
Open next GUI window for inputting one or more .npy files of previously loaded data
"""
self.destroy()
gui = loadNPY()
gui.mainloop()
def batchnpy(self):
"""
Opens next GUI window for batch analysis of several npys
"""
self.destroy()
gui = batchNPY()
gui.mainloop()
if __name__ == '__main__':
app = ChooseWindow()
app.mainloop()
<file_sep># AureusSpeedTracker
### Semi-automated analysis of the kinetics and dynamics of peptidoglycan synthases of S. aureus
#### Built in Python 3.9
###
### Requirements
### Setup instructions:
###### 1. Install Anaconda3
###### 2. Clone or Download as zip this project
###### 3. Open anaconda3 prompt terminal inside AureusSpeedTracker directory
###### 4. Create a new environment (optional)
###### `conda create -n env_name python=3.9`
###### 5. Activate environment (optional)
###### `conda activate env_name`
###### 6. Install requirements from file
###### `conda install --file requirements.txt`
### Usage instructions:
###### 1. Open Terminal inside AureusSpeedTracker directory
###### 2. Activate environment (only if you created a new environment!)
###### `conda activate env_name`
###### 3. Use SPT_tool
###### `python ChooseMethodWindow.py`
###NOTE:
###### .npy files may not load properly if they were built with older library versions
###### Using a virtual environment is not necessary but strongly advised
<file_sep>import os
import tkinter as tk
from datetime import date
from tracks import *
from ReportBuilder import npy_builder, csv_dump
# Class that inherits root window class from tk
class batchNPY(tk.Tk):
def __init__(self):
super().__init__() # init of tk.Tk
# List of track related objects
self.TrackObjects = []
self.FinalTracks = None
folder = tk.filedialog.askdirectory(initialdir="C:", title="Please choose folder")
#load one by one
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(".npy"):
self.load(root+os.sep+file)
self.analyze()
def load(self, npy):
print(f"Loading {npy}")
old_objs = np.load(npy, allow_pickle=True)
print(f"Loaded {len(old_objs)} tracks")
newobjs = []
for idx, t in enumerate(old_objs):
newobjs.append(TrackV2(t.imageobject, t.x, t.y, t.samplerate, t.name, t.ellipse))
if hasattr(t, 'bruteforce_velo'):
newobjs[-1].bruteforce_velo = t.bruteforce_velo
newobjs[-1].bruteforce_phi = t.bruteforce_phi
if hasattr(t, 'muggeo_velo'):
newobjs[-1].muggeo_velo = t.muggeo_velo
newobjs[-1].muggeo_phi = t.muggeo_phi
newobjs[-1].muggeo_params = t.muggeo_params
if hasattr(t, 'manual_velo'):
newobjs[-1].manual_velo = t.manual_velo
newobjs[-1].manual_phi = t.manual_phi
return self.TrackObjects.append(np.array(newobjs))
def analyze(self):
savepath = tk.filedialog.askdirectory(initialdir="C:", title="Please select where to save the data")
savepath = os.path.join(savepath, rf"SPT_{date.today().strftime('%d_%m_%Y')}_batch")
os.makedirs(savepath, exist_ok=True)
all_arr = np.array([])
for obj in self.TrackObjects:
all_arr = np.append(all_arr, obj)
npy_builder(all_arr, [], savepath)
csv_dump(all_arr, savepath)
self.destroy()
exit()
<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import os
import json
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
from matplotlib import patches
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
sns.set_theme()
sns.set_style("white")
sns.set_style("ticks")
from tracks import *
def buildhistogram(bins):
centerbins = []
for idx, bini in enumerate(bins):
if bini == bins[-1]:
continue
else:
centerbins.append((bins[idx + 1] + bins[idx]) / 2)
return centerbins
def npy_builder(tracklist, rejects, savepath):
np.save(f"{savepath}\\DataDump.npy", tracklist)
np.save(f"{savepath}\\RejectedTracks.npy", rejects)
return
def makeimage(tracklist, savepath, MANUALbool):
"""Image of each track"""
matplotlib.use('Agg')
for tr in tracklist:
fig = plt.figure(figsize=(16, 9))
ax1 = fig.add_subplot(2, 3, 1)
if tr.imageobject:
ax1.imshow(tr.imageobject, cmap='gray')
ax1.plot(tr.x / 0.08, tr.y / 0.08, color='b', label="Track")
xeli, yeli = tr.xellipse / 0.08, tr.yellipse / 0.08
# https://matplotlib.org/stable/gallery/lines_bars_and_markers/multicolored_line.html
cumulative_disp = np.cumsum(np.sqrt(np.diff(xeli * 0.08 * 1000) ** 2 + np.diff(yeli * 0.08 * 1000) ** 2))
points = np.array([xeli, yeli]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(cumulative_disp.min(), cumulative_disp.max())
lc = LineCollection(segments, cmap='rainbow', norm=norm)
lc.set_array(cumulative_disp)
lc.set_linewidth(2)
line = ax1.add_collection(lc)
# fig.colorbar(line, ax=ax1, label="Total distance traveled (nm)")
# ax1.plot(tr.xellipse / 0.08, tr.yellipse / 0.08, color='r', label="Ellipse Points")
eli = patches.Ellipse((tr.ellipse['x0'] / 0.08, tr.ellipse['y0'] / 0.08), tr.ellipse['major'] / 0.08,
tr.ellipse['minor'] / 0.08, tr.ellipse['angle'], fill=False,
edgecolor='black', alpha=0.3)
ax1.add_patch(eli)
ax1.set_xlabel("x coordinates (px)")
ax1.set_ylabel("y coordinates (px)")
ax1.set_xlim((np.average(tr.x / 0.08) - 25, np.average(tr.x / 0.08) + 25))
ax1.set_ylim((np.average(tr.y / 0.08) - 25, np.average(tr.y / 0.08) + 25))
ax1.set_aspect('equal')
ax1.legend()
ax2 = fig.add_subplot(2, 3, 2)
ax2.set_title("Brute force")
xaxis = np.array(range(len(tr.unwrapped))) * tr.samplerate
ax2.plot(xaxis, (tr.unwrapped - tr.unwrapped[0]) * 1000, label="Raw data")
ax2.vlines(x=xaxis[tr.bruteforce_phi], ymin=0,
ymax=(tr.unwrapped[tr.bruteforce_phi] - tr.unwrapped[0]) * 1000, colors='r')
ax2.set_xlabel("Time (sec)")
ax2.set_ylabel("Unwrapped trajectory (nm)")
ax2.legend()
ax3 = fig.add_subplot(2, 3, 3)
ax3.set_title("Muggeo et al")
xaxis = np.array(range(len(tr.unwrapped))) * tr.samplerate
ax3.plot(xaxis, (tr.unwrapped - tr.unwrapped[0]) * 1000, label="Raw data")
ax3.vlines(x=xaxis[tr.muggeo_phi], ymin=0,
ymax=(tr.unwrapped[tr.muggeo_phi] - tr.unwrapped[0]) * 1000, colors='r')
ax3.set_xlabel("Time (sec)")
ax3.set_ylabel("Unwrapped trajectory (nm)")
ax3.legend()
ax5 = fig.add_subplot(2, 3, 4)
muggeo_array = np.hstack([tr.muggeo_velo for tr in tracklist])
n, bins, pat = ax5.hist(x=muggeo_array, bins='auto', density=True, alpha=0.2)
ax5.plot(buildhistogram(bins), n, 'b', linewidth=1, label="Muggeo et al Sectioning")
ax5.vlines(x=tr.muggeo_velo, colors='b', ymin=0, ymax=np.max(n), alpha=0.4)
ax5.set_xlabel('Velocity (nm/s)')
ax5.set_ylabel('PDF')
ax5.set_xlim((0, 30))
ax5.legend()
ax5 = fig.add_subplot(2, 3, 5)
brute_array = np.hstack([tr.bruteforce_velo for tr in tracklist])
n, bins, pat = ax5.hist(x=brute_array, bins='auto', density=True, alpha=0.2)
ax5.plot(buildhistogram(bins), n, 'b', linewidth=1, label="Bruteforce Sectioning")
ax5.vlines(x=tr.bruteforce_velo, colors='b', ymin=0, ymax=np.max(n), alpha=0.4)
ax5.set_xlabel('Velocity (nm/s)')
ax5.set_ylabel('PDF')
ax5.set_xlim((0, 30))
ax5.legend()
ax6 = fig.add_subplot(2, 3, 6)
dist2eli = np.linalg.norm(tr.xypairs - tr.xy_ellipse, axis=1) * 1000
avgbrute = np.mean(tr.bruteforce_velo)
avgmug = np.mean(tr.muggeo_velo)
avgmanual = np.mean(tr.manual_velo) if not np.array(tr.manual_velo).size == 0 else 0.0
rawtxt = '\n'.join((f'Brute force average = {avgbrute:.2f} nm/s',
f'Muggeo et al average = {avgmug:.2f} nm/s',
f'Manual average = {avgmanual:.2f} nm/s',
f'Average distance to ellipse {np.mean(dist2eli):.2f} nm',
f'Total distance traveled {cumulative_disp[-1]:.2f} nm',
f'Total displacement {np.sqrt((xeli[-1] - xeli[0]) ** 2 + (yeli[-1] - yeli[0]) ** 2) * 0.08 * 1000:.2f} nm',
f'Angle to imaging plane (deg) {np.rad2deg(np.arccos(tr.ellipse["minor"] / tr.ellipse["major"])):.2f} '))
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax6.text(0, 0, rawtxt, fontsize=20, bbox=props)
ax6.set_ylim((0, 0.4))
ax6.axis('off')
plt.tight_layout()
try:
name = tr.name.split(os.sep)[-2] + '_' + tr.name.split(os.sep)[-1] + '.jpeg'
except IndexError:
name = tr.name + '.jpeg'
sv = os.path.join(savepath, name)
fig.savefig(sv)
plt.close(fig)
plt.close('all')
def csv_dump(tracklist, savepath):
namelist = [tr.name for tr in tracklist]
lengthlist = [len(tr.x) for tr in tracklist]
twodspeedlist = [tr.twodspeed * 1000 for tr in tracklist]
msdalphalist = [tr.msd_alpha for tr in tracklist]
anglelist = np.rad2deg(np.arccos([i.ellipse['minor'] / i.ellipse['major'] for i in tracklist]))
radiuslist = [i.ellipse['major'] * 1000 for i in tracklist]
dispvelolist = [np.average(tr.disp_velo) for tr in tracklist]
manualvelolist = [np.average(tr.manual_velo) for tr in tracklist]
manualseclist = [len(tr.manual_phi) for tr in tracklist]
brutevelolist = [np.average(tr.bruteforce_velo) for tr in tracklist]
brutevelo_perlist = [tr.bruteforce_velo for tr in tracklist]
bruteseclist = [len(tr.bruteforce_phi) for tr in tracklist]
mugvelolist = [np.average(tr.muggeo_velo) for tr in tracklist]
mugseclist = [len(tr.muggeo_phi) for tr in tracklist]
distancelist_X = [np.sum(np.diff(tr.x)) * 1000 for tr in tracklist]
distancelist_Y = [np.sum(np.diff(tr.y)) * 1000 for tr in tracklist]
distancelist_Z = [np.sum(np.diff(tr.z)) * 1000 for tr in tracklist]
distancelist_eX = [np.sum(np.diff(tr.xellipse)) * 1000 for tr in tracklist]
distancelist_eY = [np.sum(np.diff(tr.yellipse)) * 1000 for tr in tracklist]
distancelist_total2D = [np.sum(np.sqrt(np.diff(tr.x) ** 2 + np.diff(tr.y) ** 2)) * 1000 for tr in tracklist]
distancelist_total3D = [np.sum(np.sqrt(np.diff(tr.x) ** 2 + np.diff(tr.y) ** 2 + np.diff(tr.z) ** 2)) * 1000 for tr in
tracklist]
displacementlist_2D = [np.linalg.norm([tr.x[-1] - tr.x[0], tr.y[-1] - tr.y[0], tr.z[-1] - tr.z[0]]) * 1000 for tr in
tracklist]
displacementlist_3D = [np.linalg.norm([tr.x[-1] - tr.x[0], tr.y[-1] - tr.y[0], tr.z[-1] - tr.z[0]]) * 1000 for tr in
tracklist]
ellipsedistlist = [np.mean(np.linalg.norm(tr.xypairs - tr.xy_ellipse, axis=1) * 1000) for tr in tracklist]
d = {'Name/ID': namelist, 'Track Length': lengthlist, '2D velocity (nm/s)': twodspeedlist,
'MSD alpha': msdalphalist, 'Angle (deg)': anglelist, 'Diameter (nm)': radiuslist,
'Displacement velocity (nm/s)': dispvelolist,
'Manual Velocity (nm/s)': manualvelolist, 'Manual Sections': manualseclist,
'Bruteforce Velocity (nm/s)': brutevelolist, 'Bruteforce Sections': bruteseclist,
'Bruteforce Velocity PER section (nm/s)':brutevelo_perlist,
'Muggeo et al Velocity (nm/s):': mugvelolist, 'Muggeo et al Sections:': mugseclist,
'Distance travelled in X (nm)': distancelist_X, 'Distance travelled in Y (nm)': distancelist_Y,
'Distance travelled in Z (nm)': distancelist_Z,
'Distance travelled in Xeli (nm)': distancelist_eX, 'Distance travelled in Yeli (nm)': distancelist_eY,
'Total distance travelled in 2D (nm)': distancelist_total2D,
'Total distance travelled in 3D (nm)': distancelist_total3D,
'Total displacement in 2D (nm)': displacementlist_2D, 'Total displacement in 3D (nm)': displacementlist_3D,
'Average distance to ellipse (nm)': ellipsedistlist}
df = pd.DataFrame(data=d)
df.to_excel(savepath + os.sep + "DataDump.xlsx", index=False, float_format="%.2f")
return
<file_sep>"""
SPT_TOOL
@author <NAME>
ITQB-UNL BCB 2021
"""
import os
import json
import tkinter as tk
from datetime import date
from PIL import Image
import numpy as np
from tracks import *
from ReportBuilder import makeimage, npy_builder
from AnGUI import analysisGUI
# Class that inherits root window class from tk
class loadNPY(tk.Tk):
def __init__(self):
super().__init__() # init of tk.Tk
self.wm_title("Load data")
self.title("Load data")
self.geometry('350x75')
self.numberofnpy = tk.IntVar()
self.LabelText = tk.StringVar()
self.LabelText.set(f"{self.numberofnpy.get()} files loaded")
self.TrackObjects = []
self.filenames = []
self.init_input()
self.init_output()
def init_input(self):
frame_input = tk.Frame(self)
frame_input.pack(fill='both', expand=True, side='left')
NPY_button = tk.Button(master=frame_input, text="Load .npy file", command=self.loadnpy)
NPY_button.pack(fill='x', expand=True)
ANALYZE_button = tk.Button(master=frame_input, text="Analyze .npy files", command=self.analyze)
ANALYZE_button.pack(fill='x', expand=True)
def init_output(self):
frame_output = tk.Frame(self)
frame_output.pack(fill='both', expand=True, side='right')
status_text = tk.Label(master=frame_output, textvariable=self.LabelText)
status_text.pack(side='top', fill='both')
def loadnpy(self):
npy = tk.filedialog.askopenfilename(initialdir="C:", title="Select .npy file to load")
while not npy[-3:] == "npy":
tk.messagebox.showerror(title="NPY", message="File extension must be .npy")
npy = tk.filedialog.askopenfilename(initialdir="C:", title="Select .npy file to load")
self.numberofnpy.set(self.numberofnpy.get() + 1)
self.LabelText.set(f"{self.numberofnpy.get()} files loaded")
self.filenames.append(npy)
old_objs = np.load(npy, allow_pickle=True)
newobjs = []
for idx, t in enumerate(old_objs):
newobjs.append(TrackV2(t.imageobject, t.x, t.y, t.samplerate, t.name, t.ellipse))
if hasattr(t, 'bruteforce_velo'):
newobjs[-1].bruteforce_velo = t.bruteforce_velo
newobjs[-1].bruteforce_phi = t.bruteforce_phi
if hasattr(t, 'muggeo_velo'):
newobjs[-1].muggeo_velo = t.muggeo_velo
newobjs[-1].muggeo_phi = t.muggeo_phi
newobjs[-1].muggeo_params = t.muggeo_params
if hasattr(t, 'manual_velo'):
newobjs[-1].manual_velo = t.manual_velo
try:
newobjs[-1].manual_phi = t.manual_phi
except AttributeError: # For legacy purposes
newobjs[-1].manual_phi = t.manual_sections
self.TrackObjects.append(newobjs)
def analyze(self):
if not self.numberofnpy.get():
tk.messagebox.showerror(title="NPY", message="No file loaded!")
if self.numberofnpy.get() == 1:
self.destroy()
analysisapp = analysisGUI(self.TrackObjects[0], [], self.filenames[-1].split('/')[-1][:-4])
analysisapp.mainloop()
else:
all_arr = np.array([])
for obj in self.TrackObjects:
all_arr = np.append(all_arr, obj)
self.destroy()
analysisapp = analysisGUI(self.FinalTracks, [])
analysisapp.mainloop()
<file_sep>"""
SPT_Tool 2021
<NAME> @ BCB lab ITQB
"""
import os
import time
from datetime import date
import tkinter as tk
from multiprocessing import Pool
from tracks import *
from GUI_ManualSectioning import ManualSectioning
from Analysis import minmax
from ReportBuilder import makeimage, npy_builder, csv_dump
from tqdm import tqdm
class analysisGUI(tk.Tk):
"""
Class that inherits root window class from tk
"""
def __init__(self, tracks, rejected_tracks, npyname):
super().__init__() # init of tk.Tk
self.TrackList = tracks
self.wm_title("Analysis")
self.title("Analysis")
self.geometry("150x150")
self.TrackList = tracks
self.RejectedTracks = rejected_tracks
self.manual_var = tk.IntVar()
self.breakpointvar = tk.IntVar()
self.makeimagesvar = tk.IntVar()
self.manual_velo_array = np.nan
self.minmax_velo_array = np.nan
self.savepath = tk.filedialog.askdirectory(initialdir="C:", title="Please select where to save the data")
self.savepath = os.path.join(self.savepath, npyname)
os.makedirs(self.savepath, exist_ok=False)
self.init_options()
def init_options(self):
options_frame = tk.Frame(self)
options_frame.pack(fill='both', expand=True, side='left')
a_label = tk.Label(master=options_frame, text="Please choose the analysis", wraplength=300, justify='center')
a_label.pack(side='top', fill='both')
check_manual = tk.Checkbutton(master=options_frame, text="Manual Sectioning", variable=self.manual_var,
onvalue=1, offvalue=0)
check_manual.pack(anchor='w')
IMAGES_tick = tk.Checkbutton(master=options_frame, text="Optimize breakpoints", variable=self.breakpointvar,
onvalue=1,
offvalue=0)
IMAGES_tick.pack(anchor='w')
IMAGES_tick = tk.Checkbutton(master=options_frame, text="Make Images", variable=self.makeimagesvar, onvalue=1,
offvalue=0)
IMAGES_tick.pack(anchor='w')
analysis_button = tk.Button(master=options_frame, text="Start analysis", command=self.analyze)
analysis_button.pack(fill='x', expand=True)
def analyze(self):
if self.manual_var.get() == 1:
print("Manual...")
TL = ManualSectioning(self.TrackList)
TL.grab_set()
self.wait_window(TL)
self.TrackList = TL.alltracks
if self.breakpointvar.get() == 1:
print(f"Optimizing breakpoint locations...")
print(f"Using {os.cpu_count()} cpu cores")
start = time.time()
# Optimizations
with Pool(processes=os.cpu_count()) as pool:
iterable = tuple(tqdm(pool.imap(minmax, self.TrackList), total=len(self.TrackList)))
# Save results in another loop
# not really efficient but has to be this way to have 'pretty' progress bar with tqdm
# Overhead shouldnt be that bad
for idx, out in enumerate(iterable):
tr = self.TrackList[idx]
tr.bruteforce_velo, tr.bruteforce_phi, tr.muggeo_velo, tr.muggeo_phi, tr.muggeo_params = out
end = time.time()
print(f"Breakpoint optimization in {end-start:.2f} seconds")
# Not parallelized
"""
for tr in self.TrackList:
tr.minmax_velo, tr.minmax_sections = minmax(tr)
"""
if self.manual_var.get() == 1 or self.TrackList[0].manual_velo:
manualboolean = True
else:
manualboolean = False
# What to save?
# 1 - array of Track objects (.npy) to reload for reanalysis
npy_builder(self.TrackList, self.RejectedTracks, self.savepath)
# 2 - csv file with results
csv_dump(self.TrackList, self.savepath)
# 3 - images
if self.makeimagesvar.get() == 1:
makeimage(self.TrackList, self.savepath, manualboolean)
tk.messagebox.showinfo(title="All done!", message="All done! Check folder for full report data.")
self.destroy()
exit()
<file_sep>"""
SPT_Tool 2021
<NAME> @ BCB lab ITQB
"""
from scipy.signal import savgol_filter
from scipy.stats import linregress
from scipy.optimize import brute, least_squares
import numpy as np
def slope_and_mse(x, y, Rbool=False):
"""
Helper function method
Calculates the slope of a line given x and y coordinates
"""
s, o, r_value, p_value, std_err = linregress(x, y)
ypred = s * x + o
mse = np.average((y - ypred) ** 2)
if Rbool:
return s, mse, r_value
else:
return s, mse
def bayesianinfocriteria(error, k, n):
return np.log(error) + (k / n) * np.log(n)
def bruteforce_objective_function(x, *args):
xcoord = args[0]
ycoord = args[1]
# Make sure x is a list of integers (indexes of breakpoints)
x = [int(r) for r in x]
# Solution must have with UNIQUE indexes
if not len(np.unique(x)) == len(x):
return np.inf
# Indexes MUST be sorted
# https://stackoverflow.com/questions/3755136/pythonic-way-to-check-if-a-list-is-sorted-or-not
if not all(x[i] <= x[i + 1] for i in range(len(x) - 1)):
return np.inf
# Breakpoints must be far apart (here 2 points in between each breakpoint)
if np.any(np.diff(x, prepend=0, append=len(xcoord) - 1) < 4):
return np.inf
# Measure mean squared displacement between sections
_, mse = breakpoint_regression(xcoord, ycoord, x)
# sanity check, number of sections = number of breakpoints + 1
assert len(mse) == len(x) + 1
# MSE weighted average by the length of each section
# We can also minimize the standard deviation of all the distances divided by the mean should be scale
# independent
avg_mse = np.average(mse, weights=np.diff(x, prepend=0, append=len(xcoord) - 1))
return avg_mse
def bruteforce(x, y):
all_velos = []
opt_results = []
# Check 0 breakpoints since it might be better
v, e = slope_and_mse(x, y)
all_velos.append(v)
opt_results.append({'BIC': bayesianinfocriteria(e, 0, len(x)), 'x': [0, -1], 'MSE':e})
# Check 1-4 breakpoints
for sec_n in range(1, 4):
optimum = brute(bruteforce_objective_function, ranges=(slice(0, len(x) - 1, 1),) * sec_n, args=(x, y))
# Make sure the result is a list of ints
if isinstance(optimum, float):
optimum = [optimum]
optimum = [int(r) for r in optimum]
vv, e1 = breakpoint_regression(x, y, optimum)
all_velos.append(vv)
e2 = bruteforce_objective_function(optimum, x, y)
# Sanity check
assert np.average(e1, weights=np.diff(optimum, prepend=0, append=len(x) - 1)) == e2
opt_results.append({'BIC': bayesianinfocriteria(e2, sec_n, len(x)), 'x': optimum, 'MSE':e2})
# Analyze all number of breakpoints and choose the min BIC
errors = [r['MSE'] for r in opt_results]
velocity = all_velos[np.argmin(errors)]
sections = [r['x'] for r in opt_results][np.argmin(errors)]
return velocity, sections
def minmax(track):
ycoordinate = track.unwrapped
xcoordinate = np.array(range(len(ycoordinate))) * track.samplerate
# Test no sectioning
velob4, errorb4, rsquared = slope_and_mse(xcoordinate, ycoordinate, True)
if rsquared ** 2 >= 0.9:
# error is ok!
return np.abs([velob4]) * 1000, [], np.abs([velob4]) * 1000, [], {}
else:
# Try muggeo et al method
# https://www.researchgate.net/publication/10567491_Estimating_Regression_Models_with_Unknown_Break-Points
mugvelo, mugphi, mugparam = muggeo(xcoordinate, ycoordinate)
# brute force
brutevelo, brutephi = bruteforce(xcoordinate, ycoordinate)
return brutevelo, brutephi, mugvelo, mugphi, mugparam
def breakpoint_regression(x, y, delimiter):
"""
Given a set of delimiters, calculates the slopes
and mean squared errors between those delimiters
"""
section_velocity = []
section_mse = []
ve, er = slope_and_mse(x[0:delimiter[0]], y[0:delimiter[0]])
section_velocity.append(ve)
section_mse.append(er)
for idx, d in enumerate(delimiter):
if d == delimiter[-1]:
ve, er = slope_and_mse(x[d:-1], y[d:-1])
section_velocity.append(ve)
section_mse.append(er)
else:
nextd = delimiter[idx + 1]
ve, er = slope_and_mse(x[d:nextd], y[d:nextd])
section_velocity.append(ve)
section_mse.append(er)
section_velocity = np.abs(section_velocity) * 1000
section_mse = np.array(section_mse)
return section_velocity, section_mse
def muggeo(x, y):
# assume 3 b.p.s
phi = np.array([5, 10, 15])
Z = x
response = savgol_filter(y, 7, 2)
w1 = np.array([1 if i >= phi[0] else 0 for i in Z])
w2 = np.array([1 if i >= phi[1] else 0 for i in Z])
w3 = np.array([1 if i >= phi[2] else 0 for i in Z])
w = np.array([w1, w2, w3])
alpha = 3
beta = np.array([1, 1, 1])
gamma = np.array([1, 1, 1])
b = 0
itercount = 0
damper = 0.65
while not np.any(np.abs(gamma) < 1e-6) or np.all(np.abs(gamma) > 1e-3): # All below 1e-3 or one below 1e-6
U = []
V = []
for idx, p in enumerate(phi):
ZxW = Z * w[idx]
U.append(np.maximum(0, ZxW - p))
V.append(np.array([-1 if i > p else 0 for i in ZxW]))
parameters = np.hstack((alpha, beta, gamma, b))
try:
opt = least_squares(residuals, x0=parameters, args=(Z, response, U, V), method='lm')
except ValueError:
# Bail optimization didnt work # TODO why? was it bad x0?
v, _ = slope_and_mse(x, y)
finalvelo = [np.abs(v) * 1000]
return finalvelo, [], {}
alpha = opt.x[0]
beta = opt.x[1:4]
gamma = opt.x[4:7]
b = opt.x[-1]
# Not mentioned in the original paper, I added a damper term to decrease instabilities
# It slows down convergence but makes the algorithm more stable
# The final result should be the same
newphi = phi + damper * gamma / beta
if not opt.success:
# Bail optimization didnt work
v, _ = slope_and_mse(x, y)
finalvelo = [np.abs(v) * 1000]
return finalvelo, [], {}
elif itercount > 5000 or np.any(np.abs(newphi - phi) < 1e-12) or np.all(np.abs(newphi - phi) < 1e-6):
# Reached max iterations or phi is not changing
phi = newphi
break
else:
phi = newphi
w1 = np.array([1 if i >= phi[0] else 0 for i in Z])
w2 = np.array([1 if i >= phi[1] else 0 for i in Z])
w3 = np.array([1 if i >= phi[2] else 0 for i in Z])
w = np.array([w1, w2, w3])
itercount += 1
finalpars = {'alpha': alpha, 'beta': beta,
'gamma': gamma, 'b': b, 'phi': phi}
velo = [alpha]
for i in range(3):
velo.append(alpha + np.sum(beta[0:i + 1]))
finalphi = []
# Check phi's which are 'good' aka between the time domain
# Approximate those Phi's to real values in Z
for idx, p in enumerate(phi):
if Z[3] < p < Z[-4]:
idd = (np.abs(Z - p)).argmin()
if idd not in finalphi:
finalphi.append(idd)
if finalphi and opt.success: # Did we get successfull optimization AND finalphi is not empty?
sane_phi = np.sort(finalphi)
finalvelo, _ = breakpoint_regression(Z, y, sane_phi)
else:
sane_phi = []
v, _ = slope_and_mse(x, y)
finalvelo = [np.abs(v) * 1000]
return finalvelo, sane_phi, finalpars
def residuals(x, Zarray, responsearray, Uarray, Varray):
alpha = x[0]
beta = x[1:4]
gamma = x[4:7]
b = x[-1]
pred = Zarray * alpha + b
for ind, b in enumerate(beta):
pred += Uarray[ind] * b
for ind, g in enumerate(gamma):
pred += Varray[ind] * g
return pred - responsearray
def displacement(track):
"""
Displacement method. For a given track calculates the displacement between each point in 3D
The velocity is calculated by dividing each displacement by the sample rate and smoothing everything
by a 30% window moving average.
"""
xcoord = np.diff(track.x)
ycoord = np.diff(track.y)
zcoord = np.diff(track.z)
displacement_ = np.sqrt(xcoord ** 2 + ycoord ** 2 + zcoord ** 2)
# In reality we should be looking to regions of flatness
# Plateaus of slope zero which indicate constant velocity
velo = displacement_ / track.samplerate
window = int(len(displacement_) * 30) // 100
velo = np.convolve(velo, np.ones(window) / window, mode='valid')
return velo * 1000
|
06f9c93666721b57730c29cc78d70d1388f75ab9
|
[
"Markdown",
"Python",
"Text"
] | 13
|
Python
|
antmsbrito/SPT_Tool
|
c9aff669692312c807f2fb09d6ba316ab9d26709
|
3503e194264d727893bd189968cd8bd79a4f4989
|
refs/heads/master
|
<repo_name>novas-meng/fastserializer<file_sep>/src/serializer/intSerializer.java
package serializer;
import novasIo.Output;
/**
* Created by novas on 16/2/28.
*/
public class intSerializer
{
//从字节数组中读取基本信息,返回
//写int数组的时候,首先写入1,表示基本类型,2表示不是基本类型
//然后写入基本类型的索引,比如1表示int
//然后写入名称长度,名称,最后是值
public static void writeInt(Output output,String name,int value)
{
output.writeBasicFlag(Integer.TYPE);
output.writeString(name);
output.writeInt(value);
}
public static void writeInt(Output output,int value)
{
output.writeBasicFlag(Integer.TYPE);
output.writeInt(value);
}
}
<file_sep>/src/novasIo/novas.java
package novasIo;
/**
* Created by novas on 16/2/28.
*/
public class novas
{
public novas()
{
BasicType.register();
}
}
<file_sep>/src/father.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by novas on 16/2/28.
*/
public class father implements Serializable
{
HashMap<String,int[]> map=new HashMap<>();
public void change()
{
for(int i=0;i<intarray.length;i++)
{
intarray[i]=i;
}
for(int i=0;i<10000;i++)
{
int[] maparray=new int[1000];
for(int j=0;j<maparray.length;j++)
{
maparray[j]=j*i;
}
map.put(i+"",maparray);
}
st.c=9056;
}
int a=8;
double c=56.98;
// child child;
String demo="my name is novas";
student st=new student();
int[] intarray=new int[1000];
/*
public void change()
{
for(int i=0;i<array.length;i++)
{
array[i]=i;
}
st.c=9066;
}
*/
//ArrayList<String> arrayList=new ArrayList<>();
// student student=new student();
/*
public void init()
{
for(int i=0;i<9;i++)
{
arrayList.add(""+i);
}
}
*/
// class student
// {
// int index=9;
// }
}
<file_sep>/src/student.java
import java.io.Serializable;
/**
* Created by novas on 2016/3/1.
*/
public class student implements Serializable
{
int c=9;
}
<file_sep>/src/serializer/doubleSerializer.java
package serializer;
import novasIo.Output;
/**
* Created by novas on 16/2/29.
*/
public class doubleSerializer
{
public static void writeDouble(Output output,String name,double value)
{
output.writeBasicFlag(Double.TYPE);
output.writeString(name);
output.writeDouble(value);
}
}
|
ac16af7a1eb2595f0b144b75b918e6a44d1584ce
|
[
"Java"
] | 5
|
Java
|
novas-meng/fastserializer
|
e9e1fdd8ffca4f6de8d2df3a0c8b3f4302203da7
|
556f615e55571c734b179ce41f66bc1b85404d0d
|
refs/heads/master
|
<repo_name>akbarbmirza/hws-whitehouse-petitions<file_sep>/README.md
# hws-whitehouse-petitions
Project 7: Whitehouse Petitions from Hacking with Swift
<file_sep>/Whitehouse Petitions/Controllers/ViewController.swift
//
// ViewController.swift
// Whitehouse Petitions
//
// Created by <NAME> on 6/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import SwiftyJSON // to handle JSON
class ViewController: UITableViewController {
// =========================================================================
// Outlets
// =========================================================================
// =========================================================================
// Properties
// =========================================================================
// create a variable to hold our petitions
var petitions = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let urlString: String
if navigationController?.tabBarItem.tag == 0 {
urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
} else {
urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"
}
if let url = URL(string: urlString) {
if let data = try? Data(contentsOf: url) {
let json = JSON(data: data)
// if our response code is 200 (i.e. everything is normal)
if json["metadata"]["responseInfo"]["status"].intValue == 200 {
// we're OK to parse!
parse(json: json)
// exit the method if parsing was reached
return
}
}
}
// show an error since parsing wasn't reached
showError()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// =========================================================================
// TableView Methods
// =========================================================================
// tells us how many rows will be in our view
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return petitions.count
}
// tells iOS how to set up each individual cell in our table
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeue the cell in our storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// get the petition data for this cell
let petition = petitions[indexPath.row]
// set the labels in our cell
cell.textLabel?.text = petition["title"]
cell.detailTextLabel?.text = petition["body"]
// return our cell
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = DetailViewController()
vc.detailItem = petitions[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
// =========================================================================
// Helper Methods
// =========================================================================
// reads the "results" array from the JSON object it gets passed and adds it
// to our petitions property
func parse(json: JSON) {
// get our json array
for result in json["results"].arrayValue {
// store the title, body, and sigs in a dictionary that we can use
let title = result["title"].stringValue
let body = result["body"].stringValue
let sigs = result["signatureCount"].stringValue
let obj = [
"title": title,
"body": body,
"sigs": sigs
]
// append that dictionary to our petitions object
petitions.append(obj)
}
// reload our tableview
tableView.reloadData()
}
// shows an error if there was a loading error when trying to load the JSON
func showError() {
let ac = UIAlertController(
title: "Loading Error",
message: "There was a problem loading the feed; please check your connection and try again.",
preferredStyle: .alert)
ac.addAction(UIAlertAction(
title: "OK",
style: .default))
present(ac, animated: true)
}
}
|
044baf2cdc815d474567a1429e86ef011934a879
|
[
"Markdown",
"Swift"
] | 2
|
Markdown
|
akbarbmirza/hws-whitehouse-petitions
|
4ba79baa1ba51b932ef71f67db1300088e7638e9
|
7a4b6b607319085808efa8e6800f5dd60247ccf7
|
refs/heads/master
|
<file_sep>public class ListItem {
String text;
String path; // For media files and directories
boolean isDirectory;
public ListItem( String text, boolean isDirectory ) {
this.text = text;
this.isDirectory = isDirectory;
}
public String getText() {
return text;
}
public void setText( String text ) {
this.text = text;
}
public String getPath() {
return path;
}
public void setPath( String path ) {
this.path = path;
}
public boolean isDirectory() {
return isDirectory;
}
public void setIsDirectory( boolean isDirectory ) {
this.isDirectory = isDirectory;
}
}
<file_sep>public class Constants {
public enum ControlEvent {
MENU,
PLAY_PAUSE,
UP,
DOWN,
LEFT,
RIGHT
}
}
<file_sep>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.List;
public class MainMenu extends Menu {
public MainMenu(Screen myScreen) {
super(myScreen, "", "Front Row");
}
public void populateList() {
addListItem(new ListItem("Movies", true));
addListItem(new ListItem("Shows", true));
addListItem(new ListItem("Trailers", true));
addListItem(new ListItem("Music", true));
addListItem(new ListItem("XBox 360", false));
addListItem(new ListItem("Wii", false));
addListItem(new ListItem("Power Off", false));
}
public void selectCurrentItem() {
ListItem item = getSelectedItem();
if (item.getText().equals("Movies")) {
myScreen.pushDisplay(new MediaMenu(myScreen, "/Users/jrego/Movies", "Movies"));
// myScreen.pushDisplay(new MediaController(myScreen));
}
}
}
<file_sep>public class Constants {
public enum ControlEvent {
MENU,
PLAY_PAUSE,
UP,
DOWN,
LEFT,
RIGHT,
DOWN_PRESSED,
DOWN_RELEASED,
UP_PRESSED,
UP_RELEASED
}
}
<file_sep>import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.List;
public class ScrollingList {
JPanel panel;
double width;
double height;
double x;
double y;
String title;
ListGlow glow;
ListText text;
Image image;
ListItem[] listItems = new ListItem[12];
ScrollingListController slt = new ScrollingListController();
public ScrollingList( JPanel panel, List<ListItem> listItems, String title, double width, double height, double x, double y ) {
this.panel = panel;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.title = title;
glow = new ListGlow(panel, width, height, x, y);
text = new ListText(panel, listItems, width, height, x, y);
slt.setG(panel, glow, text);
slt.start();
// for( int i = 1; i < 12; i++ ) {
// listItems[i] = new ListItem("Movies " + i);
// }
// listItems[3] = new ListItem("TV Shows");
}
public ListItem getSelectedItem() {
return slt.getSelectedItem();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontRenderContext frc = g2d.getFontRenderContext();
Font f = new Font("Lucida Grande",Font.BOLD, (int)(0.065*width));
String s = new String(title);
FontMetrics fm = g2d.getFontMetrics(f);
TextLayout tl = new TextLayout(s, f, frc);
//drawBackground(g);
glow.draw(g);
text.draw(g);
g2d.setColor(Color.white);
double stringWidth = fm.stringWidth(s);
double stringHeight = fm.getHeight();
tl.draw(g2d, (int)(x+width/66.58+(width/1.17-stringWidth)/2), (int)(y+height/6.61));
}
public void handleControlEvent(Constants.ControlEvent event) {
slt.handleControlEvent(event);
}
public void drawBackground(Graphics g) {
ImageIcon ii = new ImageIcon(panel.getClass().getResource("smallhtpc.png"));
Image image = ii.getImage();
g.drawImage(image, 0, 0, panel);
}
}
<file_sep>import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class ScrollingList {
JPanel panel;
int width;
int height;
int x;
int y;
int glowX;
int glowY;
int glowWidth;
int glowHeight;
Image image;
public ScrollingList( JPanel panel, int width, int height, int x, int y ) {
this.panel = panel;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
glowX = x+((int)(width/10.0));
glowY = (int)(height/10.0*1.5);
glowWidth = (int)(width/10.0*8);
glowHeight = (int)(height/10.0);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
FontRenderContext frc = g2d.getFontRenderContext();
Font f = new Font("Helvetica Neue",Font.BOLD, (int)(0.075*width));
String s = new String("Front Row");
FontMetrics fm = g2d.getFontMetrics(f);
TextLayout tl = new TextLayout(s, f, frc);
g2d.setColor(Color.white);
int stringWidth = fm.stringWidth(s);
int stringHeight = fm.getHeight();
drawGlow(g, glowX, glowY, glowWidth, glowHeight);
tl.draw(g2d, x+(width-stringWidth)/2, (int)(height/10.0));
drawString(g2d, "Movies", x+((int)(width/10.0*1.5)), (int)(height/10.0*2));
}
public void handleDownArrow() {
glowY += glowHeight;
panel.repaint();
}
public void handleUpArrow() {
glowY -= glowHeight;
panel.repaint();
}
public void drawString(Graphics2D g2d, String s, int x, int y) {
FontRenderContext frc = g2d.getFontRenderContext();
Font f = new Font("Helvetica Neue", Font.BOLD, (int)(0.065*width));
FontMetrics fm = g2d.getFontMetrics(f);
TextLayout tl = new TextLayout(s,f,frc);
g2d.setColor(Color.white);
int stringWidth = fm.stringWidth(s);
int stringHeight = fm.getHeight();
tl.draw(g2d, x, y);
}
public void drawGlow(Graphics g, int x, int y, int width, int height) {
if (image == null) {
ImageIcon ii = new ImageIcon(panel.getClass().getResource("glowbg.jpg"));
image = ii.getImage();
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
g.drawImage(image, x, y, panel);
}
}
<file_sep>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.List;
public class MediaMenu extends Menu {
public MediaMenu(Screen myScreen, String path, String title) {
super(myScreen, path, title);
}
public void populateList() {
setListItems(MediaFileListFactory.buildList(getPath()));
}
public void selectCurrentItem() {
ListItem item = getSelectedItem();
if (item.isDirectory()) {
myScreen.pushDisplay(new MediaMenu(myScreen, item.getPath(), item.getText()));
} else {
myScreen.pushDisplay(new MediaController(myScreen, item.getPath()));
}
}
}
<file_sep>#!/bin/sh
javac -classpath .:commons-net-2.0.jar *.java
java -classpath .:commons-net-2.0.jar Screen
<file_sep>import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListText {
JPanel panel;
double x;
double y;
double yPercentOffset = 0.0;
double width;
double height;
double startY;
double yOffset;
List<ListItem> listItems;
int topIndex = 0;
int maxIndex = 16;
Image folder;
public ListText( JPanel panel, List<ListItem> listItems, double width, double height, double x, double y ) {
this.panel = panel;
this.listItems = listItems;
this.maxIndex = listItems.size();
this.x = x;
this.y = y;
this.startY = this.y;
this.yOffset = height/13.85;
this.width = width;
this.height = height;
try {
folder = ImageIO.read(panel.getClass().getResource("folder.png"));
folder = folder.getScaledInstance((int)(width/1.17), (int)(height/9.0), Image.SCALE_SMOOTH);
} catch( IOException e ) {
e.printStackTrace();
}
}
public ListItem getItem(int index) {
return listItems.get(index);
}
public int getMaxIndex() {
return maxIndex;
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
// These could change in the middle of rendering and screw us up
// don't want to hold up updates though if rendering is slow
// cache these values locally synchronously so they all match
double y;
double yPercentOffset;
int topIndex;
synchronized(this) {
y = this.y;
yPercentOffset = this.yPercentOffset;
topIndex = this.topIndex;
}
int startOffset = 0;
if( yPercentOffset < 0 ) {
startOffset--;
}
startOffset = topIndex;
if( startOffset > 0 ) {
drawItem( g2d, startOffset-1, -1, y );
}
for( int i = 0; i < Math.min(10, maxIndex-startOffset); i++ ) {
drawItem( g2d, startOffset+i, i, y );
}
if( topIndex+10 < maxIndex ) {
drawItem( g2d, startOffset+10, 10, y );
}
Font f = new Font("Lucida Grande", Font.BOLD, (int)(0.0453*width));
FontMetrics fm = g2d.getFontMetrics(f);
double fontHeight = fm.getHeight();
g2d.setColor(Color.black);
//g2d.fill(new Rectangle2D.Double(x,startY+height/3.96-2*yOffset,width,2*yOffset-height/70.5));
g2d.fill(new Rectangle2D.Double(x,startY+height/3.96-3*yOffset,width,2*yOffset));
g2d.fill(new Rectangle2D.Double(x,startY+height/3.96+10*yOffset-(fontHeight*.75),width,3*yOffset));
}
public void drawItem( Graphics2D g2d, int index, int offset, double y ) {
ListItem item = getItem(index);
if( item.isDirectory() ) {
g2d.drawImage(folder, (int)(x+width/12.9-width/16.0), (int)(y+height/3.96-height/14.2+yOffset*offset), panel);
}
drawString( g2d, item.getText(), (int)(x+width/12.9), (int)(y+height/3.96+yOffset*offset) );
}
public void drawString(Graphics2D g2d, String s, int x, int y) {
FontRenderContext frc = g2d.getFontRenderContext();
Font f = new Font("Lucida Grande", Font.BOLD, (int)(0.0453*width));
//FontMetrics fm = g2d.getFontMetrics(f);
TextLayout tl = new TextLayout(s,f,frc);
g2d.setColor(Color.white);
//double stringWidth = fm.stringWidth(s);
//double stringHeight = fm.getHeight();
tl.draw(g2d, x, y);
}
public synchronized void zeroOnIndex(int index) {
synchronized(this) {
setTopIndex(index);
yPercentOffset = 0;
y = startY;
}
}
public void setTopIndex(int topIndex) {
this.topIndex = topIndex;
}
public void move(double percentMove) {
yPercentOffset += percentMove;
synchronized(this) {
y = startY + yOffset*yPercentOffset;
}
}
}
<file_sep>import java.io.*;
import java.util.*;
public class MediaFileListFactory {
private String path;
private List<ListItem> list;
public MediaFileListFactory( String path ) {
super();
this.path = path;
buildList(path);
}
public static ArrayList<ListItem> buildList( String path ) {
ArrayList<ListItem> list = new ArrayList<ListItem>();
try {
File dir = new File(path);
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
ListItem item = new ListItem(file.getName(), file.isDirectory());
item.setPath(file.getAbsolutePath());
list.add(item);
}
}
} catch (Exception e) {
System.out.println("Error populating media file list for directory: " + path);
e.printStackTrace();
}
return list;
}
public String getPath() {
return path;
}
public ListItem get(int index) {
return list.get(index);
}
public boolean add(ListItem item) {
return list.add(item);
}
public void add(int index, ListItem item) {
list.add(index, item);
}
public void clear() {
list.clear();
}
public ListItem remove(int index) {
return list.remove(index);
}
public int size() {
return list.size();
}
}
|
466ac891934069b57e893b128b7bad07dd996da3
|
[
"Java",
"Shell"
] | 10
|
Java
|
jeffrego/mhhtpc
|
7e4bf7438516eccfb8bfb62e8fa8e26a31bbacf1
|
0fcf81b5c914e0b5b317dab6a6a7ae763761f571
|
refs/heads/master
|
<file_sep>API Reference
=============
The following is a full listing and description of the modules and functions
within the Valuehorizon Forex App for your API usage:
.. automodule:: forex.models
:members:
<file_sep>.. Valuehorizon Forex documentation master file, created by
sphinx-quickstart on Tue May 26 19:41:32 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Valuehorizon Forex 0.3.1 documentation!
==============================================
The foreign exchange market (forex, FX, or currency market) is a global decentralized market for the trading of currencies. In terms of volume of trading, it is by far the largest market in the world. This reusable Django app provides you with the tools to keep track of a set of currencies and their price data.
Valuehorizon Forex includes two models - ``Currency`` and ``CurrencyPrice``.
All ``Currency`` data are provided and maintained. Some sample ``CurrencyPrice`` data are provided,
but for a full production dataset, you will have to source the ``CurrencyPrice`` data yourself.
Contents:
.. toctree::
:maxdepth: 2
installation
data
usage
examples
documentation
faq
api
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>"""Tests for the models of the forex app."""
# Import Django libraries
from django.test import TestCase
from django.core.validators import ValidationError
# Import Valuehorizon libraries
from ..models import Currency, CurrencyPrice, convert_currency
from ..models import DATEFRAME_START_DATE
# Import other libraries
from datetime import date
from decimal import Decimal
import pandas as pd
class CurrencyModelTests(TestCase):
def setUp(self):
Currency.objects.create(name="Test Dollar", symbol="TEST")
test_curr1 = Currency.objects.get(symbol="TEST")
CurrencyPrice.objects.create(currency=test_curr1,
date=date(2015, 1, 1),
ask_price=4,
bid_price=3)
CurrencyPrice.objects.create(currency=test_curr1,
date=date(2015, 1, 3),
ask_price=6,
bid_price=5)
CurrencyPrice.objects.create(currency=test_curr1,
date=date(2015, 1, 5),
ask_price=8,
bid_price=7)
def field_tests(self):
required_fields = [u'id', 'name', 'symbol', 'ascii_symbol', 'num_code', 'digits', 'description', 'date_created', 'date_modified']
actual_fields = [field.name for field in Currency._meta.fields]
self.assertEqual(set(required_fields), set(actual_fields))
def test_unicode(self):
test_curr1 = Currency.objects.get(symbol="TEST")
test_curr1.save()
self.assertEqual(test_curr1.__unicode__(), "Test Dollar, TEST")
def test_dataframe_generation_base(self):
test_curr1 = Currency.objects.get(symbol="TEST")
df = test_curr1.generate_dataframe()
self.assertEqual(len(df.columns), 4)
self.assertTrue('ASK' in df.columns)
self.assertTrue('BID' in df.columns)
self.assertTrue('CHANGE' in df.columns)
self.assertTrue('MID' in df.columns)
def test_dataframe_generation_mid(self):
test_curr1 = Currency.objects.get(symbol="TEST")
df = test_curr1.generate_dataframe()
self.assertEqual(df.ix[0]['MID'], (df.ix[0]['ASK'] + df.ix[0]['BID']) / 2.0)
def test_dataframe_generation_fill(self):
test_curr1 = Currency.objects.get(symbol="TEST")
df = test_curr1.generate_dataframe()
self.assertEqual(df.ix[1]['ASK'], 4)
class CurrencyPriceModelTests(TestCase):
def setUp(self):
Currency.objects.create(name="Test Dollar", symbol="TEST")
test_curr1 = Currency.objects.get(symbol="TEST")
CurrencyPrice.objects.create(currency=test_curr1,
date=date(2015, 1, 1),
ask_price=4,
bid_price=3)
def field_tests(self):
required_fields = ['id', 'currency', 'date', 'ask_price', 'bid_price', 'date_created', 'date_modified']
actual_fields = [field.name for field in CurrencyPrice._meta.fields]
self.assertEqual(set(required_fields), set(actual_fields))
def test_unicode(self):
test_curr1 = Currency.objects.get(symbol="TEST")
test_curr1.save()
test_price1 = CurrencyPrice.objects.get(currency=test_curr1,
date=date(2015, 1, 1))
test_price1.save()
self.assertEqual(test_price1.__unicode__(), "Test Dollar, TEST, 2015-01-01")
def test_ask_price_min_validation(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.ask_price = 0
price.bid_price = 0
price.save()
self.assertEqual(price.ask_price, Decimal('0'))
price.ask_price = -1
try:
price.save()
raise AssertionError("Ask Price cannot be less than zero")
except ValidationError:
pass
def test_bid_price_min_validation(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015,
1, 1))
price.bid_price = 0
price.save()
self.assertEqual(price.bid_price, Decimal('0'))
price.bid_price = -1
try:
price.save()
raise AssertionError("Bid Price cannot be less than zero")
except ValidationError:
pass
def test_bid_ask_validity(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.bid_price = 50
price.ask_price = 40
try:
price.save()
raise AssertionError("Ask price must be greater than or equal to Bid price")
except ValidationError:
pass
price.bid_price = 40
price.ask_price = 50
self.assertEqual(price.save(), None)
price.bid_price = 50
price.ask_price = 50
self.assertEqual(price.save(), None)
def test_mid_price(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.ask_price = 5
price.bid_price = 4
price.save()
self.assertEqual(price.mid_price, Decimal('4.5'))
def test_spread(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.ask_price = 4
price.bid_price = 3
price.save()
self.assertEqual(price.spread, 4 - 3)
def test_ask_us(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.ask_price = Decimal('3')
price.save()
self.assertEqual(price.ask_price_us, 1 / Decimal('3'))
price.ask_price = 0
try:
price.ask_price_us
raise AssertionError("Price should not be zero")
except ZeroDivisionError:
pass
def test_bid_us(self):
test_curr1 = Currency.objects.get(symbol="TEST")
price = CurrencyPrice.objects.get(currency=test_curr1, date=date(2015, 1, 1))
price.bid_price = Decimal('3')
price.save()
self.assertEqual(price.bid_price_us, 1 / Decimal('3'))
price.bid_price = 0
try:
price.bid_price_us
raise AssertionError("Price should not be zero")
except ZeroDivisionError:
pass
class CurrencyPriceDataFrame(TestCase):
def setUp(self):
Currency.objects.create(name="Test Dollar", symbol="TEST1")
Currency.objects.create(name="Test Dollar2", symbol="TEST2")
Currency.objects.create(name="Test Dollar3", symbol="TEST3")
test_curr1 = Currency.objects.get(symbol="TEST1")
test_curr2 = Currency.objects.get(symbol="TEST2")
CurrencyPrice.objects.create(currency=test_curr1, date=date(2015, 1, 1), ask_price=4, bid_price=3)
CurrencyPrice.objects.create(currency=test_curr1, date=date(2015, 1, 15), ask_price=8, bid_price=6)
CurrencyPrice.objects.create(currency=test_curr2, date=date(2015, 2, 1), ask_price=10, bid_price=9)
CurrencyPrice.objects.create(currency=test_curr2, date=date(2015, 2, 15), ask_price=11, bid_price=7)
def test_correct_rate_input(self):
self.assertRaisesMessage(ValueError,
"Incorrect price_type (*BAD*) must be on of 'ask', 'bid' or 'mid'",
CurrencyPrice.objects.generate_dataframe,
symbols=None,
date_index=None,
price_type="*BAD*")
def test_no_symbols_no_dates(self):
df = CurrencyPrice.objects.generate_dataframe(symbols=None, date_index=None)
self.assertEqual(set(df.columns), set(["TEST1", "TEST2", "TEST3"]))
self.assertEqual(set(df.index), set(pd.date_range(DATEFRAME_START_DATE, date.today())))
def test_with_symbols_and_dates(self):
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=pd.date_range(date(2015, 1, 12), date(2015, 1, 26)))
self.assertEqual(set(df.columns), set(["TEST1", "TEST2"]))
self.assertEqual(set(df.index), set(pd.date_range(date(2015, 1, 12), date(2015, 1, 26))))
def test_nodata(self):
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST3"], date_index=None)
self.assertEqual(set(df.index), set(pd.date_range(DATEFRAME_START_DATE, date.today())))
self.assertEqual(set(df.columns), set(["TEST3"]))
for datapoint in df["TEST3"]:
self.assertEqual(pd.np.isnan(datapoint), True)
def test_fill(self):
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=None)
self.assertEqual(set(df.columns), set(["TEST1", "TEST2"]))
self.assertEqual(set(df.index), set(pd.date_range(DATEFRAME_START_DATE, date.today())))
self.assertEqual(df.loc[date(2015, 1, 10)]['TEST1'], Decimal('3.5'))
def test_price_types(self):
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=None)
self.assertEqual(df.loc[date(2015, 1, 10)]['TEST1'], Decimal('3.5'))
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=None, price_type="mid")
self.assertEqual(df.loc[date(2015, 1, 10)]['TEST1'], Decimal('3.5'))
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=None, price_type='ask')
self.assertEqual(df.loc[date(2015, 1, 10)]['TEST1'], Decimal('4'))
df = CurrencyPrice.objects.generate_dataframe(symbols=["TEST1", "TEST2"], date_index=None, price_type="bid")
self.assertEqual(df.loc[date(2015, 1, 10)]['TEST1'], Decimal('3'))
class ComputeReturnTests(TestCase):
def setUp(self):
Currency.objects.create(name="Test Dollar", symbol="TEST1")
test_curr1 = Currency.objects.get(symbol="TEST1")
CurrencyPrice.objects.create(currency=test_curr1, date=date(2015, 1, 1), ask_price=4, bid_price=2)
CurrencyPrice.objects.create(currency=test_curr1, date=date(2015, 1, 15), ask_price=8, bid_price=6)
def test_bad_input_rate(self):
test_curr1 = Currency.objects.get(symbol="TEST1")
self.assertRaisesMessage(ValueError,
"Unknown rate type (*BAD*)- must be 'MID', 'ASK' or 'BID'",
test_curr1.compute_return,
date(2015, 1, 2),
date(2015, 1, 5),
rate="*BAD*")
def test_bad_input_dates(self):
test_curr1 = Currency.objects.get(symbol="TEST1")
self.assertRaisesMessage(ValueError,
"End date must be on or after start date",
test_curr1.compute_return,
date(2015, 1, 10),
date(2015, 1, 5),
rate="MID")
def test_computation(self):
test_curr1 = Currency.objects.get(symbol="TEST1")
self.assertEqual(test_curr1.compute_return(start_date=date(2015, 1, 1), end_date=date(2015, 1, 15), rate="MID"), (7. / 3) - 1)
self.assertEqual(test_curr1.compute_return(start_date=date(2015, 1, 1), end_date=date(2015, 1, 15)), (7. / 3) - 1)
self.assertEqual(test_curr1.compute_return(start_date=date(2015, 1, 1), end_date=date(2015, 1, 15), rate="ASK"), 1)
self.assertEqual(test_curr1.compute_return(start_date=date(2015, 1, 1), end_date=date(2015, 1, 15), rate="BID"), 2)
class ConvertCurrencyTests(TestCase):
def setUp(self):
Currency.objects.create(name="Test Dollar", symbol="TEST")
test_curr1 = Currency.objects.get(symbol="TEST")
CurrencyPrice.objects.create(currency=test_curr1,
date=date(2015, 1, 1),
ask_price=4,
bid_price=3)
Currency.objects.create(name="Test Dollar2", symbol="TEST2")
test_curr2 = Currency.objects.get(symbol="TEST2")
CurrencyPrice.objects.create(currency=test_curr2,
date=date(2015, 1, 1),
ask_price=8,
bid_price=6)
Currency.objects.create(name="Test Dollar3", symbol="TEST3")
test_curr2 = Currency.objects.get(symbol="TEST3")
CurrencyPrice.objects.create(currency=test_curr2,
date=date(2016, 1, 1),
ask_price=10,
bid_price=9)
def test_convert_equal_currency(self):
self.assertEqual(convert_currency("TEST", "TEST", 45, date(2015, 1, 1)), 45)
self.assertEqual(convert_currency("TEST", "TEST", -45, date(2015, 1, 1)), -45)
self.assertEqual(convert_currency("TEST", "TEST", 45, date(2015, 1, 30)), 45)
self.assertEqual(convert_currency("TEST", "TEST", -45, date(2015, 1, 30)), -45)
def test_convert_currency_no_data(self):
self.assertEqual(convert_currency("TEST", "TEST2", -45, date(2015, 1, 15)), None)
self.assertEqual(convert_currency("TEST", "TEST3", -45, date(2015, 1, 1)), None)
def test_convert_currency_float(self):
self.assertEqual(convert_currency("TEST", "TEST2", float(4.5), date(2015, 1, 1)), float(9))
self.assertEqual(convert_currency("TEST", "TEST2", pd.np.float(4.5), date(2015, 1, 1)), pd.np.float(9))
self.assertEqual(convert_currency("TEST", "TEST2", pd.np.float16(4.5), date(2015, 1, 1)), pd.np.float16(9))
self.assertEqual(convert_currency("TEST", "TEST2", pd.np.float32(4.5), date(2015, 1, 1)), pd.np.float32(9))
self.assertEqual(convert_currency("TEST", "TEST2", pd.np.float64(4.5), date(2015, 1, 1)), pd.np.float64(9))
self.assertEqual(convert_currency("TEST", "TEST2", pd.np.float128(4.5), date(2015, 1, 1)), pd.np.float128(9))
self.assertEqual(convert_currency("TEST", "TEST2", 4.5, date(2015, 1, 1)), 9.0)
self.assertEqual(convert_currency("TEST", "TEST2", Decimal('4.5'), date(2015, 1, 1)), Decimal('9.0000'))
self.assertEqual(convert_currency("TEST", "TEST2", '-45', date(2015, 1, 1)), None)
<file_sep>from django.contrib import admin
from forex.models import Currency, CurrencyPrice
class CurrencyAdmin(admin.ModelAdmin):
search_fields=["name", ]
list_display = ('name', 'symbol', 'digits', 'num_code', 'ascii_symbol')
admin.site.register(Currency, CurrencyAdmin)
class CurrencyPriceAdmin(admin.ModelAdmin):
list_filter=['currency']
list_display = ('currency', 'date', 'ask_price', 'bid_price')
admin.site.register(CurrencyPrice, CurrencyPriceAdmin)
<file_sep>#!/usr/bin/env python
"""
This script is a trick to setup a fake Django environment, since this reusable
app will be developed and tested outside any specifiv Django project.
Via ``settings.configure`` you will be able to set all necessary settings
for your app and run the tests as if you were calling ``./manage.py test``.
"""
from django.conf import settings
from django_nose import NoseTestSuiteRunner
import sys
import coverage
import forex.settings.test_settings as test_settings
if not settings.configured:
settings.configure(**test_settings.__dict__)
class NoseCoverageTestRunner(NoseTestSuiteRunner):
"""Custom test runner that uses nose and coverage"""
def run_tests(self, *args, **kwargs):
cov = coverage.Coverage()
cov.start()
results = super(NoseCoverageTestRunner, self).run_tests(
*args, **kwargs)
cov.stop()
cov.save()
cov.html_report()
return results
def runtests(*test_args):
failures = NoseCoverageTestRunner(verbosity=2, interactive=True).run_tests(
test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<file_sep>Examples and Notebooks
======
This document is meant to give a tutorial-like overview of all common tasks
while using Valuehorizon Forex.
The purpose of this app is to provide tools for working with Foreign Exchange Data.
It allows you to calculate and convert one currency to another, compute the mid point
between bid and ask prices, generates dataframe consisting of the currency prices plus more!
<file_sep>Installation
=========
Simple instructions for installation and configuration of the Valuehorizon Forex application.
Install Forex
--------------------------
Start by creating a new virtualenv for your project::
$ mkvirtualenv myproject
Next install the Valuehorizon Forex application::
$ pip install valuehorizon-forex
Finally, install Valuehorizon Forex, from the `PyPI <https://pypi.python.org/pypi/valuehorizon-forex>`_ distribution package with::
$ pip install valuehorizon-forex
Dependencies
--------------------------
Valuehorizon Forex has a few dependencies that are requried for its time series functionality.
The following commands are for installing these dependencies on a Ubuntu Linux machine.
First, install the ``python-dev`` library through the package manager::
$ sudo apt-get install python-dev
Next, install ``lxml``, ``numpy`` and ``pandas``::
$ pip install lxml
$ pip install numpy
$ pip install pandas
Optionally, you can install ``scipy`` to access some of the advanced features of pandas::
$ pip install pandas
If you are trying to install on a Windows or Mac machine, then we recommend using the
`Enthought Canopy <https://www.enthought.com/products/canopy/package-index>`_ package index.
Configuration
-------------
Add ``'forex'`` to the ``INSTALLED_APPS`` section in your django settings file.
<file_sep>=======================
Forex, by Valuehorizon
=======================
.. image:: https://badge.fury.io/py/valuehorizon-forex.svg
:target: http://badge.fury.io/py/valuehorizon-forex
.. image:: https://travis-ci.org/Valuehorizon/valuehorizon-forex.svg?branch=master
:target: https://travis-ci.org/Valuehorizon/valuehorizon-forex
.. image:: https://coveralls.io/repos/Valuehorizon/valuehorizon-forex/badge.svg
:target: https://coveralls.io/r/Valuehorizon/valuehorizon-forex
.. image:: https://codeclimate.com/github/Valuehorizon/valuehorizon-forex/badges/gpa.svg
:target: https://codeclimate.com/github/Valuehorizon/valuehorizon-forex
A Django-based Foreign Exchange data toolkit. It provides time-series functionality
with built-in statistical plugins such as volatility and returns. You can also write
your own statistical plugins.
It also includes documentation, test coverage and a good amount of sample data to play around with.
This app is a part of the Valuehorizon application ecosystem.
Installation
============
Start by creating a new ``virtualenv`` for your project ::
mkvirtualenv myproject
Next install ``numpy`` and ``pandas`` and optionally ``scipy`` ::
pip install numpy==1.1.0
pip install pandas==0.13.0
Finally, install ``valuehorizon-forex`` using ``pip``::
pip install valuehorizon-forex
Usage
============
Let's start by loading some sample data.::
python manage.py load_fixtures --settings=my_settings_file
This dataset contains the exchange rate data for the US Dollar to Euro (USD/EUR) from 2013-01-01 to 2015-12-31. In a
django shell, we can try the following::
euro = Currency.objects.get(symbol="EUR")
Contributing
============
Please file bugs and send pull requests to the `GitHub repository`_ and `issue
tracker`_.
.. _GitHub repository: https://github.com/Valuehorizon/valuehorizon-forex/
.. _issue tracker: https://github.com/Valuehorizon/valuehorizon-forex/issues
Commercial Support
==================
This project is sponsored by Valuehorizon_. If you require assistance on
your project(s), please contact us: <EMAIL>.
.. _Valuehorizon: http://www.valuehorizon.com
<file_sep># -*- encoding: utf-8 -*-
"""
Python setup file for the forex app.
"""
import os
from setuptools import setup, find_packages
import forex as app
dev_requires = [
'flake8',
]
install_requires = [
# User should install requirements
]
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
return ''
setup(
name="valuehorizon-forex",
version=app.__version__,
description=read('DESCRIPTION'),
long_description=read('README.rst'),
license='The MIT License',
platforms=['OS Independent'],
keywords='django, app, reusable, finance, forex, foreign exchange, valuehorizon',
author='<NAME>',
author_email='<EMAIL>',
url="https://github.com/Valuehorizon/valuehorizon-forex",
packages=find_packages(),
include_package_data=True,
install_requires=install_requires,
extras_require={
'dev': dev_requires,
},
test_suite="forex.tests.runtests.runtests"
)
<file_sep>from django.db import models
from django.db.models import Manager
from django.core.validators import MinValueValidator, ValidationError
# Import misc packages
import numpy as np
from datetime import date, timedelta
from decimal import Decimal
from pandas import DataFrame, date_range
PRICE_PRECISION = 4
DATEFRAME_START_DATE = date(2005, 1, 1)
class Currency(models.Model):
"""
Represents a currency according to ISO 4217 standards.
"""
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=10, unique=True)
ascii_symbol = models.CharField(max_length=20, null=True, blank=True)
num_code = models.IntegerField(null=True, blank=True)
digits = models.IntegerField(null=True, blank=True) # Digits after decimal (minor unit)
description = models.TextField(blank=True)
# Cached Data
date_modified = models.DateTimeField(null=True, blank=True, editable=False, auto_now=True)
date_created = models.DateTimeField(null=True, blank=True, editable=False, auto_now_add=True)
class Meta:
verbose_name_plural = 'Currencies'
verbose_name = 'Currency'
ordering = ['name', 'symbol']
def __unicode__(self):
return u'%s, %s' % (unicode(self.name), unicode(self.symbol))
def generate_dataframe(self, start_date=None, end_date=None):
"""
"""
first_series_point = CurrencyPrice.objects.filter(currency=self)[0]
last_series_point = CurrencyPrice.objects.filter(currency=self).reverse()[0]
start_date = first_series_point.date if start_date is None else max(first_series_point.date, start_date)
temp_start_date = start_date - timedelta(days=3) # Add lag
end_date = last_series_point.date if end_date is None else min(last_series_point.date, end_date)
currency_date = CurrencyPrice.objects.filter(currency=self, date__gte=temp_start_date, date__lte=end_date).values_list('date', 'ask_price', 'bid_price')
currency_data_array = np.core.records.fromrecords(currency_date, names=['DATE', "ASK", "BID"])
df = DataFrame.from_records(currency_data_array, index='DATE').astype(float)
df['MID'] = (df['ASK'] + df['BID']) / 2.0
df['CHANGE'] = df['MID'].pct_change()
required_dates = date_range(start_date, end_date)
df = df.reindex(required_dates)
df = df.fillna(method='ffill')
return df
def compute_return(self, start_date, end_date, rate="MID"):
"""
Compute the return of the currency between two dates
"""
if rate not in ["MID", "ASK", "BID"]:
raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate))
if end_date <= start_date:
raise ValueError("End date must be on or after start date")
df = self.generate_dataframe(start_date=start_date, end_date=end_date)
start_price = df.ix[start_date][rate]
end_price = df.ix[end_date][rate]
currency_return = (end_price / start_price) - 1.0
return currency_return
class CurrencyPriceManager(Manager):
""" Adds some added functionality """
def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"):
"""
Generate a dataframe consisting of the currency prices (specified by symbols)
from the start to end date
"""
# Set defaults if necessary
if symbols is None:
symbols = list(Currency.objects.all().values_list('symbol', flat=True))
try:
start_date = date_index[0]
end_date = date_index[-1]
except:
start_date = DATEFRAME_START_DATE
end_date = date.today()
date_index = date_range(start_date, end_date)
currency_price_data = CurrencyPrice.objects.filter(currency__symbol__in=symbols,
date__gte=date_index[0],
date__lte=date_index[-1]).values_list('date', 'currency__symbol', 'ask_price', 'bid_price')
try:
forex_data_array = np.core.records.fromrecords(currency_price_data, names=['date', 'symbol', 'ask_price', 'bid_price'])
except IndexError:
forex_data_array = np.core.records.fromrecords([(date(1900, 1, 1), "", 0, 0)], names=['date', 'symbol', 'ask_price', 'bid_price'])
df = DataFrame.from_records(forex_data_array, index='date')
df['date'] = df.index
if price_type == "mid":
df['price'] = (df['ask_price'] + df['bid_price']) / 2
elif price_type == "ask":
df['price'] = df['ask_price']
elif price_type == "bid":
df['price'] = df['bid_price']
else:
raise ValueError("Incorrect price_type (%s) must be on of 'ask', 'bid' or 'mid'" % str(price_type))
df = df.pivot(index='date', columns='symbol', values='price')
df = df.reindex(date_index)
df = df.fillna(method="ffill")
unlisted_symbols = list(set(symbols) - set(df.columns))
for unlisted_symbol in unlisted_symbols:
df[unlisted_symbol] = np.nan
df = df[symbols]
return df
class CurrencyPrice(models.Model):
"""
Represents a currency price to US
"""
currency = models.ForeignKey(Currency)
date = models.DateField()
# Price Data per $1 of US
ask_price = models.DecimalField(max_digits=20, decimal_places=PRICE_PRECISION,
validators=[MinValueValidator(Decimal('0.00'))])
bid_price = models.DecimalField(max_digits=20, decimal_places=PRICE_PRECISION,
validators=[MinValueValidator(Decimal('0.00'))])
# Cached Data
date_modified = models.DateTimeField(null=True, blank=True, editable=False, auto_now=True)
date_created = models.DateTimeField(null=True, blank=True, editable=False, auto_now_add=True)
# Add custom managers
objects = CurrencyPriceManager()
class Meta:
verbose_name_plural = 'Currency Prices'
verbose_name = 'Currency Price'
ordering = ['date', ]
unique_together = ['date', 'currency']
get_latest_by = "date"
def __unicode__(self):
return u'%s, %s' % (unicode(self.currency),
unicode(self.date),)
def save(self, *args, **kwargs):
"""
Sanitation checks
"""
if self.ask_price < 0:
raise ValidationError("Ask price must be greater than zero")
if self.bid_price < 0:
raise ValidationError("Bid price must be greater than zero")
if self.ask_price < self.bid_price:
raise ValidationError("Ask price must be at least Bid price")
super(CurrencyPrice, self).save(*args, **kwargs) # Call the "real" save() method.
@property
def mid_price(self):
"""
Compute the mid point between the bid and ask prices
"""
return (self.ask_price + self.bid_price) / Decimal('2.0')
@property
def spread(self):
"""
Compute the difference between bid and ask prices
"""
return (self.ask_price - self.bid_price)
@property
def ask_price_us(self):
"""
Calculate the ask_price in USD. This is the inverse
of the ask price.
"""
if self.ask_price != 0:
return 1 / Decimal(str(self.ask_price))
else:
raise ZeroDivisionError('Ask price is zero')
@property
def bid_price_us(self):
"""
Calculate the bid_price in USD. This is the inverse
of the bid price.
"""
if self.bid_price != 0:
return 1 / Decimal(str(self.bid_price))
else:
raise ZeroDivisionError('Bid price is zero')
def conversion_factor(from_symbol, to_symbol, date):
"""
Generates a multiplying factor used to convert two currencies
"""
from_currency = Currency.objects.get(symbol=from_symbol)
try:
from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price
except CurrencyPrice.DoesNotExist:
print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date))
return None
to_currency = Currency.objects.get(symbol=to_symbol)
try:
to_currency_price = CurrencyPrice.objects.get(currency=to_currency, date=date).mid_price
except CurrencyPrice.DoesNotExist:
print "Cannot fetch prices for %s on %s" % (str(to_currency), str(date))
return None
return to_currency_price / from_currency_price
def convert_currency(from_symbol, to_symbol, value, date):
"""
Converts an amount of money from one currency to another on a specified date.
"""
if from_symbol == to_symbol:
return value
factor = conversion_factor(from_symbol, to_symbol, date)
if type(value) == float:
output = value * float(factor)
elif type(value) == Decimal:
output = Decimal(format(value * factor, '.%sf' % str(PRICE_PRECISION)))
elif type(value) in [np.float16, np.float32, np.float64, np.float128, np.float]:
output = float(value) * float(factor)
else:
output = None
return output
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forex', '0003_auto_20150508_1447'),
]
operations = [
migrations.RemoveField(
model_name='currency',
name='change_52_week',
),
migrations.RemoveField(
model_name='currency',
name='latest_ask_price',
),
migrations.RemoveField(
model_name='currency',
name='latest_ask_price_us',
),
migrations.RemoveField(
model_name='currency',
name='latest_change',
),
migrations.RemoveField(
model_name='currency',
name='latest_date',
),
migrations.RemoveField(
model_name='currency',
name='volatility_52_week',
),
]
<file_sep>[run]
source = forex
branch = 0
omit =
forex/migrations/*
forex/tests/*
forex/settings/*
[report]
exclude_lines =
pragma: no cover
def __repr__
raise AssertionError
raise NotImplementedError
if __name__ == .__main__.:
<file_sep>Loading the Data
======
This document is meant to give a tutorial-like overview of all common tasks
while using Valuehorizon Forex.
The purpose of this app is to provide tools for working with Foreign Exchange Data.
It allows you to calculate and convert one currency to another, compute the mid point
between bid and ask prices, generates dataframe consisting of the currency prices plus more!
Load the full Currency dataset
------------------------------
Start by creating a new virtualenv for your project::
Maintain the Currency dataset
-----------------------------
Start by creating a new virtualenv for your project::
Load the sample CurrencyPrice dataset
-------------------------------------
Start by creating a new virtualenv for your project::<file_sep>FAQ
=========
Simple instructions for installation and configuration of the Valuehorizon Forex application.
Since Pythagoras, we know that :math:`a^2 + b^2 = c^2`.
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('forex', '0006_auto_20150524_1013'),
]
operations = [
migrations.AlterField(
model_name='currencyprices',
name='ask_price',
field=models.DecimalField(max_digits=20, decimal_places=4, validators=[django.core.validators.MinValueValidator(Decimal('0.00'))]),
),
migrations.AlterField(
model_name='currencyprices',
name='bid_price',
field=models.DecimalField(blank=True, null=True, max_digits=20, decimal_places=4, validators=[django.core.validators.MinValueValidator(Decimal('0.00'))]),
),
]
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('forex', '0008_auto_20150526_1310'),
]
operations = [
migrations.RenameModel(
old_name='CurrencyPrices',
new_name='CurrencyPrice',
),
]
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Currency',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=255)),
('symbol', models.CharField(unique=True, max_length=10)),
('ascii_symbol', models.CharField(max_length=20, null=True, blank=True)),
('num_code', models.IntegerField(null=True, blank=True)),
('digits', models.IntegerField(null=True, blank=True)),
('description', models.TextField(blank=True)),
('latest_date', models.DateField(null=True, editable=False, blank=True)),
('latest_ask_price', models.DecimalField(null=True, editable=False, max_digits=20, decimal_places=4, blank=True)),
('latest_ask_price_us', models.DecimalField(null=True, editable=False, max_digits=20, decimal_places=4, blank=True)),
('latest_change', models.DecimalField(null=True, editable=False, max_digits=20, decimal_places=2, blank=True)),
('change_52_week', models.DecimalField(null=True, editable=False, max_digits=20, decimal_places=2, blank=True)),
('volatility_52_week', models.DecimalField(null=True, editable=False, max_digits=20, decimal_places=2, blank=True)),
],
options={
'ordering': ['symbol'],
'verbose_name': 'Currency',
'verbose_name_plural': 'Currencies',
},
),
migrations.CreateModel(
name='CurrencyPrices',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date', models.DateField()),
('ask_price', models.DecimalField(max_digits=20, decimal_places=4)),
('bid_price', models.DecimalField(null=True, max_digits=20, decimal_places=4, blank=True)),
('ask_price_us', models.DecimalField(null=True, max_digits=20, decimal_places=4, blank=True)),
('bid_price_us', models.DecimalField(null=True, max_digits=20, decimal_places=4, blank=True)),
('name', models.CharField(max_length=255, null=True, blank=True)),
('is_monthly', models.BooleanField(default=False)),
('currency', models.ForeignKey(to='forex.Currency')),
],
options={
'ordering': ['date'],
'get_latest_by': 'date',
'verbose_name': 'Currency Price',
'verbose_name_plural': 'Currency Prices',
},
),
migrations.AlterUniqueTogether(
name='currencyprices',
unique_together=set([('date', 'currency')]),
),
]
|
4de7bd4bac917eacae0ed49ace8bff59668039fa
|
[
"Python",
"reStructuredText",
"INI"
] | 17
|
reStructuredText
|
Valuehorizon/forex
|
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
|
4492cef009ca22461a08582baa91848e6847357a
|
refs/heads/master
|
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_operator_non_member.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/18 16:01:39 by jereligi #+# #+# */
/* Updated: 2021/03/18 16:08:50 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
void test_non_member_ope_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "== | != :" << COLOR_RESET << std::endl;
std::list<std::string> lst_str1;
lst_str1.push_back("Mulhouse");
lst_str1.push_back("Niort");
lst_str1.push_back("Locmaria grand-champ");
lst_str1.push_back("Vatan");
lst_str1.push_back("jouy-en-josasse");
std::list<std::string> lst_str2(lst_str1);
std::list<std::string> lst_str3;
lst_str3.push_back("Paris");
lst_str3.push_back("Lyon");
lst_str3.push_back("Toulouse");
lst_str3.push_back("Grenoble");
lst_str3.push_back("Brest");
std::cout << "For string list lst_str1 : ";
std::cout << " { ";
for (std::list<std::string>::iterator it = lst_str1.begin(); it != lst_str1.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For string list lst_str2 : ";
std::cout << " { ";
for (std::list<std::string>::iterator it = lst_str2.begin(); it != lst_str2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For string list lst_str3 : ";
std::cout << " { ";
for (std::list<std::string>::iterator it = lst_str3.begin(); it != lst_str3.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_str1 == lst_str1 : " << std::boolalpha << (lst_str1 == lst_str1) << std::endl << std::endl;
std::cout << "lst_str1 == lst_str2 : " << std::boolalpha << (lst_str1 == lst_str2) << std::endl;
std::cout << "lst_str1 != lst_str2 : " << std::boolalpha << (lst_str1 != lst_str2) << std::endl << std::endl;
std::cout << "lst_str1 == lst_str3 : " << std::boolalpha << (lst_str1 == lst_str3) << std::endl;
std::cout << "lst_str1 != lst_str3 : " << std::boolalpha << (lst_str1 != lst_str3) << std::endl << std::endl;
std::cout << COLOR_YELLOW << "< | <= :" << COLOR_RESET << std::endl;
std::list<int> lst_nums1;
lst_nums1.push_back(0);
lst_nums1.push_back(1);
lst_nums1.push_back(10);
lst_nums1.push_back(11);
lst_nums1.push_back(100);
lst_nums1.push_back(101);
lst_nums1.push_back(110);
lst_nums1.push_back(111);
std::list<int> lst_nums2(lst_nums1);
lst_nums2.push_back(1000);
std::cout << "For int string list lst_nums1 : ";
std::cout << " { ";
for (std::list<int>::iterator it = lst_nums1.begin(); it != lst_nums1.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For int string list lst_nums2 : ";
std::cout << " { ";
for (std::list<int>::iterator it = lst_nums2.begin(); it != lst_nums2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_nums1 < lst_nums1 = " << (lst_nums1 < lst_nums1) << std::endl;
std::cout << "lst_nums1 < lst_nums2 = " << (lst_nums1 < lst_nums2) << std::endl;
std::cout << "lst_nums2 < lst_nums1 = " << (lst_nums2 < lst_nums1) << std::endl;
std::cout << "lst_nums1 <= lst_nums1 = " << (lst_nums1 <= lst_nums1) << std::endl;
std::cout << "lst_nums1 <= lst_nums2 = " << (lst_nums1 <= lst_nums2) << std::endl;
std::cout << "lst_nums2 <= lst_nums1 = " << (lst_nums2 <= lst_nums1) << std::endl << std::endl;
std::cout << COLOR_YELLOW << "> | >= :" << COLOR_RESET << std::endl;
std::cout << "lst_nums1 > lst_nums1 = " << (lst_nums1 > lst_nums1) << std::endl;
std::cout << "lst_nums1 > lst_nums2 = " << (lst_nums1 > lst_nums2) << std::endl;
std::cout << "lst_nums2 > lst_nums1 = " << (lst_nums2 > lst_nums1) << std::endl;
std::cout << "lst_nums1 >= lst_nums1 = " << (lst_nums1 >= lst_nums1) << std::endl;
std::cout << "lst_nums1 >= lst_nums2 = " << (lst_nums1 >= lst_nums2) << std::endl;
std::cout << "lst_nums2 >= lst_nums1 = " << (lst_nums2 >= lst_nums1) << std::endl;
next_test();
}
void test_non_member_ope(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test non-member operators" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "== | != :" << COLOR_RESET << std::endl;
ft::list<std::string> lst_str1;
lst_str1.push_back("Mulhouse");
lst_str1.push_back("Niort");
lst_str1.push_back("<NAME>");
lst_str1.push_back("Vatan");
lst_str1.push_back("jouy-en-josasse");
ft::list<std::string> lst_str2(lst_str1);
ft::list<std::string> lst_str3;
lst_str3.push_back("Paris");
lst_str3.push_back("Lyon");
lst_str3.push_back("Toulouse");
lst_str3.push_back("Grenoble");
lst_str3.push_back("Brest");
std::cout << "For string list lst_str1 : " << lst_str1 << std::endl;
std::cout << "For string list lst_str2 : " << lst_str2 << std::endl;
std::cout << "For string list lst_str3 : " << lst_str3 << std::endl << std::endl;
std::cout << "lst_str1 == lst_str1 : " << std::boolalpha << (lst_str1 == lst_str1) << std::endl << std::endl;
std::cout << "lst_str1 == lst_str2 : " << std::boolalpha << (lst_str1 == lst_str2) << std::endl;
std::cout << "lst_str1 != lst_str2 : " << std::boolalpha << (lst_str1 != lst_str2) << std::endl << std::endl;
std::cout << "lst_str1 == lst_str3 : " << std::boolalpha << (lst_str1 == lst_str3) << std::endl;
std::cout << "lst_str1 != lst_str3 : " << std::boolalpha << (lst_str1 != lst_str3) << std::endl << std::endl;
std::cout << COLOR_YELLOW << "< | <= :" << COLOR_RESET << std::endl;
ft::list<int> lst_nums1;
lst_nums1.push_back(0);
lst_nums1.push_back(1);
lst_nums1.push_back(10);
lst_nums1.push_back(11);
lst_nums1.push_back(100);
lst_nums1.push_back(101);
lst_nums1.push_back(110);
lst_nums1.push_back(111);
ft::list<int> lst_nums2(lst_nums1);
lst_nums2.push_back(1000);
std::cout << "For int string list lst_nums1 : " << lst_nums1 << std::endl;
std::cout << "For int string list lst_nums2 : " << lst_nums2 << std::endl << std::endl;
std::cout << "lst_nums1 < lst_nums1 = " << (lst_nums1 < lst_nums1) << std::endl;
std::cout << "lst_nums1 < lst_nums2 = " << (lst_nums1 < lst_nums2) << std::endl;
std::cout << "lst_nums2 < lst_nums1 = " << (lst_nums2 < lst_nums1) << std::endl;
std::cout << "lst_nums1 <= lst_nums1 = " << (lst_nums1 <= lst_nums1) << std::endl;
std::cout << "lst_nums1 <= lst_nums2 = " << (lst_nums1 <= lst_nums2) << std::endl;
std::cout << "lst_nums2 <= lst_nums1 = " << (lst_nums2 <= lst_nums1) << std::endl << std::endl;
std::cout << COLOR_YELLOW << "> | >= :" << COLOR_RESET << std::endl;
std::cout << "lst_nums1 > lst_nums1 = " << (lst_nums1 > lst_nums1) << std::endl;
std::cout << "lst_nums1 > lst_nums2 = " << (lst_nums1 > lst_nums2) << std::endl;
std::cout << "lst_nums2 > lst_nums1 = " << (lst_nums2 > lst_nums1) << std::endl;
std::cout << "lst_nums1 >= lst_nums1 = " << (lst_nums1 >= lst_nums1) << std::endl;
std::cout << "lst_nums1 >= lst_nums2 = " << (lst_nums1 >= lst_nums2) << std::endl;
std::cout << "lst_nums2 >= lst_nums1 = " << (lst_nums2 >= lst_nums1) << std::endl << std::endl;
test_non_member_ope_std();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vector.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Jeanxavier <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/04 12:05:06 by jereligi #+# #+# */
/* Updated: 2021/04/03 18:49:09 by Jeanxavier ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef VECTOR_HPP
#define VECTOR_HPP
#include "./iterator/iterator.hpp"
#include "./iterator/const_iterator.hpp"
#include "./iterator/reverse_iterator.hpp"
#include "./iterator/const_reverse_iterator.hpp"
#include "../utils.hpp"
namespace ft
{
template <class T, class Allocator = std::allocator<T> >
class vector
{
public:
typedef T value_type;
typedef Allocator allocator_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename ft::Iterator<T> iterator;
typedef typename ft::const_iterator<T> const_iterator;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename ft::reverse_iterator<T> reverse_iterator;
typedef typename ft::const_reverse_iterator<T> const_reverse_iterator;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
// default
explicit vector (const allocator_type& alloc = allocator_type())
{
_array = NULL;
_size = 0;
_capacity = 0;
_alloc = alloc;
}
// fill
explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type())
{
_array = NULL;
_size = 0;
_capacity = 0;
_alloc = alloc;
reserve(n);
for (size_type i = 0; i < n; i++)
push_back(val);
}
// range
template <class InputIterator>
vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type(),
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
_array = NULL;
_size = 0;
_capacity = 0;
_alloc = alloc;
while (first != last)
{
push_back(*first);
first++;
}
}
// copy
vector (vector& src)
{
_array = NULL;
_size = 0;
_capacity = 0;
_alloc = allocator_type();
*this = src;
}
~vector() {
clear();
}
vector& operator=(vector& src)
{
clear();
for (iterator it = src.begin(); it != src.end(); it++)
push_back(*it);
return (*this);
}
/*******************************************
***** Iterators *****
*******************************************/
iterator begin() {
return (iterator(_array));
}
const_iterator begin() const {
return (const_iterator(_array));
}
iterator end() {
return (iterator(_array + _size));
}
const_iterator end() const {
return (const_iterator(_array + _size));
}
reverse_iterator rbegin()
{
return (reverse_iterator((end() - 1)));
}
const_reverse_iterator rbegin() const
{
return (const_reverse_iterator((end() - 1)));
}
reverse_iterator rend()
{
return (reverse_iterator((begin() - 1)));
}
const_reverse_iterator rend() const
{
return (const_reverse_iterator(begin() - 1));
}
/*******************************************
***** Capacity *****
*******************************************/
size_type size() const {
return (_size);
}
size_type max_size() const {
return (_alloc.max_size());
}
void resize(size_type n, value_type val = value_type())
{
if (n < _size)
{
for (size_type i = n + 1; i < _size; i++)
_alloc.destroy(&_array[i]);
}
else if (n > _size)
{
for (size_type i = _size; i < n; i++)
push_back(val);
}
_size = n;
}
size_type capacity() const {
return (_capacity);
}
bool empty() const
{
if (_size > 0)
return (0);
return (1);
}
void reserve(size_type n)
{
if (n > _capacity)
{
T *tmp;
tmp = _alloc.allocate(n);
if (_capacity > 0)
{
for (size_type i = 0; i < _size; i++)
{
_alloc.construct(&tmp[i], _array[i]);
_alloc.destroy(&_array[i]);
}
_alloc.deallocate(_array, _capacity);
}
_array = tmp;
_capacity = n;
}
}
/*******************************************
***** Element access *****
*******************************************/
reference operator[](size_type n) {
return (_array[n]);
}
const_reference operator[](size_type n) const {
return (_array[n]);
}
reference at(size_type n)
{
if (n >= _size)
throw std::out_of_range("Out of Range error");
return (_array[n]);
}
const_reference at(size_type n) const
{
if (n >= _size)
throw std::out_of_range("Out of Range error");
return (_array[n]);
}
reference front() {
return (_array[0]);
}
const_reference front() const {
return (_array[0]);
}
reference back() {
return (_array[_size - 1]);
}
const_reference back() const {
return (_array[_size - 1]);
}
/*******************************************
***** Modifiers *****
*******************************************/
template <class InputIterator>
void assign (InputIterator first, InputIterator last,
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
if (empty() == 0)
clear();
while (first < last)
{
push_back(*first);
first++;
}
}
void assign(size_type n, const value_type& val)
{
if (empty() == 0)
clear();
for (size_type i = 0; i < n; i++)
push_back(val);
}
void push_back(const value_type& val)
{
if (_size >= _capacity)
{
if (_size == 0)
reserve(1);
else
reserve(_capacity * 2);
}
_array[_size] = val;
_size++;
}
void pop_back()
{
_alloc.destroy(&_array[_size]);
_size -= 1;
}
iterator insert(iterator position, const value_type& val)
{
// if (_size + 1 >= _capacity)
// {
// if (_size == 0)
// reserve(1);
// else
// reserve(_capacity * 2);
// }
ft::vector<T> tmp(position, end());
for (size_type i = 0; i < tmp.size(); i++)
pop_back();
push_back(val);
iterator it = tmp.begin();
for (size_type i = 0; i < tmp.size(); i++, it++)
push_back(*it);
return (position);
}
void insert(iterator position, size_type n, const value_type& val)
{
// if (_size + n >= _capacity)
// {
// if (_size == 0)
// reserve(1);
// else
// reserve(_capacity * 2);
// }
ft::vector<T> tmp(position, end());
for (size_type i = 0; i < tmp.size(); i++)
pop_back();
for (size_type i = 0; i < n; i++)
push_back(val);
iterator it = tmp.begin();
for (size_type i = 0; i < tmp.size(); i++, it++)
push_back(*it);
}
template <class InputIterator>
void insert(iterator position, InputIterator first, InputIterator last,
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
difference_type int_pos = position - this->begin();
size_type count = 0;
while (first != last)
{
first++;
count++;
}
first -= count;
if (_capacity - _size <= count)
{
if (_size == 0)
reserve(1);
else
reserve(_capacity * 2);
}
ft::vector<T> tmp(begin() + int_pos, end());
for (size_type i = 0; i < tmp.size(); i++)
pop_back();
while (first != last)
{
push_back(*first);
first++;
}
iterator it = tmp.begin();
for (size_type i = 0; i < tmp.size(); i++, it++)
push_back(*it);
}
iterator erase(iterator position)
{
ft::vector<T> tmp(position + 1, end());
for (size_type i = 0; i < tmp._size; i++)
pop_back();
pop_back();
for (iterator it = tmp.begin(); it != tmp.end(); it++)
push_back(*it);
return (position);
}
iterator erase(iterator first, iterator last)
{
iterator tmp = first;
while (tmp != last)
{
erase(first);
tmp++;
}
return (first);
}
void swap(vector& src)
{
std::swap(_array, src._array);
std::swap(_size, src._size);
std::swap(_capacity, src._capacity);
}
void clear()
{
if (_size > 0)
{
for (size_type i = 0; i <= _size; i++)
_alloc.destroy(&_array[i]);
_alloc.deallocate(_array, _capacity);
// _array = NULL;
_size = 0;
_capacity = 0;
}
}
private:
T *_array;
size_type _size;
size_type _capacity;
allocator_type _alloc;
};
}
#endif<file_sep>
#include "stack.hpp"
#include "../list/list.hpp"
int main(void)
{
ft::list<int> l(2,42);
ft::stack<int> s(l);
ft::stack<int> s2(l);
l.push_back(41);
s2.push(41);
std::cout << "stack size : " << s.size() << std::endl;
s.push(43);
std::cout << " == : " << std::boolalpha << (s == s2) << std::endl;
std::cout << " != : " << std::boolalpha << (s != s2) << std::endl;
std::cout << " < : " << std::boolalpha << (s < s2) << std::endl;
std::cout << " <= : " << std::boolalpha << (s2 <= s2) << std::endl;
std::cout << " > : " << std::boolalpha << (s > s2) << std::endl;
std::cout << " >= : " << std::boolalpha << (s >= s2) << std::endl;
while (!s.empty())
{
std::cout << ' ' << s.top();
s.pop();
}
return (0);
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_operations.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/18 13:45:22 by jereligi #+# #+# */
/* Updated: 2021/04/03 15:29:20 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
#include <tgmath.h>
bool mycomparison (double first, double second)
{ return ( int(first)<int(second) ); }
static void test_operations_merge_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "merge :" << COLOR_RESET << std::endl;
std::list<double> lst_doubles_a;
std::list<double> lst_doubles_b;
lst_doubles_a.push_back(3.1);
lst_doubles_a.push_back(2.2);
lst_doubles_a.push_back(2.9);
lst_doubles_b.push_back(3.7);
lst_doubles_b.push_back(7.1);
lst_doubles_b.push_back(1.4);
lst_doubles_a.sort();
lst_doubles_b.sort();
std::cout << "lst_doubles_a :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_a.begin(); it != lst_doubles_a.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_doubles_b :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_b.begin(); it != lst_doubles_b.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_doubles_a.merge(lst_doubles_b);" << std::endl << std::endl;
lst_doubles_a.merge(lst_doubles_b);
std::cout << "lst_doubles_a :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_a.begin(); it != lst_doubles_a.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_doubles_b :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_b.begin(); it != lst_doubles_b.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_doubles_b.push_back(2.1);" << std::endl;
lst_doubles_b.push_back(2.1);
std::cout << "lst_doubles_a.merge(lst_doubles_b, mycomparison);" << std::endl << std::endl;
lst_doubles_a.merge(lst_doubles_b, mycomparison);
std::cout << "lst_doubles_a :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_a.begin(); it != lst_doubles_a.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_doubles_b :";
std::cout << " { ";
for (std::list<double>::iterator it = lst_doubles_b.begin(); it != lst_doubles_b.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<int> lst_int_a;
std::list<int> lst_int_b;
lst_int_a.push_back(10);
lst_int_a.push_back(20);
lst_int_a.push_back(30);
lst_int_a.push_back(40);
lst_int_a.push_back(50);
lst_int_a.push_back(60);
lst_int_b.push_back(40);
lst_int_b.push_back(41);
lst_int_b.push_back(42);
lst_int_b.push_back(43);
lst_int_b.push_back(44);
lst_int_b.push_back(45);
std::cout << "lst_int_a :";
std::cout << " { ";
for (std::list<int>::iterator it = lst_int_a.begin(); it != lst_int_a.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_int_b :";
std::cout << " { ";
for (std::list<int>::iterator it = lst_int_b.begin(); it != lst_int_b.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_int_a.merge(lst_int_b);" << std::endl << std::endl;
lst_int_a.merge(lst_int_b);
std::cout << "lst_int_a :";
std::cout << " { ";
for (std::list<int>::iterator it = lst_int_a.begin(); it != lst_int_a.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst_int_b :";
std::cout << " { ";
for (std::list<int>::iterator it = lst_int_b.begin(); it != lst_int_b.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_operations_merge(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test merge" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "merge :" << COLOR_RESET << std::endl;
ft::list<double> lst_doubles_a;
ft::list<double> lst_doubles_b;
lst_doubles_a.push_back(3.1);
lst_doubles_a.push_back(2.2);
lst_doubles_a.push_back(2.9);
lst_doubles_b.push_back(3.7);
lst_doubles_b.push_back(7.1);
lst_doubles_b.push_back(1.4);
lst_doubles_a.sort();
lst_doubles_b.sort();
std::cout << "lst_doubles_a :" << lst_doubles_a << std::endl;
std::cout << "lst_doubles_b :" << lst_doubles_b << std::endl << std::endl;
std::cout << "lst_doubles_a.merge(lst_doubles_b);" << std::endl << std::endl;
lst_doubles_a.merge(lst_doubles_b);
std::cout << "lst_doubles_a = " << lst_doubles_a << std::endl;
std::cout << "lst_doubles_b = " << lst_doubles_b << std::endl << std::endl;
std::cout << "lst_doubles_b.push_back(2.1);" << std::endl;
lst_doubles_b.push_back(2.1);
std::cout << "lst_doubles_a.merge(lst_doubles_b, mycomparison);" << std::endl << std::endl;
lst_doubles_a.merge(lst_doubles_b, mycomparison);
std::cout << "lst_doubles_a = " << lst_doubles_a << std::endl;
std::cout << "lst_doubles_b = " << lst_doubles_b << std::endl << std::endl;
ft::list<int> lst_int_a;
ft::list<int> lst_int_b;
lst_int_a.push_back(10);
lst_int_a.push_back(20);
lst_int_a.push_back(30);
lst_int_a.push_back(40);
lst_int_a.push_back(50);
lst_int_a.push_back(60);
lst_int_b.push_back(40);
lst_int_b.push_back(41);
lst_int_b.push_back(42);
lst_int_b.push_back(43);
lst_int_b.push_back(44);
lst_int_b.push_back(45);
std::cout << "lst_int_a : " << lst_int_a << std::endl;
std::cout << "lst_int_b : " << lst_int_b << std::endl << std::endl;
std::cout << "lst_int_a.merge(lst_int_b);" << std::endl << std::endl;
lst_int_a.merge(lst_int_b);
std::cout << "lst_int_a : " << lst_int_a << std::endl;
std::cout << "lst_int_b : " << lst_int_b << std::endl << std::endl;
test_operations_merge_std();
}
static void test_operations_reverse_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "reverse :" << COLOR_RESET << std::endl;
std::list<int> lst_numbers;
lst_numbers.push_back(1);
lst_numbers.push_back(2);
lst_numbers.push_back(3);
lst_numbers.push_back(4);
lst_numbers.push_back(5);
lst_numbers.push_back(6);
lst_numbers.push_back(7);
lst_numbers.push_back(8);
lst_numbers.push_back(9);
std::cout << "For a number list : ";
std::cout << " { ";
for (std::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_numbers.reverse();
std::cout << "lst_numbers.reverse();" << std::endl;
std::cout << "lst_numbers : ";
std::cout << std::endl << "lst_numbers = { ";
for (std::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string> lst_potatos;
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("potatos");
std::cout << "For a potato list (constructor test) : ";
std::cout << std::endl << "lst_potatos = { ";
for (std::list<std::string>::iterator it = lst_potatos.begin(); it != lst_potatos.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_potatos.reverse();
std::cout << "lst_potatos.reverse();" << std::endl;
std::cout << "lst_potatos : ";
std::cout << std::endl << "lst_potatos = { ";
for (std::list<std::string>::iterator it = lst_potatos.begin(); it != lst_potatos.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string> lst_alone;
lst_alone.push_back("Simone");
std::cout << "For a string alone list (crash test) : ";
std::cout << std::endl << "lst_alone = { ";
for (std::list<std::string>::iterator it = lst_alone.begin(); it != lst_alone.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_alone.reverse();
std::cout << "lst_alone.reverse();" << std::endl;
std::cout << "lst_alone : ";
std::cout << std::endl << "lst_alone = { ";
for (std::list<std::string>::iterator it = lst_alone.begin(); it != lst_alone.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string> lst_empty;
std::cout << "For a empty string list (crash test) : ";
std::cout << std::endl << "lst_empty = { ";
for (std::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_empty.reverse();
std::cout << "lst_empty.reverse();" << std::endl;
std::cout << "lst_empty : ";
std::cout << std::endl << "lst_empty = { ";
for (std::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
static void test_operations_reverse(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test reverse" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "reverse :" << COLOR_RESET << std::endl;
ft::list<int> lst_numbers;
lst_numbers.push_back(1);
lst_numbers.push_back(2);
lst_numbers.push_back(3);
lst_numbers.push_back(4);
lst_numbers.push_back(5);
lst_numbers.push_back(6);
lst_numbers.push_back(7);
lst_numbers.push_back(8);
lst_numbers.push_back(9);
std::cout << "For a number list : " << lst_numbers << std::endl;
lst_numbers.reverse();
std::cout << "lst_numbers.reverse();" << std::endl;
std::cout << "lst_numbers : " << lst_numbers << std::endl << std::endl;
ft::list<std::string> lst_potatos;
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("🥔");
lst_potatos.push_back("potatos");
std::cout << "For a potato list (constructor test) : " << lst_potatos << std::endl;
lst_potatos.reverse();
std::cout << "lst_potatos.reverse();" << std::endl;
std::cout << "lst_potatos : " << lst_potatos << std::endl << std::endl;
ft::list<std::string> lst_alone;
lst_alone.push_back("Simone");
std::cout << "For a string alone list (crash test) : " << lst_alone << std::endl;
lst_alone.reverse();
std::cout << "lst_alone.reverse();" << std::endl;
std::cout << "lst_alone : " << lst_alone << std::endl << std::endl;
ft::list<std::string> lst_empty;
std::cout << "For a empty string list (crash test) : " << lst_empty << std::endl;
lst_empty.reverse();
std::cout << "lst_empty.reverse();" << std::endl;
std::cout << "lst_empty : " << lst_empty << std::endl << std::endl;
test_operations_reverse_std();
}
template <typename T>
static bool superior_comp(T &lvalue, T &rvalue) { return (lvalue > rvalue); };
void test_operations_sort_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "sort without condition :" << COLOR_RESET << std::endl;
std::list<int> lst_int;
lst_int.push_back(4);
lst_int.push_back(-8392454);
lst_int.push_back(3849);
lst_int.push_back(-9000);
lst_int.push_back(-2147483648);
lst_int.push_back(2147483647);
lst_int.push_back(0);
std::cout << "For a int list lst_int : ";
std::cout << std::endl << "lst_int = { ";
for (std::list<int>::iterator it = lst_int.begin(); it != lst_int.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_int.sort();
std::cout << "lst_int.sort();" << std::endl;
std::cout << "Now lst_int : ";
std::cout << std::endl << "lst_int = { ";
for (std::list<int>::iterator it = lst_int.begin(); it != lst_int.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<double> lst_double;
lst_double.push_back(2.2);
lst_double.push_back(INFINITY);
lst_double.push_back(42.42);
lst_double.push_back(420.024);
lst_double.push_back(3.14);
lst_double.push_back(-233.141);
lst_double.push_back(-INFINITY);
lst_double.push_back(0);
lst_double.push_back(347589.19454);
std::cout << "For a double list lst_double : ";
std::cout << std::endl << "lst_double = { ";
for (std::list<double>::iterator it = lst_double.begin(); it != lst_double.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_double.sort();
std::cout << "lst_double.sort();" << std::endl;
std::cout << "Now lst_double : ";
std::cout << std::endl << "lst_double = { ";
for (std::list<double>::iterator it = lst_double.begin(); it != lst_double.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string> lst_string;
lst_string.push_back("coucou8");
lst_string.push_back("coucou1");
lst_string.push_back("coucou4");
lst_string.push_back("coucou4");
lst_string.push_back("coucou2");
lst_string.push_back("coucou1");
lst_string.push_back("coucou9");
lst_string.push_back("coucou0");
lst_string.push_back("coucou6");
std::cout << "For a std::string list lst_string : ";
std::cout << std::endl << "lst_string = { ";
for (std::list<std::string>::iterator it = lst_string.begin(); it != lst_string.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_string.sort();
std::cout << "lst_string.sort();" << std::endl;
std::cout << "Now lst_string : ";
std::cout << std::endl << "lst_string = { ";
for (std::list<std::string>::iterator it = lst_string.begin(); it != lst_string.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "sort with condition :" << COLOR_RESET << std::endl;
std::cout << "Conditition superior_comp = return (lvalue > rvalue);" << std::endl;
std::list<int> lst_int_condition;
lst_int_condition.push_back(4);
lst_int_condition.push_back(-8392454);
lst_int_condition.push_back(3849);
lst_int_condition.push_back(-9000);
lst_int_condition.push_back(-2147483648);
lst_int_condition.push_back(2147483647);
lst_int_condition.push_back(0);
std::cout << "For a int list lst_int_condition : ";
std::cout << std::endl << "lst_int_condition = { ";
for (std::list<int>::iterator it = lst_int_condition.begin(); it != lst_int_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_int_condition.sort(superior_comp<int>);
std::cout << "lst_int_condition.sort(superior_comp);" << std::endl;
std::cout << "Now lst_int_condition : ";
std::cout << std::endl << "lst_int_condition = { ";
for (std::list<int>::iterator it = lst_int_condition.begin(); it != lst_int_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string> lst_string_condition;
lst_string_condition.push_back("coucou8");
lst_string_condition.push_back("coucou1");
lst_string_condition.push_back("coucou4");
lst_string_condition.push_back("coucou4");
lst_string_condition.push_back("coucou2");
lst_string_condition.push_back("coucou1");
lst_string_condition.push_back("coucou9");
lst_string_condition.push_back("coucou0");
lst_string_condition.push_back("coucou6");
std::cout << "For a std::string list lst_string_condition : " << std::endl;
lst_string_condition.sort(superior_comp<std::string>);
std::cout << "lst_string_condition.sort(superior_comp);" << std::endl;
std::cout << "Now lst_string_condition : ";
std::cout << std::endl << "lst_string_condition = { ";
for (std::list<std::string>::iterator it = lst_string_condition.begin(); it != lst_string_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_operations_sort(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test sort " << std::endl << std::endl;
std::cout << COLOR_YELLOW << "sort without condition :" << COLOR_RESET << std::endl;
ft::list<int> lst_int;
lst_int.push_back(4);
lst_int.push_back(-8392454);
lst_int.push_back(3849);
lst_int.push_back(-9000);
lst_int.push_back(-2147483648);
lst_int.push_back(2147483647);
lst_int.push_back(0);
std::cout << "For a int list lst_int : ";
std::cout << std::endl << "lst_int = { ";
for (ft::list<int>::iterator it = lst_int.begin(); it != lst_int.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_int.sort();
std::cout << "lst_int.sort();" << std::endl;
std::cout << "Now lst_int : ";
std::cout << std::endl << "lst_int = { ";
for (ft::list<int>::iterator it = lst_int.begin(); it != lst_int.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<double> lst_double;
lst_double.push_back(2.2);
lst_double.push_back(INFINITY);
lst_double.push_back(42.42);
lst_double.push_back(420.024);
lst_double.push_back(3.14);
lst_double.push_back(-233.141);
lst_double.push_back(-INFINITY);
lst_double.push_back(0);
lst_double.push_back(347589.19454);
std::cout << "For a double list lst_double : ";
std::cout << std::endl << "lst_double = { ";
for (ft::list<double>::iterator it = lst_double.begin(); it != lst_double.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_double.sort();
std::cout << "lst_double.sort();" << std::endl;
std::cout << "Now lst_double : ";
std::cout << std::endl << "lst_double = { ";
for (ft::list<double>::iterator it = lst_double.begin(); it != lst_double.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<std::string> lst_string;
lst_string.push_back("coucou8");
lst_string.push_back("coucou1");
lst_string.push_back("coucou4");
lst_string.push_back("coucou4");
lst_string.push_back("coucou2");
lst_string.push_back("coucou1");
lst_string.push_back("coucou9");
lst_string.push_back("coucou0");
lst_string.push_back("coucou6");
std::cout << "For a std::string list lst_string : ";
std::cout << std::endl << "lst_string = { ";
for (ft::list<std::string>::iterator it = lst_string.begin(); it != lst_string.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_string.sort();
std::cout << "lst_string.sort();" << std::endl;
std::cout << "Now lst_string : ";
std::cout << std::endl << "lst_string = { ";
for (ft::list<std::string>::iterator it = lst_string.begin(); it != lst_string.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "sort with condition :" << COLOR_RESET << std::endl;
std::cout << "Conditition superior_comp = return (lvalue > rvalue);" << std::endl;
ft::list<int> lst_int_condition;
lst_int_condition.push_back(4);
lst_int_condition.push_back(-8392454);
lst_int_condition.push_back(3849);
lst_int_condition.push_back(-9000);
lst_int_condition.push_back(-2147483648);
lst_int_condition.push_back(2147483647);
lst_int_condition.push_back(0);
std::cout << "For a int list lst_int_condition : ";
std::cout << std::endl << "lst_int_condition = { ";
for (ft::list<int>::iterator it = lst_int_condition.begin(); it != lst_int_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_int_condition.sort(superior_comp<int>);
std::cout << "lst_int_condition.sort(superior_comp);" << std::endl;
std::cout << "Now lst_int_condition : ";
std::cout << std::endl << "lst_int_condition = { ";
for (ft::list<int>::iterator it = lst_int_condition.begin(); it != lst_int_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<std::string> lst_string_condition;
lst_string_condition.push_back("coucou8");
lst_string_condition.push_back("coucou1");
lst_string_condition.push_back("coucou4");
lst_string_condition.push_back("coucou4");
lst_string_condition.push_back("coucou2");
lst_string_condition.push_back("coucou1");
lst_string_condition.push_back("coucou9");
lst_string_condition.push_back("coucou0");
lst_string_condition.push_back("coucou6");
std::cout << "For a std::string list lst_string_condition : " << std::endl;
lst_string_condition.sort(superior_comp<std::string>);
std::cout << "lst_string_condition.sort(superior_comp);" << std::endl;
std::cout << "Now lst_string_condition : ";
std::cout << std::endl << "lst_string_condition = { ";
for (ft::list<std::string>::iterator it = lst_string_condition.begin(); it != lst_string_condition.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_operations_sort_std();
}
// a binary predicate implemented as a function:
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }
// a binary predicate implemented as a class:
struct is_near {
bool operator() (double first, double second)
{ return (abs(first-second)<5.0); }
};
static void test_operations_unique_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_CYAN << "Test unique " << std::endl << std::endl;
std::cout << COLOR_YELLOW << "unique without condition :" << COLOR_RESET << std::endl;
std::list<int> lst_nums;
lst_nums.push_back(1);
lst_nums.push_back(1);
lst_nums.push_back(2);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(4);
lst_nums.push_back(5);
lst_nums.push_back(6);
lst_nums.push_back(6);
lst_nums.push_back(7);
lst_nums.push_back(8);
lst_nums.push_back(9);
lst_nums.push_back(9);
std::cout << "For a int list lst_nums : ";
std::cout << std::endl << "lst_nums = { ";
for (std::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.unique();
std::cout << "lst_nums.unique();" << std::endl << std::endl;
std::cout << "Now lst_nums = ";
std::cout << std::endl << "lst_nums = { ";
for (std::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<int> lst_nums2;
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
std::cout << "For a int list lst_nums2 : ";
std::cout << std::endl << "lst_nums2 = { ";
for (std::list<int>::iterator it = lst_nums2.begin(); it != lst_nums2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums2.unique();
std::cout << "lst_nums2.unique();" << std::endl << std::endl;
std::cout << "Now lst_nums2 = ";
std::cout << std::endl << "lst_nums2 = { ";
for (std::list<int>::iterator it = lst_nums2.begin(); it != lst_nums2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "unique with condition :" << COLOR_RESET << std::endl;
std::list<float> lst_floats;
lst_floats.push_back(2.72);
lst_floats.push_back(3.14);
lst_floats.push_back(12.15);
lst_floats.push_back(12.77);
lst_floats.push_back(15.3);
lst_floats.push_back(72.25);
lst_floats.push_back(73.0);
lst_floats.push_back(73.35);
std::cout << "For a float list lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (std::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_floats.unique(same_integral_part);
std::cout << "lst_floats.unique(same_integral_part);" << std::endl << std::endl;
std::cout << "Now lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (std::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_floats.unique(is_near());
std::cout << "lst_floats.unique(is_near());" << std::endl << std::endl;
std::cout << "Now lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (std::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
static void test_operations_unique(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test unique " << std::endl << std::endl;
std::cout << COLOR_YELLOW << "unique without condition :" << COLOR_RESET << std::endl;
ft::list<int> lst_nums;
lst_nums.push_back(1);
lst_nums.push_back(1);
lst_nums.push_back(2);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(3);
lst_nums.push_back(4);
lst_nums.push_back(5);
lst_nums.push_back(6);
lst_nums.push_back(6);
lst_nums.push_back(7);
lst_nums.push_back(8);
lst_nums.push_back(9);
lst_nums.push_back(9);
std::cout << "For a int list lst_nums : ";
std::cout << std::endl << "lst_nums = { ";
for (ft::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.unique();
std::cout << "lst_nums.unique();" << std::endl << std::endl;
std::cout << "Now lst_nums = ";
std::cout << std::endl << "lst_nums = { ";
for (ft::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<int> lst_nums2;
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
lst_nums2.push_back(1);
std::cout << "For a int list lst_nums2 : ";
std::cout << std::endl << "lst_nums2 = { ";
for (ft::list<int>::iterator it = lst_nums2.begin(); it != lst_nums2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums2.unique();
std::cout << "lst_nums2.unique();" << std::endl << std::endl;
std::cout << "Now lst_nums2 = ";
std::cout << std::endl << "lst_nums2 = { ";
for (ft::list<int>::iterator it = lst_nums2.begin(); it != lst_nums2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "unique with condition :" << COLOR_RESET << std::endl;
ft::list<float> lst_floats;
lst_floats.push_back(2.72);
lst_floats.push_back(3.14);
lst_floats.push_back(12.15);
lst_floats.push_back(12.77);
lst_floats.push_back(15.3);
lst_floats.push_back(72.25);
lst_floats.push_back(73.0);
lst_floats.push_back(73.35);
std::cout << "For a float list lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (ft::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_floats.unique(same_integral_part);
std::cout << "lst_floats.unique(same_integral_part);" << std::endl << std::endl;
std::cout << "Now lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (ft::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_floats.unique(is_near());
std::cout << "lst_floats.unique(is_near());" << std::endl << std::endl;
std::cout << "Now lst_floats : ";
std::cout << std::endl << "lst_floats = { ";
for (ft::list<float>::iterator it = lst_floats.begin(); it != lst_floats.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_operations_unique_std();
}
bool is_odd(int n) { return ((n % 2) != 0); };
bool is_neg(int n) { return (n < 0); };
void test_operations_remove_std()
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"remove :" << COLOR_RESET << std::endl << std::endl;
std::list<int> lst_numbers;
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
std::cout << "For a int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (std::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_numbers.remove(42);
std::cout << "lst_numbers.remove(42);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (std::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_numbers.remove(69);
std::cout << "lst_numbers.remove(69);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (std::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"remove_if :" << COLOR_RESET << std::endl << std::endl;
std::list<int> lst_nums;
lst_nums.push_back(-4355);
lst_nums.push_back(4573);
lst_nums.push_back(-2267);
lst_nums.push_back(3468);
lst_nums.push_back(2351);
lst_nums.push_back(-1112);
lst_nums.push_back(-6356);
lst_nums.push_back(6832);
lst_nums.push_back(4548);
lst_nums.push_back(-3252);
lst_nums.push_back(-5420);
lst_nums.push_back(2232);
std::cout << "For a int list : ";
std::cout << std::endl << "lst_nums = { ";
for (std::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.remove_if(is_odd);
std::cout << "lst_nums.remove_if(is_odd);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_nums = { ";
for (std::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.remove_if(is_neg);
std::cout << "lst_nums.remove_if(is_neg);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_nums = { ";
for (std::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_operations_remove()
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test operation remove | remove_if " << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"remove :" << COLOR_RESET << std::endl << std::endl;
ft::list<int> lst_numbers;
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
lst_numbers.push_back(42);
lst_numbers.push_back(69);
std::cout << "For a int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (ft::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_numbers.remove(42);
std::cout << "lst_numbers.remove(42);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (ft::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_numbers.remove(69);
std::cout << "lst_numbers.remove(69);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_numbers = { ";
for (ft::list<int>::iterator it = lst_numbers.begin(); it != lst_numbers.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"remove_if :" << COLOR_RESET << std::endl << std::endl;
ft::list<int> lst_nums;
lst_nums.push_back(-4355);
lst_nums.push_back(4573);
lst_nums.push_back(-2267);
lst_nums.push_back(3468);
lst_nums.push_back(2351);
lst_nums.push_back(-1112);
lst_nums.push_back(-6356);
lst_nums.push_back(6832);
lst_nums.push_back(4548);
lst_nums.push_back(-3252);
lst_nums.push_back(-5420);
lst_nums.push_back(2232);
std::cout << "For a int list : ";
std::cout << std::endl << "lst_nums = { ";
for (ft::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.remove_if(is_odd);
std::cout << "lst_nums.remove_if(is_odd);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_nums = { ";
for (ft::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_nums.remove_if(is_neg);
std::cout << "lst_nums.remove_if(is_neg);" << std::endl << std::endl;
std::cout << "Now int list : ";
std::cout << std::endl << "lst_nums = { ";
for (ft::list<int>::iterator it = lst_nums.begin(); it != lst_nums.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_operations_remove_std();
}
static void test_operations_splice_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "splice" << COLOR_RESET << std::endl;
std::list<int> mylist1, mylist2;
std::list<int>::iterator it;
// set some initial values:
for (int i=1; i<=4; ++i)
mylist1.push_back(i); // mylist1: 1 2 3 4
for (int i=1; i<=3; ++i)
mylist2.push_back(i*10); // mylist2: 10 20 30
it = mylist1.begin();
++it; // points to 2
mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element)
mylist2.splice (mylist2.begin(),mylist1, it);
// mylist1: 1 10 20 30 3 4
// mylist2: 2
// "it" is now invalid.
it = mylist1.begin();
std::advance(it,3); // "it" points now to 30
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20
std::cout << "mylist1 contains:";
for (it=mylist1.begin(); it!=mylist1.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "mylist2 contains:";
for (it=mylist2.begin(); it!=mylist2.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
next_test();
}
void test_operations_splice(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test operations splice" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "splice | single" << COLOR_RESET << std::endl;
ft::list<int> mylist1, mylist2;
ft::list<int>::iterator it;
// set some initial values:
for (int i=1; i<=4; ++i)
mylist1.push_back(i); // mylist1: 1 2 3 4
for (int i=1; i<=3; ++i)
mylist2.push_back(i*10); // mylist2: 10 20 30
it = mylist1.begin();
++it; // points to 2
mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element)
mylist2.splice (mylist2.begin(),mylist1, it);
// mylist1: 1 10 20 30 3 4
// mylist2: 2
// "it" is now invalid.
it = mylist1.begin();
it++;
it++;
it++;
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20
std::cout << "mylist1 contains:";
for (it=mylist1.begin(); it!=mylist1.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "mylist2 contains:";
for (it=mylist2.begin(); it!=mylist2.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
test_operations_splice_std();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mapIterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/22 15:52:21 by jereligi #+# #+# */
/* Updated: 2021/04/03 11:47:39 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MAPITERATOR_HPP
#define MAPITERATOR_HPP
#include "../../utils.hpp"
#include "../map.hpp"
namespace ft
{
template <typename T, typename node_type>
class mapIterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef value_type* pointer;
typedef std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
mapIterator(void) : _map(NULL) {
};
mapIterator(node_type *src) {
_map = src;
};
mapIterator(const mapIterator &src) {
_map = src._map;
};
virtual ~mapIterator() {};
mapIterator &operator=(mapIterator const &src) {
_map = src._map;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator ==(mapIterator const& src) const {
return (_map == src._map);
};
bool operator !=(mapIterator const& src) const {
return (_map != src._map);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
mapIterator operator ++()
{
if (_map->right != NULL)
{
_map = _map->right;
while (_map->left != NULL)
_map = _map->left;
}
else
{
node_type *child = _map;
_map = _map->parent;
while (_map->right == child)
{
child = _map;
_map = _map->parent;
}
}
return (*this);
};
mapIterator operator --()
{
if (_map->left != NULL)
{
_map = _map->left;
while (_map->right != NULL)
_map = _map->right;
}
else
{
node_type *child = _map;
_map = _map->parent;
while (_map && child == _map->left)
{
child = _map;
_map = _map->parent;
}
}
return (*this);
};
mapIterator operator ++(int) // a++
{
mapIterator temp = *this;
++(*this);
return (temp);
};
mapIterator operator --(int) // a--
{
mapIterator temp = *this;
--(*this);
return (temp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
reference operator *() {
return (_map->data);
};
const_reference operator *() const {
return (_map->data);
};
pointer operator ->() {
return (&_map->data);
};
pointer operator ->() const {
return (&_map->data);
};
/*******************************************
***** personnal getter function *****
***** *****
*******************************************/
// void far_left(void)
// {
// while (get_left(_map))
// _map = get_left(_map);
// }
// void far_right(void)
// {
// while (get_right(_map))
// _map = get_right(_map);
// _map = _map->parent;
// }
node_type *get_map(void) const {
return (_map);
};
private:
node_type *_map;
};
}
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tester_list.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 15:29:38 by jereligi #+# #+# */
/* Updated: 2021/04/03 15:00:53 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
#include "test_essentials.cpp"
#include "test_capacity.cpp"
#include "test_iterator.cpp"
#include "test_modifiers.cpp"
#include "test_operations.cpp"
#include "test_operator_non_member.cpp"
#include <cmath>
void next_test()
{
std::string buf;
std::cout << COLOR_GREEN << "press enter for continu..." << COLOR_RESET;
std::getline (std::cin, buf);
std::cout << clear_terminal << std::endl;
}
int main(void)
{
test_essentials();
test_capacity();
test_iterator();
test_operator_over_ite();
test_constructors();
test_modifiers_one();
test_modifiers_two();
test_operations_splice();
test_operations_remove();
test_operations_unique();
test_operations_sort();
test_operations_reverse();
test_non_member_ope();
test_operations_merge();
return (0);
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/25 11:06:31 by jereligi #+# #+# */
/* Updated: 2021/04/03 14:58:47 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ITERATOR_HPP
#define ITERATOR_HPP
#include "../../utils.hpp"
namespace ft
{
template <typename T, typename Node>
class Iterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
Iterator(void) {};
Iterator(Node* src) { _node = src; };
Iterator(Iterator const &src) { *this = src; } ;
virtual ~Iterator() {};
Iterator &operator=(Iterator const &src) {
_node = src._node;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator==(Iterator const& src) const {
return (_node == src._node);
};
bool operator!=(Iterator const& src) const {
return (_node != src._node);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
Iterator operator++() {
_node = _node->next;
return (*this);
};
Iterator operator++(int) {
Iterator tmp = *this;
++(*this);
return (tmp);
};
Iterator operator--() {
_node = _node->prev;
return (*this);
};
Iterator operator--(int) {
Iterator tmp = *this;
--(*this);
return (tmp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
const_reference operator*() const {
return (_node->val);
};
reference operator*() {
return (_node->val);
};
Node* operator->() {
return (_node);
};
Node* operator->() const {
return (_node);
};
private:
Node *_node;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_capacity.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 15:45:34 by jereligi #+# #+# */
/* Updated: 2021/03/17 15:53:23 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
void test_capacity_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << "For a string list : { need, to, finish, this, project }" << std::endl << std::endl;
std::list<std::string> lst;
lst.push_back("need");
lst.push_back("to");
lst.push_back("finish");
lst.push_back("this");
lst.push_back("project");
std::cout << "lst.size() = " << COLOR_GREEN << lst.size() << COLOR_RESET << std::endl;
std::cout << "lst.empty() = " << COLOR_GREEN << std::boolalpha << lst.empty() << COLOR_RESET << std::endl;
std::cout << "lst.max_size() = " << COLOR_GREEN << lst.max_size() << COLOR_RESET << std::endl << std::endl;
std::cout << "For an empty string list :" << std::endl;
std::list<std::string> lst2;
std::cout << "lst2.size() = " << COLOR_GREEN << lst2.size() << COLOR_RESET << std::endl;
std::cout << "lst2.empty() = " << COLOR_GREEN << std::boolalpha << lst2.empty() << COLOR_RESET << std::endl << std::endl;
next_test();
}
void test_capacity(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test capacity | size | empty | max_size " << COLOR_RESET << std::endl;
std::cout << "For a string list : { need, to, finish, this, project }" << std::endl;
ft::list<std::string> lst;
lst.push_back("need");
lst.push_back("to");
lst.push_back("finish");
lst.push_back("this");
lst.push_back("project");
std::cout << "lst.size() = " << COLOR_GREEN << lst.size() << COLOR_RESET << std::endl;
std::cout << "lst.empty() = " << COLOR_GREEN << std::boolalpha << lst.empty() << COLOR_RESET << std::endl;
std::cout << "lst.max_size() = " << COLOR_GREEN << lst.max_size() << COLOR_RESET << std::endl << std::endl;
std::cout << "For an empty string list :" << std::endl;
ft::list<std::string> lst2;
std::cout << "lst2.size() = " << COLOR_GREEN << lst2.size() << COLOR_RESET << std::endl;
std::cout << "lst2.empty() = " << COLOR_GREEN << std::boolalpha << lst2.empty() << COLOR_RESET << std::endl << std::endl;
test_capacity_std();
}<file_sep>#include "list.hpp"
#include <iostream>
bool single_digit (const int& value) { return (value<13); }
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }
int main(void)
{
ft::list<int> l(2,42);
ft::list<int> l2(2,8);
ft::list<int> l3(1, 12);
ft::list<int>::iterator it;
for (it = l.begin(); it != l.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl << std::endl;
l.push_back(43);
l.push_front(41);
l.push_front(40);
for (it = l.begin(); it != l.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl << std::endl;
l.insert(l.begin(), 39);
l.insert(++(l.begin()), 38);
l.push_front(37);
std::cout << "size : " << l.size() << std::endl;
for (it = l.begin(); it != l.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl;
l.insert(--(l.end()), 3, 59);
std::cout << "size : " << l.size() << std::endl;
for (it = l.begin(); it != l.end(); it++)
std::cout << *it << std::endl;
ft::list<int> l1(2,1);
std::cout << std::endl << "l1 : " << std::endl;
l1.insert(++(l1.begin()), ++(l.begin()), l.end());
for (it = l1.begin(); it != l1.end(); it++)
std::cout << *it << std::endl;
l1.erase(++(l1.begin()));
l1.erase(++(l1.begin()));
// l1.erase(++(l1.begin()), l1.end());
std::cout << std::endl << "l2 : " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.splice(l2.begin(), l3, l3.begin());
std::cout << std::endl << "l2 : " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
ft::list<int> l4(2, 70);
l4.push_back(71);
l4.push_back(75);
l2.splice(l2.end(), l4);
std::cout << std::endl << "l2 splice: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.push_back(70);
std::cout << std::endl << "l2 push: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl << "l4 " << std::endl;
for (it = l4.begin(); it != l4.end(); it++)
std::cout << *it << std::endl;
// l2.remove_if(single_digit);
l2.unique();
std::cout << std::endl << "l2 unique: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.sort();
std::cout << std::endl << "l2 sort: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.reverse();
std::cout << std::endl << "l2 reverse: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
ft::list<int> l7(l2);
l7.push_back(30);
std::cout << std::endl << "l7 : " << std::endl;
for (it = l7.begin(); it != l7.end(); it++)
std::cout << *it << std::endl;
ft::swap(l2, l7);
l2.sort();
l7.sort();
std::cout << std::endl << "l2 swap: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl << "l7 : " << std::endl;
for (it = l7.begin(); it != l7.end(); it++)
std::cout << *it << std::endl;
l2.merge(l7);
std::cout << std::endl << "l2 merge: " << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
std::cout << std::endl << "l7 : " << std::endl;
for (it = l7.begin(); it != l7.end(); it++)
std::cout << *it << std::endl;
std::cout << (l7 == l2) << std::endl;
l2.clear();
l7.clear();
l2.push_back(2);
l2.push_back(4);
l2.push_back(6);
l7.push_back(2);
l7.push_back(5);
l7.push_back(6);
std::cout << "== : " << (l7 == l2) << std::endl;
std::cout << "< : " << (l2 < l7) << std::endl;
std::cout << "<= : " << (l2 <= l7) << std::endl;
std::cout << "> :" << (l7 > l2) << std::endl;
std::cout << ">= :" << (l7 >= l2) << std::endl;
std::cout << "> :" << (l2 > l7) << std::endl;
return 0;
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/04 11:46:10 by jereligi #+# #+# */
/* Updated: 2021/04/06 12:05:53 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MAP_HPP
#define MAP_HPP
#include "../utils.hpp"
#include "./iterator/mapIterator.hpp"
#include "./iterator/mapConstIterator.hpp"
#include "./iterator/mapReverseIterator.hpp"
#include "./iterator/mapConstReverseIterator.hpp"
#include <limits>
#ifndef __APPLE__
# define __APPLE__ 0
#endif
template <typename Tpair>
struct mapNode
{
private:
bool _unused;
#if __APPLE__ == 0
int _unused_for_linux;
#endif
public:
Tpair data;
mapNode *parent;
mapNode *left;
mapNode *right;
};
template <typename T>
mapNode<T> *get_right(mapNode<T> *node) {
return (node->right);
}
template <typename T>
mapNode<T> *get_left(mapNode<T> *node) {
return (node->left);
}
template <typename T>
mapNode<T> *get_parent(mapNode<T> *node) {
return (node->parent);
}
template <typename T>
mapNode<T> *far_right(mapNode<T> *node) {
while (node->right != NULL)
node = node->right;
return (node);
}
template <typename T>
mapNode<T> *far_left(mapNode<T> *node) {
while (node->left != NULL)
node = node->left;
return (node);
}
template <typename Tpair>
std::ostream &operator<<(std::ostream &o, mapNode<Tpair> const &i)
{
std::cout << \
"curr = " << i.get_curr() << std::endl << \
"_top = " << i.get_top() << std::endl << \
"_left = " << i.get_left() << std::endl << \
"_right = " << i.get_right() << std::endl << \
"_keyval : " << std::endl << i.get_pair();
return (o);
};
namespace ft
{
template< class T >
struct less
{
bool operator()( const T& lhs, const T& rhs ) const
{
return lhs < rhs;
}
};
/*******************************************
***** Class Pair *****
*******************************************/
template <typename Tkey, typename Tvalue>
class pair
{
public:
// default
pair(void) {};
// copy
template<class U, class V>
pair (const pair<U,V>& src)
{
this->first = src.first;
this->second = src.second;
};
// initialization
pair (const Tkey& a, const Tvalue& b) : first(a), second(b) {};
~pair() {};
pair &operator=(pair const &src)
{
this->first = src.first;
this->second = src.second;
return (*this);
};
Tkey first;
Tvalue second;
};
template <typename Tkey, typename Tvalue>
std::ostream &operator<<(std::ostream &o, pair<Tkey, Tvalue> const &i)
{
std::cout << \
"key = " << i.first << ", value = " << i.second << " ";
return (o);
};
template <class T1, class T2>
bool operator==(const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return (lhs.first == rhs.first && lhs.second == rhs.second);
}
template <class T1, class T2>
bool operator!=(const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return !(lhs == rhs);
}
template <class T1, class T2>
bool operator< (const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return lhs.first < rhs.first || (!(rhs.first < lhs.first) && lhs.second < rhs.second);
}
template <class T1, class T2>
bool operator<=(const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return !(rhs < lhs);
}
template <class T1, class T2>
bool operator> (const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return (rhs < lhs);
}
template <class T1, class T2>
bool operator>=(const pair<T1, T2> &lhs, const pair<T1, T2> &rhs) {
return !(lhs < rhs);
}
/*******************************************
***** Class Map *****
*******************************************/
template < class Tkey, // map::key_type
class Tvalue, // map::mapped_type
class Compare = ft::less<Tkey>, // map::key_compare
class Alloc = std::allocator<pair<const Tkey,Tvalue> > // map::allocator_type
>
class map
{
public:
// member type
typedef Tkey key_type;
typedef Tvalue mapped_type;
typedef ft::pair<key_type, mapped_type> value_type;
typedef mapNode<value_type> node_type;
typedef Compare key_compare;
typedef std::allocator<value_type> allocator_type;
typedef value_type & reference;
typedef reference const_reference;
typedef value_type * pointer;
typedef const pointer const_pointer;
typedef mapIterator<value_type, node_type> iterator;
typedef mapConstIterator<value_type, node_type> const_iterator;
typedef mapReverseIterator<value_type, node_type> reverse_iterator;
typedef mapConstReverseIterator<value_type, node_type> const_reverse_iterator;
typedef size_t size_type;
typedef std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
// empty
explicit map (const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type())
{
_map = new node_type();
_map->left = NULL;
_map->right = NULL;
_map->parent = NULL;
_size = 0;
_alloc = alloc;
_key_comp = comp;
}
// range
template <class InputIterator>
map (InputIterator first, InputIterator last, const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type(),
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
_map = new node_type();
_map->left = NULL;
_map->right = NULL;
_map->parent = NULL;
_size = 0;
_alloc = alloc;
_key_comp = comp;
insert(first, last);
}
// copy / assign
map& operator=(map const & x)
{
if (_size > 0)
clear();
if (x.size() > 0)
this->insert(x.begin(), x.end());
return (*this);
}
// // copy
map (const map& x){
_map = new node_type();
_map->left = NULL;
_map->right = NULL;
_map->parent = NULL;
_size = 0;
_alloc = allocator_type();
_key_comp = key_compare();
*this = x;
}
virtual ~map()
{
if (empty() == 0)
clear();
}
/*******************************************
***** Iterators *****
*******************************************/
iterator begin() {
return (iterator(far_left(_map)));
}
const_iterator begin() const {
return (const_iterator(far_left(_map)));
}
iterator end() {
return (iterator(far_right(_map)));
}
const_iterator end() const {
return (const_iterator(far_right(_map)));
}
reverse_iterator rbegin() {
return (reverse_iterator(--end()));
}
const_reverse_iterator rbegin() const {
return (const_reverse_iterator(rbegin()));
}
reverse_iterator rend() {
return (reverse_iterator(begin()));
}
const_reverse_iterator rend() const {
return (const_reverse_iterator(begin()));
}
/*******************************************
***** Capacity *****
*******************************************/
bool empty() const {
if (_size > 0)
return (0);
return (1);
}
size_type size() const {
return (_size);
}
size_type max_size() const {
return (std::numeric_limits<difference_type>::max() / (sizeof(node_type) / 2 ?: 1));
}
/*******************************************
***** Element access *****
*******************************************/
mapped_type& operator[](const key_type& k)
{
iterator it = find(k);
if (it != end())
return ((*it).second);
return ((insert(value_type(k, mapped_type()))).first->second);
}
/*******************************************
***** Modifiers *****
*******************************************/
//single element
pair<iterator,bool> insert (const value_type& val)
{
ft::pair<iterator, bool> ret;
if (_size > 0 && (count(val.first)) == 1)
{
ret.second = false;
return (ret);
}
value_type new_pair(val);
node_type *new_node = new node_type();
new_node->data = new_pair;
new_node->left = NULL;
new_node->right = NULL;
new_node->parent = NULL;
_btree_add(new_node);
ret.first = find(val.first);
return (ret);
}
// with hint
iterator insert (iterator position, const value_type& val)
{
static_cast<void>(position);
return (insert(val).first);
}
//range
template <class InputIterator>
void insert (InputIterator first, InputIterator last,
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
while (first != last)
{
insert(*first);
first++;
}
}
void erase (iterator position) {
erase((*position).first);
}
size_type erase (const key_type& k)
{
iterator it = find(k);
node_type *node_rm = it.get_map();
node_type **parent = &node_rm->parent;
node_type *child;
node_type *node_replace;
// ----------------- No child -----------------------
if (node_rm->left == NULL && node_rm->right == NULL)
{
// std::cout << "No child" << std::endl;
if ((*parent)->left == node_rm)
(*parent)->left = NULL;
else
(*parent)->right = NULL;
delete node_rm;
}
// ----------------- One child ----------------------
else if (node_rm->left == NULL || node_rm->right == NULL)
{
// std::cout << "One child" << std::endl;
if (node_rm->left)
child = node_rm->left;
else
child = node_rm->right;
child->parent = *parent;
if (node_rm->parent)
{
if ((*parent)->left == node_rm)
(*parent)->left = child;
else
(*parent)->right = child;
}
else
{
_map = child;
}
delete node_rm;
}
// ----------------- Two child ---------------------
else
{
// std::cout << "Two child" << std::endl;
if (node_rm->parent == NULL) // root
{
node_replace = node_rm->left;
while (node_replace->right)
node_replace = node_replace->right;
if (node_replace == node_rm->left) // no under child
{
node_replace->parent = node_rm->parent;
node_replace->right = node_rm->right;
node_rm->right->parent = node_replace;
if (node_rm->parent)
{
if ((*parent)->right == node_rm)
(*parent)->right = node_replace;
else
(*parent)->left = node_replace;
}
else
{
_map = node_replace;
}
}
else // under child
{
// std::cout << "Under child" << std::endl;
node_replace->parent->right = NULL;
node_replace->parent = node_rm->parent;
node_replace->left = node_rm->left;
node_replace->right = node_rm->right;
node_rm->right->parent = node_replace;
node_rm->left->parent = node_replace;
if (node_rm->parent)
{
if ((*parent)->left == node_rm)
(*parent)->left = node_replace;
else
(*parent)->right = node_replace;
}
else
{
_map = node_replace;
}
}
}
else // no root
{
node_replace = node_rm->right;
while (node_replace->left)
node_replace = node_replace->left;
std::cout << "node test :" << node_replace->data.first << std::endl;
if (node_replace == node_rm->right) // no under child
{
node_replace->parent = node_rm->parent;
node_replace->left = node_rm->left;
node_rm->left->parent = node_replace;
if (node_rm->parent)
{
if ((*parent)->left == node_rm)
(*parent)->left = node_replace;
else
(*parent)->right = node_replace;
}
else
{
_map = node_replace;
}
}
else // under child
{
// std::cout << "Under child" << std::endl;
node_replace->parent->left = node_replace->right;
node_replace->right->parent = node_replace->parent;
node_replace->right = node_rm->right;
node_replace->right->parent = node_replace;
node_replace->parent = node_rm->parent;
node_replace->left = node_rm->left;
node_replace->left->parent = node_replace;
if (node_rm->parent)
{
if ((*parent)->left == node_rm)
(*parent)->left = node_replace;
else
(*parent)->right = node_replace;
}
else
{
_map = node_replace;
}
}
}
delete node_rm;
}
_size--;
return (1);
}
void erase (iterator first, iterator last)
{
while (first != last)
erase(first++);
}
void swap (map& x)
{
map tmp;
tmp._copy_data(x);
x._copy_data(*this);
this->_copy_data(tmp);
}
void clear()
{
node_type *sentinel = far_right(_map);
if (_size == 0)
return ;
sentinel->parent->right = NULL;
_btree_clear(_map);
_map = sentinel;
_size = 0;
}
/*******************************************
***** Observers *****
*******************************************/
key_compare key_comp() const {
return (key_compare());
}
class value_compare
{
public:
typedef bool result_type;
typedef value_type first_argument_type;
typedef value_type second_argument_type;
Compare comp;
value_compare(Compare c) : comp(c) {};
virtual ~value_compare() {};
bool operator() (const value_type& x, const value_type& y) const
{
return (comp(x.first, y.first));
}
};
value_compare value_comp() const {
return (value_compare(key_compare()));
}
/*******************************************
***** Map operations *****
*******************************************/
iterator find(const key_type& k)
{
iterator it = begin();
iterator ite = end();
while (it != ite)
{
if (!_key_comp((*it).first, k) && !_key_comp(k, (*it).first))
break ;
it++;
}
return (it);
}
const_iterator find (const key_type& k) const
{
const_iterator it = begin();
const_iterator ite = end();
while (it != ite)
{
if (!_key_comp((*it).first, k) && !_key_comp(k, (*it).first))
break ;
it++;
}
return (it);
}
size_type count (const key_type& k) const
{
size_t ret = 0;
const_iterator it = begin();
const_iterator ite = end();
while (it != ite)
{
if (!_key_comp((*it).first, k) && !_key_comp(k, (*it).first))
{
ret++;
break ;
}
it++;
}
return (ret);
}
iterator lower_bound (const key_type& k)
{
iterator it = begin();
iterator ite = end();
while (it != ite)
{
if (!_key_comp((*it).first, k))
break ;
it++;
}
return (it);
}
const_iterator lower_bound (const key_type& k) const
{
const_iterator it = begin();
const_iterator ite = end();
while (it != ite)
{
if (!_key_comp((*it).first, k))
break ;
it++;
}
return (it);
}
iterator upper_bound (const key_type& k)
{
iterator it = begin();
iterator ite = end();
while (it != ite)
{
if (!_key_comp(k, (*it).first))
break ;
it++;
}
return (it);
}
const_iterator upper_bound (const key_type& k) const
{
const_iterator it = begin();
const_iterator ite = end();
while (it != ite)
{
if (!_key_comp(k, (*it).first))
break ;
it++;
}
return (it);
}
pair<const_iterator,const_iterator> equal_range (const key_type& k) const
{
pair <const_iterator, const_iterator> ret;
ret.first = lower_bound(k);
ret.second = upper_bound(k);
return (ret);
}
pair<iterator,iterator> equal_range (const key_type& k)
{
pair <iterator, iterator> ret;
ret.first = lower_bound(k);
ret.second = upper_bound(k);
return (ret);
}
private:
mapNode<value_type> *_map;
size_type _size;
allocator_type _alloc;
key_compare _key_comp;
void _btree_add(node_type *new_node)
{
node_type **parent = &_map;
node_type **node = &_map;
node_type *sentinel = far_right(_map);
bool side_left = -1;
while (*node && *node != sentinel)
{
parent = node;
side_left = _key_comp(new_node->data.first, (*node)->data.first);
node = (side_left ? &(*node)->left : &(*node)->right);
}
if (*node == NULL)
{
new_node->parent = (*parent);
*node = new_node;
}
else // if (*node == sentinel)
{
*node = new_node;
new_node->parent = sentinel->parent;
sentinel->parent = far_right(new_node);
far_right(new_node)->right = sentinel;
}
_size++;
};
void _btree_clear(node_type *node)
{
if (node == NULL)
return ;
_btree_clear(node->left);
_btree_clear(node->right);
delete node;
};
void _copy_data(map &src)
{
this->clear();
node_type *tmp = _map;
_map = src._map;
_size = src._size;
_alloc = src._alloc;
_key_comp = src._key_comp;
src._map = tmp;
src._size = 0;
tmp = NULL;
}
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* const_reverse_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/01 16:07:03 by jereligi #+# #+# */
/* Updated: 2021/03/03 16:08:13 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CONST_REVERSE_ITERATOR_HPP
#define CONST_REVERSE_ITERATOR_HPP
#include "iterator.hpp"
#include "reverse_iterator.hpp"
namespace ft
{
template <typename T>
class const_reverse_iterator
{
public:
static const bool is_iterator = true;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
const_reverse_iterator(void) {};
const_reverse_iterator(const T* src) { _ptr = src; };
const_reverse_iterator(Iterator<T> const &src) { _ptr = src.operator->(); };
const_reverse_iterator(reverse_iterator<T> const &src) { _ptr = src.operator->(); };
const_reverse_iterator(const_reverse_iterator const &src) { *this = src; } ;
virtual ~const_reverse_iterator() {};
const_reverse_iterator &operator=(const_reverse_iterator const &src) {
_ptr = src.operator->();
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != | > | >= | < | <= *****
*******************************************/
bool operator==(const_reverse_iterator const& src) const {
return (_ptr == src._ptr);
};
bool operator!=(const_reverse_iterator const& src) const {
return (_ptr != src._ptr);
};
bool operator>(const_reverse_iterator const& src) const {
return (_ptr < src._ptr);
};
bool operator>=(const_reverse_iterator const& src) const {
return (_ptr <= src._ptr);
};
bool operator<(const_reverse_iterator const& src) const {
return (_ptr > src._ptr);
};
bool operator<=(const_reverse_iterator const& src) const {
return (_ptr >= src._ptr);
};
/*******************************************
***** Operator Arithmetics *****
***** + | - | ++ | -- | += | -= *****
*******************************************/
const_reverse_iterator operator+(difference_type src) {
return (const_reverse_iterator(_ptr - src));
};
const_reverse_iterator operator-(difference_type src) {
return (const_reverse_iterator(_ptr + src));
};
difference_type operator+(const_reverse_iterator src) {
return (_ptr - src._ptr);
};
difference_type operator-(const_reverse_iterator src) {
return (_ptr + src._ptr);
};
const_reverse_iterator operator++() {
_ptr--;
return (*this);
};
const_reverse_iterator operator++(int) {
_ptr--;
return (const_reverse_iterator(_ptr + 1));
};
const_reverse_iterator operator--() {
_ptr++;
return (*this);
};
const_reverse_iterator operator--(int) {
_ptr++;
return (const_reverse_iterator(_ptr - 1));
};
void operator+=(difference_type src) {
_ptr -= src;
};
void operator-=(difference_type src) {
_ptr += src;
};
/*******************************************
***** Operator deferencing *****
***** * | [] | -> *****
*******************************************/
const T& operator*() const {
return (*_ptr);
};
const T& operator[](difference_type src) const {
return (*(_ptr + src));
};
const T* operator->() {
return (_ptr);
};
const T* operator->() const {
return (_ptr);
};
private:
const T* _ptr;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* const_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/01 16:07:03 by jereligi #+# #+# */
/* Updated: 2021/04/03 14:59:22 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CONST_ITERATOR_HPP
#define CONST_ITERATOR_HPP
#include "iterator.hpp"
namespace ft
{
template <typename T, typename Node>
class const_iterator
{
public:
static const bool is_iterator = true;
typedef const T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
const_iterator(void) {};
const_iterator(const Node* src) { _node = src; };
const_iterator(Iterator<T, Node> const &src) { _node = src.operator->(); };
const_iterator(const_iterator const &src) { _node = src._node; } ;
virtual ~const_iterator() {};
const_iterator &operator=(const_iterator const &src) {
_node = src._node;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator==(const_iterator const& src) const {
return (_node == src._node);
};
bool operator!=(const_iterator const& src) const {
return (_node != src._node);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
const_iterator operator++() {
_node = _node->next;
return (*this);
};
const_iterator operator++(int) {
const_iterator tmp = *this;
++(*this);
return (tmp);
};
const_iterator operator--() {
_node = _node->prev;
return (*this);
};
const_iterator operator--(int) {
const_iterator tmp = *this;
--(*this);
return (tmp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
const_reference operator*() const {
return (_node->val);
};
// Node* const operator->() {
// return (_node);
// };
const Node* operator->() const {
return (_node);
};
private:
const Node *_node;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_modifiers.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/18 11:11:52 by jereligi #+# #+# */
/* Updated: 2021/03/18 13:42:59 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
void test_modifiers_two_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "erase | one element :" << COLOR_RESET << std::endl;
std::list<std::string> alien_hidden;
alien_hidden.push_back("👽");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("👽");
std::cout << "For a string vector alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Remove the begining alien" << std::endl;
std::cout << "alien_hidden.erase(alien_hidden.begin());" << std::endl;
alien_hidden.erase(alien_hidden.begin());
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Remove the end alien" << std::endl;
std::cout << "alien_hidden.erase(--alien_hidden.end());" << std::endl;
alien_hidden.erase(--alien_hidden.end());
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "erase | range :" << COLOR_RESET << std::endl;
std::cout << "// Remove the group of alien" << std::endl;
std::list<std::string>::iterator it_first_alien_grp = alien_hidden.begin();
std::list<std::string>::iterator it_last_alien_grp;
it_first_alien_grp++;
it_first_alien_grp++;
it_first_alien_grp++;
it_last_alien_grp = it_first_alien_grp;
it_last_alien_grp++;
it_last_alien_grp++;
it_last_alien_grp++;
std::cout << "alien_hidden.erase(it_first_alien_grp, ++it_last_alien_grp);" << std::endl;
alien_hidden.erase(it_first_alien_grp, ++it_last_alien_grp);
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "rezise :" << COLOR_RESET << std::endl;
std::cout << "// let's add some Santa girls with the resize function !" << std::endl;
alien_hidden.resize(16, "🤶");
std::cout << "alien_hidden.resize(16, \"🤶\")" << std::endl;
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "As there is only one Santa claus and one Santa girl :" << std::endl;
std::cout << "alien_hidden.resize(1, \"🎅\")" << std::endl;
std::cout << "alien_hidden.resize(2, \"🤶\")" << std::endl;
alien_hidden.resize(1, "🎅");
alien_hidden.resize(2, "🤶");
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (std::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "swap :" << COLOR_RESET << std::endl;
std::list<std::string> ticks(5, "✅");
std::list<std::string> cross(5, "❌");
std::cout << "For a string list of ticks : ";
std::cout << std::endl << "ticks = { ";
for (std::list<std::string>::iterator it = ticks.begin(); it != ticks.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For a string list of cross : ";
std::cout << std::endl << "cross = { ";
for (std::list<std::string>::iterator it = cross.begin(); it != cross.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Now lets swap it" << std::endl;
std::cout << "ticks.swap(cross);" << std::endl << std::endl;
ticks.swap(cross);
std::cout << "Now list of ticks : ";
std::cout << std::endl << "ticks = { ";
for (std::list<std::string>::iterator it = ticks.begin(); it != ticks.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "Now list of cross : : ";
std::cout << std::endl << "cross = { ";
for (std::list<std::string>::iterator it = cross.begin(); it != cross.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_modifiers_two(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test modifiers two | erase | resize | swap " << std::endl << std::endl;
std::cout << COLOR_YELLOW << "erase | one element :" << COLOR_RESET << std::endl;
ft::list<std::string> alien_hidden;
alien_hidden.push_back("👽");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("👽");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("🎅");
alien_hidden.push_back("👽");
std::cout << "For a string vector alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Remove the begining alien" << std::endl;
std::cout << "alien_hidden.erase(alien_hidden.begin());" << std::endl;
alien_hidden.erase(alien_hidden.begin());
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Remove the end alien" << std::endl;
std::cout << "alien_hidden.erase(--alien_hidden.end());" << std::endl;
alien_hidden.erase(--alien_hidden.end());
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "erase | range :" << COLOR_RESET << std::endl;
std::cout << "// Remove the group of alien" << std::endl;
ft::list<std::string>::iterator it_first_alien_grp = alien_hidden.begin();
ft::list<std::string>::iterator it_last_alien_grp;
it_first_alien_grp++;
it_first_alien_grp++;
it_first_alien_grp++;
it_last_alien_grp = it_first_alien_grp;
it_last_alien_grp++;
it_last_alien_grp++;
it_last_alien_grp++;
std::cout << "alien_hidden.erase(it_first_alien_grp, ++it_last_alien_grp);" << std::endl;
alien_hidden.erase(it_first_alien_grp, ++it_last_alien_grp);
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "rezise :" << COLOR_RESET << std::endl;
std::cout << "// let's add some Santa girls with the resize function !" << std::endl;
alien_hidden.resize(16, "🤶");
std::cout << "alien_hidden.resize(16, \"🤶\")" << std::endl;
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "As there is only one Santa claus and one Santa girl :" << std::endl;
std::cout << "alien_hidden.resize(1, \"🎅\")" << std::endl;
std::cout << "alien_hidden.resize(2, \"🤶\")" << std::endl;
alien_hidden.resize(1, "🎅");
alien_hidden.resize(2, "🤶");
std::cout << "Now alien_hidden = ";
std::cout << std::endl << "alien_hidden = { ";
for (ft::list<std::string>::iterator it = alien_hidden.begin(); it != alien_hidden.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW << "swap :" << COLOR_RESET << std::endl;
ft::list<std::string> ticks(5, "✅");
ft::list<std::string> cross(5, "❌");
std::cout << "For a string list of ticks : ";
std::cout << std::endl << "ticks = { ";
for (ft::list<std::string>::iterator it = ticks.begin(); it != ticks.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For a string list of cross : ";
std::cout << std::endl << "cross = { ";
for (ft::list<std::string>::iterator it = cross.begin(); it != cross.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Now lets swap it" << std::endl;
std::cout << "ticks.swap(cross);" << std::endl << std::endl;
ticks.swap(cross);
std::cout << "Now list of ticks : ";
std::cout << std::endl << "ticks = { ";
for (ft::list<std::string>::iterator it = ticks.begin(); it != ticks.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "Now list of cross : : ";
std::cout << std::endl << "cross = { ";
for (ft::list<std::string>::iterator it = cross.begin(); it != cross.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_modifiers_two_std();
}
void test_modifiers_one_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"clear :" << COLOR_RESET << std::endl << std::endl;
std::list<std::string> lst;
lst.push_back("mr");
lst.push_back("robot");
lst.push_back("is");
lst.push_back("a");
lst.push_back("very");
lst.push_back("good");
lst.push_back("series.");
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (std::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
lst.clear();
std::cout << "lst.clear();"<< std::endl << std::endl;
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (std::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
lst.clear();
std::cout << "lst.clear();"<< std::endl << std::endl;
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (std::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"assign :" << COLOR_RESET << std::endl << std::endl;
std::list<std::string> lst_empty;
std::list<std::string> lst_watch_brands;
lst_watch_brands.push_back("rolex");
lst_watch_brands.push_back("lip");
lst_watch_brands.push_back("montblanc");
lst_watch_brands.push_back("cartier");
lst_watch_brands.push_back("TAG_Heuer");
std::cout << "For an empty string list : ";
std::cout << std::endl << "lst_empty = { ";
for (std::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "With an string list lst_watch_brands : ";
std::cout << std::endl << "lst = { ";
for (std::list<std::string>::iterator it = lst_watch_brands.begin(); it != lst_watch_brands.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_empty.assign(10, "empty");
std::cout << "lst_empty.assign(10, \"empty\");" << std::endl;
std::cout << std::endl << "lst_empty = { ";
for (std::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_empty.assign(lst_watch_brands.begin(), lst_watch_brands.end());
std::cout << "lst_empty.assign(lst_watch_brands.begin(), lst_watch_brands.end());" << std::endl;
std::cout << std::endl << "lst_empty = { ";
for (std::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert | single element :" << COLOR_RESET << std::endl << std::endl;
std::list<std::string> red_apples(10, "🍎");
std::cout << "For red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (std::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Inserting green apple at the begining of the list" << std::endl;
std::cout << "red_apples.insert(red_apples.begin(), \"🍏\")" << std::endl;
red_apples.insert(red_apples.begin(), "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (std::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Inserting green apple at the end of the list" << std::endl;
std::cout << "red_apples.insert(red_apples.end(), \"🍏\")" << std::endl;
red_apples.insert(red_apples.end(), "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (std::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<std::string>::iterator it_middle = red_apples.begin();
it_middle++;
it_middle++;
it_middle++;
it_middle++;
it_middle++;
it_middle++;
std::cout << "// Inserting green apple at the middle of the list" << std::endl;
std::cout << "red_apples.insert(it_middle, \"🍏\")" << std::endl;
red_apples.insert(it_middle, "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (std::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert | range :" << COLOR_RESET << std::endl << std::endl;
std::list<std::string> fruits;
fruits.push_back("🍍");
fruits.push_back("🍉");
fruits.push_back("🍐");
fruits.push_back("🍒");
fruits.push_back("🍓");
std::list<std::string> animals;
animals.push_back("🐈");
animals.push_back("🐊");
animals.push_back("🐇");
animals.push_back("🦖");
animals.push_back("🐬");
std::list<std::string>::iterator animalsIteMid = animals.begin();
animalsIteMid++;
animalsIteMid++;
std::cout << "For fruit in string list : ";
std::cout << std::endl << "fruits = { ";
for (std::list<std::string>::iterator it = fruits.begin(); it != fruits.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For animal in string list : ";
std::cout << std::endl << "animals = { ";
for (std::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Insert range of fruits in animals list" << std::endl;
animals.insert(animalsIteMid, fruits.begin(), fruits.end());
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (std::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert multiple same element :" << COLOR_RESET << std::endl << std::endl;
std::cout << "// In the animal list, insert 5 bananas at the begining" << std::endl;
animals.insert(animals.begin(), 5, "🍌");
std::cout << "animals.insert(animals.begin(), 5, \"🍌\")" << std::endl;
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (std::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// In the animal list, insert 5 bananas at the end" << std::endl;
animals.insert(animals.end(), 5, "🍌");
std::cout << "animals.insert(animals.end(), 5, \"🍌\")" << std::endl;
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (std::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_modifiers_one(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test Modifiers part one" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"clear :" << COLOR_RESET << std::endl << std::endl;
ft::list<std::string> lst;
lst.push_back("mr");
lst.push_back("robot");
lst.push_back("is");
lst.push_back("a");
lst.push_back("very");
lst.push_back("good");
lst.push_back("series.");
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (ft::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
lst.clear();
std::cout << "lst.clear();"<< std::endl << std::endl;
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (ft::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
lst.clear();
std::cout << "lst.clear();"<< std::endl << std::endl;
std::cout << "For a string list : ";
std::cout << std::endl << "lst = { ";
for (ft::list<std::string>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "lst.size() = " << lst.size() << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"assign :" << COLOR_RESET << std::endl << std::endl;
ft::list<std::string> lst_empty;
ft::list<std::string> lst_watch_brands;
lst_watch_brands.push_back("rolex");
lst_watch_brands.push_back("lip");
lst_watch_brands.push_back("montblanc");
lst_watch_brands.push_back("cartier");
lst_watch_brands.push_back("TAG_Heuer");
std::cout << "For an empty string list : ";
std::cout << std::endl << "lst_empty = { ";
for (ft::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "With an string list lst_watch_brands : ";
std::cout << std::endl << "lst = { ";
for (ft::list<std::string>::iterator it = lst_watch_brands.begin(); it != lst_watch_brands.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_empty.assign(10, "empty");
std::cout << "lst_empty.assign(10, \"empty\");" << std::endl;
std::cout << std::endl << "lst_empty = { ";
for (ft::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
lst_empty.assign(lst_watch_brands.begin(), lst_watch_brands.end());
std::cout << "lst_empty.assign(lst_watch_brands.begin(), lst_watch_brands.end());" << std::endl;
std::cout << std::endl << "lst_empty = { ";
for (ft::list<std::string>::iterator it = lst_empty.begin(); it != lst_empty.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert | single element :" << COLOR_RESET << std::endl << std::endl;
ft::list<std::string> red_apples(10, "🍎");
std::cout << "For red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (ft::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Inserting green apple at the begining of the list" << std::endl;
std::cout << "red_apples.insert(red_apples.begin(), \"🍏\")" << std::endl;
red_apples.insert(red_apples.begin(), "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (ft::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Inserting green apple at the end of the list" << std::endl;
std::cout << "red_apples.insert(red_apples.end(), \"🍏\")" << std::endl;
red_apples.insert(red_apples.end(), "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (ft::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<std::string>::iterator it_middle = red_apples.begin();
it_middle++;
it_middle++;
it_middle++;
it_middle++;
it_middle++;
it_middle++;
std::cout << "// Inserting green apple at the middle of the list" << std::endl;
std::cout << "red_apples.insert(it_middle, \"🍏\")" << std::endl;
red_apples.insert(it_middle, "🍏");
std::cout << "red apples list : ";
std::cout << std::endl << "red_apples = { ";
for (ft::list<std::string>::iterator it = red_apples.begin(); it != red_apples.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert | range :" << COLOR_RESET << std::endl << std::endl;
ft::list<std::string> fruits;
fruits.push_back("🍍");
fruits.push_back("🍉");
fruits.push_back("🍐");
fruits.push_back("🍒");
fruits.push_back("🍓");
ft::list<std::string> animals;
animals.push_back("🐈");
animals.push_back("🐊");
animals.push_back("🐇");
animals.push_back("🦖");
animals.push_back("🐬");
ft::list<std::string>::iterator animalsIteMid = animals.begin();
animalsIteMid++;
animalsIteMid++;
std::cout << "For fruit in string list : ";
std::cout << std::endl << "fruits = { ";
for (ft::list<std::string>::iterator it = fruits.begin(); it != fruits.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "For animal in string list : ";
std::cout << std::endl << "animals = { ";
for (ft::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// Insert range of fruits in animals list" << std::endl;
animals.insert(animalsIteMid, fruits.begin(), fruits.end());
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (ft::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"insert multiple same element :" << COLOR_RESET << std::endl << std::endl;
std::cout << "// In the animal list, insert 5 bananas at the begining" << std::endl;
animals.insert(animals.begin(), 5, "🍌");
std::cout << "animals.insert(animals.begin(), 5, \"🍌\")" << std::endl;
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (ft::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << "// In the animal list, insert 5 bananas at the end" << std::endl;
animals.insert(animals.end(), 5, "🍌");
std::cout << "animals.insert(animals.end(), 5, \"🍌\")" << std::endl;
std::cout << "animal list after insert : ";
std::cout << std::endl << "animals = { ";
for (ft::list<std::string>::iterator it = animals.begin(); it != animals.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_modifiers_one_std();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mapConstReverseIterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/24 16:31:36 by jereligi #+# #+# */
/* Updated: 2021/04/03 15:46:26 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MAPCONSTREVERSEITERATOR_HPP
#define MAPCONSTREVERSEITERATOR_HPP
#include "../../utils.hpp"
#include "./mapIterator.hpp"
#include "../map.hpp"
namespace ft
{
template <typename T, typename node_type>
class mapConstReverseIterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef value_type* pointer;
typedef const pointer const_pointer;
typedef std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
mapConstReverseIterator(void) : _map(NULL) {
};
mapConstReverseIterator(node_type *src) {
_map = src;
};
mapConstReverseIterator(const mapConstReverseIterator &src) {
_map = src._map;
};
mapConstReverseIterator(const mapIterator<T, node_type> &src) {
_map = src.get_map();
};
virtual ~mapConstReverseIterator() {};
mapConstReverseIterator &operator=(mapConstReverseIterator const &src) {
_map = src._map;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator ==(mapConstReverseIterator const& src) const {
return (_map == src.map);
};
bool operator !=(mapConstReverseIterator const& src) const {
return (_map != src._map);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
mapConstReverseIterator operator ++()
{
if (_map->left != NULL)
{
_map = _map->left;
while (_map->right != NULL)
_map = _map->right;
}
else
{
node_type *child = _map;
_map = _map->parent;
while (_map && child == _map->left)
{
child = _map;
_map = _map->parent;
}
}
return (*this);
};
mapConstReverseIterator operator --()
{
if (_map->right != NULL)
{
_map = _map->right;
while (_map->left != NULL)
_map = _map->left;
}
else
{
node_type *child = _map;
_map = _map->parent;
while (_map->right == child)
{
child = _map;
_map = _map->parent;
}
}
return (*this);
};
mapConstReverseIterator operator ++(int) // a++
{
mapConstReverseIterator temp = *this;
++(*this);
return (temp);
};
mapConstReverseIterator operator --(int) // a--
{
mapConstReverseIterator temp = *this;
--(*this);
return (temp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
reference operator *() {
return (_map->data);
};
const_reference operator *() const {
return (_map->data);
};
pointer operator ->() {
return (&_map->data);
};
// const_pointer operator ->() const {
// return (&_map->data);
// };
private:
const node_type *_map;
};
}
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* capacity_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 16:12:14 by jereligi #+# #+# */
/* Updated: 2021/03/04 11:14:25 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../vector.hpp"
#include "constant.hpp"
void capacity_vector()
{
// tester size() | max_size() | resize() | capacity | reserve
std::cout << ft_vector << std::endl;
// FT_VECTOR
ft::vector<int> vec(4,42);
std::cout << COLOR_CYAN << "Test Capacity vector" << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_CYAN << "Test ft::vector size() | max_size() | resize() | capacity | reserve" \
<< COLOR_RESET << std::endl << std::endl;
std::cout << "vec.size() = " << vec.size() << std::endl;
std::cout << "vec.capacity() = " << vec.capacity() << std::endl;
vec.push_back(43);
std::cout << "vec.push_back(43)" << std::endl;
std::cout << "vec.size() = " << vec.size() << std::endl;
std::cout << "vec.capacity() = " << vec.capacity() << std::endl;
std::cout << "vec.max_size() = " << vec.max_size() << std::endl;
vec.resize(2);
std::cout << "vec.resize(2) | vec.size() = " << vec.size() << std::endl;
std::cout << "vec.capacity() = " << vec.capacity() << std::endl;
vec.resize(6, 24);
std::cout << "vec.resize(6, 24) | vec.size() = " << vec.size() << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl;
}
std::cout << "vec.empty is " << std::boolalpha << vec.empty() << std::endl;
vec.resize(0);
std::cout << "vec.resize(0)" << std::endl;
std::cout << "vec.empty is " << std::boolalpha << vec.empty() << std::endl;
vec.reserve(12);
std::cout << "vec.reserve(12)" << std::endl;
std::cout << "vec.capacity() = " << vec.capacity() << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1(4, 42);
std::cout << COLOR_CYAN << "Test std::vector size() | max_size() | resize() | capacity | reserve" \
<< COLOR_RESET << std::endl << std::endl;
std::cout << "vec.size() = " << vec1.size() << std::endl;
std::cout << "vec.capacity() = " << vec1.capacity() << std::endl;
vec1.push_back(43);
std::cout << "vec.push_back(43)" << std::endl;
std::cout << "vec.size() = " << vec1.size() << std::endl;
std::cout << "vec.capacity() = " << vec1.capacity() << std::endl;
std::cout << "vec.max_size() = " << vec1.max_size() << std::endl;
vec1.resize(2);
std::cout << "vec.resize(2) | vec.size() = " << vec1.size() << std::endl;
std::cout << "vec.capacity() = " << vec1.capacity() << std::endl;
vec1.resize(6, 24);
std::cout << "vec.resize(6, 24) | vec.size() = " << vec1.size() << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl;
}
std::cout << "vec.empty is " << std::boolalpha << vec1.empty() << std::endl;
vec1.resize(0);
std::cout << "vec.resize(0)" << std::endl;
std::cout << "vec.empty is " << std::boolalpha << vec1.empty() << std::endl;
vec1.reserve(12);
std::cout << "vec.reserve(12)" << std::endl;
std::cout << "vec.capacity() = " << vec1.capacity() << std::endl << std::endl;
next_test();
}<file_sep># 42Ft_containers
### Subject
The subject of this project is to re-implement some STL containers. It is a library containing various components facilitating programming in C ++. Vector, List, Map, Stack, and Queue are the containers to reimplement.
***Language C++98***

<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* constant.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 16:12:08 by jereligi #+# #+# */
/* Updated: 2021/04/03 15:16:37 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CONSTANT_HPP
#define CONSTANT_HPP
#include <iostream>
#include <list>
#include <string>
#include "../list.hpp"
#define COLOR_RESET "\033[0m"
#define COLOR_RED "\033[1;31m"
#define COLOR_BLUE "\033[1;34m"
#define COLOR_GREEN "\033[1;32m"
#define COLOR_WHITE "\033[1;37m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_CYAN "\033[1;36m"
#define clear_terminal "\x1B[2J\x1B[H"
#define ft_list COLOR_BLUE << "----- ft::list -----" << COLOR_RESET << std::endl
void next_test();
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tester.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Jeanxavier <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/03 14:06:06 by jereligi #+# #+# */
/* Updated: 2021/04/03 19:15:37 by Jeanxavier ### ########.fr */
/* */
/* ************************************************************************** */
#include <map>
#include "../map.hpp"
#include <vector>
#include <iostream>
#include "utils.hpp"
#define COLOR_RESET "\033[0m"
#define COLOR_RED "\033[1;31m"
#define COLOR_BLUE "\033[1;34m"
#define COLOR_GREEN "\033[1;32m"
#define COLOR_WHITE "\033[1;37m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_CYAN "\033[1;36m"
#define clear_terminal "\x1B[2J\x1B[H"
#define ft_list COLOR_BLUE << "----- ft::map -----" << COLOR_RESET << std::endl
void next_test()
{
std::string buf;
std::cout << COLOR_GREEN << "press enter for continu..." << COLOR_RESET;
std::getline (std::cin, buf);
std::cout << clear_terminal << std::endl;
}
static void test_operator_brackets_std(void)
{
print_header("STD MAP OPERATOR BRACKETS TEST");
std::map<std::string, int> str_int_map;
std::cout << "for a std::map<std::string, int> str_int_map;" << std::endl << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl;
std::cout << "str_int_map[\"init\"] : " << str_int_map["init"] << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl << std::endl;
str_int_map["init"] = 56;
std::cout << "str_int_map[\"init\"] = 56;"<< std::endl;
std::cout << "str_int_map[\"init\"] : " << str_int_map["init"] << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl << std::endl;
std::map<int, int> int_int_map;
std::cout << "for a std::map<int, int> int_int_map;" << std::endl << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl;
std::cout << "int_int_map[0] : " << int_int_map[0] << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl << std::endl;
int_int_map[0] = 56;
std::cout << "int_int_map[0] = 56;"<< std::endl;
std::cout << "int_int_map[0] : " << int_int_map[0] << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl << std::endl;
int_int_map[10] = 42;
std::cout << "int_int_map[10] = 42;"<< std::endl;
std::cout << "int_int_map[10] : " << int_int_map[10] << std::endl;
std::cout << "int_int_map.slize() : " << int_int_map.size() << std::endl << std::endl;
next_test();
}
static void test_operator_brackets(void)
{
print_header("FT MAP OPERATOR BRACKETS TEST");
ft::map<std::string, int> str_int_map;
std::cout << "for a ft::map<std::string, int> str_int_map;" << std::endl << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl;
std::cout << "str_int_map[\"init\"] : " << str_int_map["init"] << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl << std::endl;
str_int_map["init"] = 56;
std::cout << "str_int_map[\"init\"] = 56;"<< std::endl;
std::cout << "str_int_map[\"init\"] : " << str_int_map["init"] << std::endl;
std::cout << "str_int_map.size() : " << str_int_map.size() << std::endl << std::endl;
ft::map<int, int> int_int_map;
std::cout << "for a ft::map<int, int> int_int_map;" << std::endl << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl;
std::cout << "int_int_map[0] : " << int_int_map[0] << std::endl;
std::cout << "str_int_map.empty() : " << std::boolalpha << str_int_map.empty() << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl << std::endl;
int_int_map[0] = 56;
std::cout << "int_int_map[0] = 56;"<< std::endl;
std::cout << "int_int_map[0] : " << int_int_map[0] << std::endl;
std::cout << "int_int_map.size() : " << int_int_map.size() << std::endl << std::endl;
int_int_map[10] = 42;
std::cout << "int_int_map[10] = 42;"<< std::endl;
std::cout << "int_int_map[10] : " << int_int_map[10] << std::endl;
std::cout << "int_int_map.slize() : " << int_int_map.size() << std::endl << std::endl;
test_operator_brackets_std();
}
static void test_iterator_std(void)
{
print_header("STD TEST ITERATOR");
std::map<int, int> int_int_map;
std::cout << "For a std::map<int, int> int_int_map;" << std::endl << std::endl;
int_int_map[56] = 56;
int_int_map[30] = 30;
int_int_map[70] = 70;
int_int_map[22] = 22;
int_int_map[40] = 40;
int_int_map[60] = 60;
int_int_map[95] = 95;
int_int_map[11] = 11;
int_int_map[65] = 65;
int_int_map[3] = 3;
int_int_map[16] = 16;
int_int_map[63] = 63;
int_int_map[67] = 67;
std::cout << "int_int_map[56] = 56;" << std::endl;
std::cout << "int_int_map[30] = 30;" << std::endl;
std::cout << "int_int_map[70] = 70;" << std::endl;
std::cout << "int_int_map[22] = 22;" << std::endl;
std::cout << "int_int_map[40] = 40;" << std::endl;
std::cout << "int_int_map[60] = 60;" << std::endl;
std::cout << "int_int_map[95] = 95;" << std::endl;
std::cout << "int_int_map[11] = 11;" << std::endl;
std::cout << "int_int_map[65] = 65;" << std::endl;
std::cout << "int_int_map[3] = 3;" << std::endl;
std::cout << "int_int_map[16] = 16;" << std::endl;
std::cout << "int_int_map[63] = 63;" << std::endl;
std::cout << "int_int_map[67] = 67;" << std::endl << std::endl;
std::cout << "for (std::map<int, int>::iterator it = int_int_map.begin(); it != int_int_map.end(); it++)" << std::endl;
std::cout << "\tstd::cout << *it << std::endl;" << std::endl << std::endl;
for (std::map<int, int>::iterator it = int_int_map.begin();
it != int_int_map.end();
it++)
std::cout << *it << std::endl;
std::cout << std::endl;
std::cout << "int_int_map.begin() == int_int_map.begin() : " << \
std::boolalpha << (int_int_map.begin() == int_int_map.begin()) << std::endl;
std::cout << "int_int_map.begin() != int_int_map.begin() : " << \
std::boolalpha << (int_int_map.begin() != int_int_map.begin()) << std::endl;
std::cout << "int_int_map.begin() == int_int_map.end() : " << \
std::boolalpha << (int_int_map.begin() == int_int_map.end()) << std::endl;
std::cout << "int_int_map.begin() != int_int_map.end() : " << \
std::boolalpha << (int_int_map.begin() != int_int_map.end()) << std::endl << std::endl;
next_test();
}
static void test_iterator(void)
{
print_header("FT TEST ITERATOR");
ft::map<int, int> int_int_map;
std::cout << "For a ft::map<int, int> int_int_map;" << std::endl << std::endl;
int_int_map[56] = 56;
int_int_map[30] = 30;
int_int_map[70] = 70;
int_int_map[22] = 22;
int_int_map[40] = 40;
int_int_map[60] = 60;
int_int_map[95] = 95;
int_int_map[11] = 11;
int_int_map[65] = 65;
int_int_map[3] = 3;
int_int_map[16] = 16;
int_int_map[63] = 63;
int_int_map[67] = 67;
std::cout << "int_int_map[56] = 56;" << std::endl;
std::cout << "int_int_map[30] = 30;" << std::endl;
std::cout << "int_int_map[70] = 70;" << std::endl;
std::cout << "int_int_map[22] = 22;" << std::endl;
std::cout << "int_int_map[40] = 40;" << std::endl;
std::cout << "int_int_map[60] = 60;" << std::endl;
std::cout << "int_int_map[95] = 95;" << std::endl;
std::cout << "int_int_map[11] = 11;" << std::endl;
std::cout << "int_int_map[65] = 65;" << std::endl;
std::cout << "int_int_map[3] = 3;" << std::endl;
std::cout << "int_int_map[16] = 16;" << std::endl;
std::cout << "int_int_map[63] = 63;" << std::endl;
std::cout << "int_int_map[67] = 67;" << std::endl << std::endl;
std::cout << "for (ft::map<int, int>::iterator it = int_int_map.begin(); it != int_int_map.end(); it++)" << std::endl;
std::cout << "\tstd::cout << *it << std::endl;" << std::endl << std::endl;
for (ft::map<int, int>::iterator it = int_int_map.begin();
it != int_int_map.end();
it++)
std::cout << *it << std::endl;
std::cout << std::endl;
std::cout << "int_int_map.begin() == int_int_map.begin() : " << \
std::boolalpha << (int_int_map.begin() == int_int_map.begin()) << std::endl;
std::cout << "int_int_map.begin() != int_int_map.begin() : " << \
std::boolalpha << (int_int_map.begin() != int_int_map.begin()) << std::endl;
std::cout << "int_int_map.begin() == int_int_map.end() : " << \
std::boolalpha << (int_int_map.begin() == int_int_map.end()) << std::endl;
std::cout << "int_int_map.begin() != int_int_map.end() : " << \
std::boolalpha << (int_int_map.begin() != int_int_map.end()) << std::endl;
test_iterator_std();
}
static void test_reverse_iterator_std(void)
{
print_header("STD TEST REVERSE ITERATOR");
std::map<int, int> int_int_map;
std::cout << "For a std::map<int, int> int_int_map;" << std::endl << std::endl;
int_int_map[74] = 74;
int_int_map[64] = 64;
int_int_map[77] = 77;
int_int_map[56] = 56;
int_int_map[76] = 76;
int_int_map[87] = 87;
int_int_map[58] = 58;
int_int_map[83] = 83;
int_int_map[92] = 92;
std::cout << "int_int_map[74] = 74;" << std::endl;
std::cout << "int_int_map[64] = 64;" << std::endl;
std::cout << "int_int_map[77] = 77;" << std::endl;
std::cout << "int_int_map[56] = 56;" << std::endl;
std::cout << "int_int_map[76] = 76;" << std::endl;
std::cout << "int_int_map[87] = 87;" << std::endl;
std::cout << "int_int_map[58] = 58;" << std::endl;
std::cout << "int_int_map[83] = 83;" << std::endl;
std::cout << "int_int_map[92] = 92;" << std::endl << std::endl;
std::cout << "for (std::map<int, int>::reverse_iterator it = int_int_map.begin(); it != int_int_map.end(); it++)" << std::endl;
std::cout << "\tstd::cout << *it << std::endl;" << std::endl << std::endl;
for (std::map<int, int>::reverse_iterator it = int_int_map.rbegin();
it != int_int_map.rend();
it++)
std::cout << *it << std::endl;
std::cout << std::endl;
std::cout << "int_int_map.rbegin() == int_int_map.rbegin() : " << \
std::boolalpha << (int_int_map.rbegin() == int_int_map.rbegin()) << std::endl;
std::cout << "int_int_map.rbegin() != int_int_map.rbegin() : " << \
std::boolalpha << (int_int_map.rbegin() != int_int_map.rbegin()) << std::endl;
std::cout << "int_int_map.rbegin() == int_int_map.rend() : " << \
std::boolalpha << (int_int_map.rbegin() == int_int_map.rend()) << std::endl;
std::cout << "int_int_map.rbegin() != int_int_map.rend() : " << \
std::boolalpha << (int_int_map.rbegin() != int_int_map.rend()) << std::endl;
next_test();
}
static void test_reverse_iterator(void)
{
print_header("FT TEST REVERSE ITERATOR");
ft::map<int, int> int_int_map;
std::cout << "For a ft::map<int, int> int_int_map;" << std::endl << std::endl;
int_int_map[74] = 74;
int_int_map[64] = 64;
int_int_map[77] = 77;
int_int_map[56] = 56;
int_int_map[76] = 76;
int_int_map[87] = 87;
int_int_map[58] = 58;
int_int_map[83] = 83;
int_int_map[92] = 92;
std::cout << "int_int_map[74] = 74;" << std::endl;
std::cout << "int_int_map[64] = 64;" << std::endl;
std::cout << "int_int_map[77] = 77;" << std::endl;
std::cout << "int_int_map[56] = 56;" << std::endl;
std::cout << "int_int_map[76] = 76;" << std::endl;
std::cout << "int_int_map[87] = 87;" << std::endl;
std::cout << "int_int_map[58] = 58;" << std::endl;
std::cout << "int_int_map[83] = 83;" << std::endl;
std::cout << "int_int_map[92] = 92;" << std::endl << std::endl;
std::cout << "for (ft::map<int, int>::reverse_iterator it = int_int_map.begin(); it != int_int_map.end(); it++)" << std::endl;
std::cout << "\tstd::cout << *it << std::endl;" << std::endl << std::endl;
for (ft::map<int, int>::reverse_iterator it = int_int_map.rbegin();
it != int_int_map.rend();
it++)
std::cout << *it << std::endl;
std::cout << std::endl;
std::cout << "int_int_map.rbegin() == int_int_map.rbegin() : " << \
std::boolalpha << (int_int_map.rbegin() == int_int_map.rbegin()) << std::endl;
std::cout << "int_int_map.rbegin() != int_int_map.rbegin() : " << \
std::boolalpha << (int_int_map.rbegin() != int_int_map.rbegin()) << std::endl;
std::cout << "int_int_map.rbegin() == int_int_map.rend() : " << \
std::boolalpha << (int_int_map.rbegin() == int_int_map.rend()) << std::endl;
std::cout << "int_int_map.rbegin() != int_int_map.rend() : " << \
std::boolalpha << (int_int_map.rbegin() != int_int_map.rend()) << std::endl;
test_reverse_iterator_std();
}
static void test_erase_by_key_std(void)
{
std::map<std::string, int> map_family;
print_header("STD ERASE BY KEY TEST");
map_family["grand_mother"] = 99;
map_family["Dad"] = 70;
map_family["uncle"] = 60;
map_family["A_me"] = 45;
map_family["G_brother"] = 35;
map_family["s_cousin"] = 40;
map_family["v_cousin"] = 25;
map_family["9_son"] = 20;
map_family["C_daughter"] = 25;
map_family["Z_nethew"] = 8;
map_family["q_lilcousin"] = 15;
map_family["uo_lilcousin"] = 1;
map_family["B_lilson"] = 15;
std::cout << "Our family is :" << std::endl;
std::cout << map_family << std::endl;
std::cout << "erase a leaf : map_family.erase(\"G_brother\")" << std::endl << std::endl;
map_family.erase("G_brother");
std::cout << map_family << std::endl;
std::cout << "erase a one leaf branch : map_family.erase(\"C_daughter\")" << std::endl << std::endl;
map_family.erase("C_daughter");
std::cout << map_family << std::endl;
std::cout << "erase the root : map_family.erase(\"grand_mother\")" << std::endl << std::endl;
map_family.erase("grand_mother");
std::cout << map_family << std::endl;
next_test();
}
static void test_erase_by_key(void)
{
ft::map<std::string, int> map_family;
std::cout << "Here is a representation of the binary tree :" << std::endl << std::endl;
std::cout << \
" grand-mother" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" / \\" << std::endl << \
" Dad uncle" << std::endl << \
" / \\ / \\" << std::endl << \
" / \\ / \\" << std::endl << \
" / \\ / \\" << std::endl << \
" / \\ / \\" << std::endl << \
" / \\ / \\" << std::endl << \
" A_me G_brother s_cousin v_cousin" << std::endl << \
" / \\ \\ / /" << std::endl << \
" / \\ \\ / /" << std::endl << \
" / \\ \\ / /" << std::endl << \
" / \\ \\ / /" << std::endl << \
"9_son C_daughter Z_nethew q_lilcousin um_lilcousin" << std::endl << \
std::endl;
print_header("FT ERASE BY KEY TEST");
map_family["grand_mother"] = 99;
map_family["Dad"] = 70;
map_family["uncle"] = 60;
map_family["A_me"] = 45;
map_family["G_brother"] = 35;
map_family["s_cousin"] = 40;
map_family["v_cousin"] = 25;
map_family["9_son"] = 20;
map_family["C_daughter"] = 25;
map_family["Z_nethew"] = 8;
map_family["q_lilcousin"] = 15;
map_family["uo_lilcousin"] = 1;
map_family["B_lilson"] = 15;
std::cout << "Our family is :" << std::endl << std::endl;
std::cout << map_family << std::endl;
std::cout << "erase a leaf : map_family.erase(\"G_brother\")" << std::endl << std::endl;
map_family.erase("G_brother");
std::cout << map_family << std::endl;
std::cout << "erase a one leaf branch : map_family.erase(\"C_daughter\")" << std::endl << std::endl;
map_family.erase("C_daughter");
std::cout << map_family << std::endl;
std::cout << "erase the root : map_family.erase(\"grand_mother\")" << std::endl << std::endl;
map_family.erase("grand_mother");
std::cout << map_family << std::endl;
test_erase_by_key_std();
}
static void test_erase_by_iterators_std(void)
{
print_header("STD ERASE ITERATORS TEST");
std::cout << "#-- Erase a range of elements --#" << std::endl;
std::map<double, double> db_db_map;
std::cout << "For a std::map<double, double> db_db_map;" << std::endl << std::endl;
db_db_map[54.32] = 54.32;
db_db_map[15.62] = 15.62;
db_db_map[81.778] = 81.778;
db_db_map[3.14] = 3.14;
db_db_map[2.3948] = 2.3948;
db_db_map[584.329] = 584.329;
db_db_map[1] = 1;
db_db_map[58932] = 58932;
db_db_map[902.314] = 902.314;
std::cout << "db_db_map :" << std::endl << db_db_map << std::endl << std::endl;
db_db_map.erase(db_db_map.begin(), db_db_map.end());;
std::cout << "db_db_map.erase(db_db_map.begin(), db_db_map.end());" << std::endl << std::endl;
std::cout << "db_db_map :" << std::endl << db_db_map << std::endl << std::endl;
std::cout << "#-- Erase a range of elements in a single element map --#" << std::endl << std::endl;
std::cout << "For a std::map<std::string, std::string> str_str_map;" << std::endl << std::endl;
std::map<std::string, std::string> str_str_map;
std::cout << "str_str_map[\"I\'m alone\"] = \"i\'m not alone !\";" << std::endl << std::endl;
str_str_map["I'm alone"] = "i'm not alone !";
std::cout << "str_str_map :" << std::endl << str_str_map << std::endl << std::endl;
str_str_map.erase(str_str_map.begin(), str_str_map.end());;
std::cout << "str_str_map.erase(str_str_map.begin(), str_str_map.end());" << std::endl << std::endl;
std::cout << "str_str_map :" << std::endl << str_str_map << std::endl << std::endl;
std::cout << "#-- Erase by single iterator --#" << std::endl << std::endl;
std::map<int, int> int_int_map;
int_int_map[66] = 66;
int_int_map[47] = 47;
int_int_map[74] = 74;
int_int_map[54] = 54;
int_int_map[71] = 71;
int_int_map[53] = 53;
int_int_map[59] = 59;
int_int_map[69] = 69;
int_int_map[72] = 72;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::map<int, int>::iterator it = int_int_map.begin();
std::cout << "std::map<int, int>::iterator it = int_int_map.begin();" << std::endl;
it++;
it++;
it++;
it++;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl << std::endl;
std::cout << "*it : " << *it << std::endl << std::endl;
int_int_map.erase(it);
std::cout << "int_int_map.erase(it);" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "#-- Erase by single iterator in a single list --#" << std::endl << std::endl;
std::map<std::string, bool> affirmation;
std::cout << "std::map<std::string, bool> affirmation;" << std::endl << std::endl;
affirmation["Is the earth flat ?"] = false;
std::cout << "affirmation : " << std::endl << affirmation << std::endl;
std::map<std::string, bool>::iterator it_aff = affirmation.begin();
affirmation.erase(it_aff);
std::cout << "affirmation.erase(it_aff);" << std::endl << std::endl;
std::cout << "affirmation : " << std::endl << affirmation << std::endl << std::endl;
next_test();
}
static void test_erase_by_iterators(void)
{
print_header("FT ERASE ITERATORS TEST");
std::cout << "#-- Erase a range of elements --#" << std::endl;
ft::map<double, double> db_db_map;
std::cout << "For a ft::map<double, double> db_db_map;" << std::endl << std::endl;
db_db_map[54.32] = 54.32;
db_db_map[15.62] = 15.62;
db_db_map[81.778] = 81.778;
db_db_map[3.14] = 3.14;
db_db_map[2.3948] = 2.3948;
db_db_map[584.329] = 584.329;
db_db_map[1] = 1;
db_db_map[58932] = 58932;
db_db_map[902.314] = 902.314;
std::cout << "db_db_map :" << std::endl << db_db_map << std::endl << std::endl;
db_db_map.erase(db_db_map.begin(), db_db_map.end());;
std::cout << "db_db_map.erase(db_db_map.begin(), db_db_map.end());" << std::endl << std::endl;
std::cout << "db_db_map :" << std::endl << db_db_map << std::endl << std::endl;
std::cout << "#-- Erase a range of elements in a single element map --#" << std::endl << std::endl;
std::cout << "For a ft::map<std::string, std::string> str_str_map;" << std::endl << std::endl;
ft::map<std::string, std::string> str_str_map;
std::cout << "str_str_map[\"I\'m alone\"] = \"i\'m not alone !\";" << std::endl << std::endl;
str_str_map["I'm alone"] = "i'm not alone !";
std::cout << "str_str_map :" << std::endl << str_str_map << std::endl << std::endl;
str_str_map.erase(str_str_map.begin(), str_str_map.end());;
std::cout << "str_str_map.erase(str_str_map.begin(), str_str_map.end());" << std::endl << std::endl;
std::cout << "str_str_map :" << std::endl << str_str_map << std::endl << std::endl;
std::cout << "#-- Erase by single iterator --#" << std::endl << std::endl;
ft::map<int, int> int_int_map;
int_int_map[66] = 66;
int_int_map[47] = 47;
int_int_map[74] = 74;
int_int_map[54] = 54;
int_int_map[71] = 71;
int_int_map[53] = 53;
int_int_map[59] = 59;
int_int_map[69] = 69;
int_int_map[72] = 72;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
ft::map<int, int>::iterator it = int_int_map.begin();
std::cout << "ft::map<int, int>::iterator it = int_int_map.begin();" << std::endl;
it++;
it++;
it++;
it++;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl;
std::cout << "it++" << std::endl << std::endl;
std::cout << "*it : " << *it << std::endl << std::endl;
int_int_map.erase(it);
std::cout << "int_int_map.erase(it);" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "#-- Erase by single iterator in a single list --#" << std::endl << std::endl;
ft::map<std::string, bool> affirmation;
std::cout << "ft::map<std::string, bool> affirmation;" << std::endl << std::endl;
affirmation["Is the earth flat ?"] = false;
std::cout << "affirmation : " << std::endl << affirmation << std::endl;
ft::map<std::string, bool>::iterator it_aff = affirmation.begin();
affirmation.erase(it_aff);
std::cout << "affirmation.erase(it_aff);" << std::endl << std::endl;
std::cout << "affirmation : " << std::endl << affirmation << std::endl;
test_erase_by_iterators_std();
}
static void test_clear_std(void)
{
print_header("STD CLEAR TEST");
std::map<std::string, double> world_records_apnea;
world_records_apnea["Mifsud"] = 11.35;
world_records_apnea["Sietas"] = 10.12;
world_records_apnea["Mathieu"] = 8.40;
world_records_apnea["<NAME>"] = 8.16;
world_records_apnea["Savornin"] = 8.12;
world_records_apnea["Stepanek"] = 8.06;
std::cout << "For a string double map world_records_apnea :" << std::endl << world_records_apnea << std::endl;
std::cout << "world_records_apnea.size() : " << std::endl << world_records_apnea.size() << std::endl << std::endl;
world_records_apnea.clear();
std::cout << "world_records_apnea.clear();" << std::endl << std::endl;
std::cout << "Now world_records_apnea : " << std::endl << world_records_apnea << std::endl;
std::cout << "world_records_apnea.size() : " << std::endl << world_records_apnea.size() << std::endl << std::endl;
next_test();
}
static void test_clear(void)
{
print_header("FT CLEAR TEST");
ft::map<std::string, double> world_records_apnea;
world_records_apnea["Mifsud"] = 11.35;
world_records_apnea["Sietas"] = 10.12;
world_records_apnea["Mathieu"] = 8.40;
world_records_apnea["<NAME>"] = 8.16;
world_records_apnea["Savornin"] = 8.12;
world_records_apnea["Stepanek"] = 8.06;
std::cout << "For a string double map world_records_apnea :" << std::endl << world_records_apnea << std::endl;
std::cout << "world_records_apnea.size() : " << std::endl << world_records_apnea.size() << std::endl << std::endl;
world_records_apnea.clear();
std::cout << "world_records_apnea.clear();" << std::endl << std::endl;
std::cout << "Now world_records_apnea : " << std::endl << world_records_apnea << std::endl << std::endl;
std::cout << "world_records_apnea.size() : " << std::endl << world_records_apnea.size() << std::endl << std::endl;
test_clear_std();
}
static void test_find_std(void)
{
print_header("STD FIND TEST");
std::map<int, int> random_tree;
random_tree[32] = 32;
random_tree[19] = 19;
random_tree[46] = 46;
random_tree[18] = 18;
random_tree[23] = 23;
random_tree[44] = 44;
random_tree[66] = 66;
random_tree[24] = 24;
random_tree[59] = 59;
random_tree[75] = 75;
std::cout << "random_tree : " << std::endl << random_tree << std::endl;
std::map<int, int>::iterator it = random_tree.find(42442424);
std::cout << "std::map<int, int>::iterator it = random_tree.find(42442424);" << std::endl << std::endl;
std::cout << "it == random_tree.end() : " << std::boolalpha << (it == random_tree.end()) << std::endl << std::endl;
std::map<int, int>::const_iterator it_found = random_tree.find(59);
std::cout << "std::map<int, int>::const_iterator it_found = random_tree.find(59);" << std::endl << std::endl;
std::cout << "*it_found : " << *it_found << std::endl << std::endl;
next_test();
}
static void test_find(void)
{
print_header("FT FIND TEST");
ft::map<int, int> random_tree;
random_tree[32] = 32;
random_tree[19] = 19;
random_tree[46] = 46;
random_tree[18] = 18;
random_tree[23] = 23;
random_tree[44] = 44;
random_tree[66] = 66;
random_tree[24] = 24;
random_tree[59] = 59;
random_tree[75] = 75;
std::cout << "random_tree : " << std::endl << random_tree << std::endl;
ft::map<int, int>::iterator it = random_tree.find(42442424);
std::cout << "ft::map<int, int>::iterator it = random_tree.find(42442424);" << std::endl << std::endl;
std::cout << "it == random_tree.end() : " << std::boolalpha << (it == random_tree.end()) << std::endl << std::endl;
ft::map<int, int>::const_iterator it_found = random_tree.find(59);
std::cout << "ft::map<int, int>::const_iterator it_found = random_tree.find(59);" << std::endl << std::endl;
std::cout << "*it_found : " << *it_found << std::endl << std::endl;
test_find_std();
}
static void test_insert_std(void)
{
print_header("STD INSERT TEST");
std::cout << "#-- INSERT WITH A PAIR ON AN EMPTY MAP --#" << std::endl << std::endl;
std::map<int, int> int_int_map;
std::cout << "For an <int, int> empty map int_int_map;" << std::endl << std::endl;
int_int_map.insert(std::pair<int, int>(42, 42));
std::cout << "int_int_map.insert(std::pair<int, int>(42, 42));" << std::endl << std::endl;
std::cout << "int_int_map[42] : " << int_int_map[42] << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
int_int_map.insert(std::pair<int, int>(109, 109));
std::cout << "int_int_map.insert(std::pair<int, int>(109, 109));" << std::endl << std::endl;
int_int_map.insert(std::pair<int, int>(56, 56));
std::cout << "int_int_map.insert(std::pair<int, int>(56, 56));" << std::endl << std::endl;
int_int_map.insert(std::pair<int, int>(69, 69));
std::cout << "int_int_map.insert(std::pair<int, int>(69, 69));" << std::endl << std::endl;
int_int_map.insert(std::pair<int, int>(1, 1));
std::cout << "int_int_map.insert(std::pair<int, int>(1, 1));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "#-- INSERT WITH A POSITION --#" << std::endl << std::endl;
std::map<int, int>::iterator it = int_int_map.begin();
it++;
it++;
int_int_map.insert(it, std::pair<int, int>(57, 57));
std::cout << "int_int_map.insert(it, std::pair<int, int>(57, 57));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(it, std::pair<int, int>(9100, 9100));
std::cout << "int_int_map.insert(it, std::pair<int, int>(9100, 9100));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(it, std::pair<int, int>(57, 57));
std::cout << "int_int_map.insert(it, std::pair<int, int>(57, 57));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(int_int_map.begin(), std::pair<int, int>(67, 67));
std::cout << "int_int_map.insert(int_int_map.begin(), std::pair<int, int>(67, 67));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
std::cout << "#-- INSERT BY A RANGE --#" << std::endl << std::endl;
std::cout << "std::map<int, int> int_int_map_two;" << std::endl;
std::map<int, int> int_int_map_two;
int_int_map_two[23] = 23;
int_int_map_two[29] = 29;
int_int_map_two[95] = 95;
int_int_map_two[192] = 192;
int_int_map_two[6] = 6;
int_int_map_two[654] = 654;
std::cout << "int_int_map_two : " << std::endl << int_int_map_two << std::endl;
int_int_map.insert(int_int_map_two.begin(), int_int_map_two.end());
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
next_test();
}
static void test_insert(void)
{
print_header("FT INSERT TEST");
std::cout << "#-- INSERT WITH A PAIR ON AN EMPTY MAP --#" << std::endl << std::endl;
ft::map<int, int> int_int_map;
std::cout << "For an <int, int> empty map int_int_map;" << std::endl << std::endl;
int_int_map.insert(ft::pair<int, int>(42, 42));
std::cout << "int_int_map.insert(ft::pair<int, int>(42, 42));" << std::endl << std::endl;
std::cout << "int_int_map[42] : " << int_int_map[42] << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
int_int_map.insert(ft::pair<int, int>(109, 109));
std::cout << "int_int_map.insert(ft::pair<int, int>(109, 109));" << std::endl << std::endl;
int_int_map.insert(ft::pair<int, int>(56, 56));
std::cout << "int_int_map.insert(ft::pair<int, int>(56, 56));" << std::endl << std::endl;
int_int_map.insert(ft::pair<int, int>(69, 69));
std::cout << "int_int_map.insert(ft::pair<int, int>(69, 69));" << std::endl << std::endl;
int_int_map.insert(ft::pair<int, int>(1, 1));
std::cout << "int_int_map.insert(ft::pair<int, int>(1, 1));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "#-- INSERT WITH A POSITION --#" << std::endl << std::endl;
ft::map<int, int>::iterator it = int_int_map.begin();
it++;
it++;
int_int_map.insert(it, ft::pair<int, int>(57, 57));
std::cout << "int_int_map.insert(it, ft::pair<int, int>(57, 57));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(it, ft::pair<int, int>(9100, 9100));
std::cout << "int_int_map.insert(it, ft::pair<int, int>(9100, 9100));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(it, ft::pair<int, int>(57, 57));
std::cout << "int_int_map.insert(it, ft::pair<int, int>(57, 57));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
int_int_map.insert(int_int_map.begin(), ft::pair<int, int>(67, 67));
std::cout << "int_int_map.insert(int_int_map.begin(), ft::pair<int, int>(67, 67));" << std::endl << std::endl;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl << std::endl;
std::cout << "#-- INSERT BY A RANGE --#" << std::endl << std::endl;
std::cout << "ft::map<int, int> int_int_map_two;" << std::endl;
ft::map<int, int> int_int_map_two;
int_int_map_two[23] = 23;
int_int_map_two[29] = 29;
int_int_map_two[95] = 95;
int_int_map_two[192] = 192;
int_int_map_two[6] = 6;
int_int_map_two[654] = 654;
std::cout << "int_int_map_two : " << std::endl << int_int_map_two << std::endl;
int_int_map.insert(int_int_map_two.begin(), int_int_map_two.end());
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
test_insert_std();
}
static void test_copy_std(void)
{
print_header("STD COPY CONSTRUCTOR + ASSIGNATION OPERATOR");
std::cout << "For a string, string map hand_france;" << std::endl << std::endl;
std::map<std::string, std::string> hand_france;
hand_france["Glauser"] = "Laura";
hand_france["Nocandy"] = "Méline";
hand_france["Coatenea"] = "Pauline";
hand_france["Valentini"] = "Chloé";
hand_france["Lassource"] = "Coralie";
hand_france["Zaadi"] = "Grace";
std::cout << "map hand_france : " << std::endl << hand_france << std::endl;
std::map<std::string, std::string> cpy_hand_france(hand_france);
std::cout << "std::map<std::string, std::string> cpy_hand_france(hand_france);" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
std::cout << "// Test to modify the new copied map" << std::endl;
cpy_hand_france["Kouyaté"] = "Aissatou";
std::cout << "cpy_hand_france[\"Kouyaté\"] = \"Aissatou\";" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
std::map<std::string, std::string> artists_world;
std::cout << "For a string, string map top world artists :" << std::endl << std::endl;
artists_world["<NAME>"] = "drivers license";
artists_world["The Weekend"] = "Save Your Tears";
artists_world["Lil Tjay"] = "Calling My Phone";
artists_world["The Weekend"] = "Blinding Lights";
artists_world["Bad Bunny"] = "DAKITI";
artists_world["<NAME>"] = "Bandido";
artists_world["24kGoldn"] = "Mood";
std::cout << "map artists_world : " << std::endl << artists_world << std::endl;
cpy_hand_france = artists_world;
std::cout << "cpy_hand_france = artists_world;" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
next_test();
}
static void test_copy(void)
{
print_header("FT COPY CONSTRUCTOR + ASSIGNATION OPERATOR");
std::cout << "For a string, string map hand_france;" << std::endl << std::endl;
ft::map<std::string, std::string> hand_france;
hand_france["Glauser"] = "Laura";
hand_france["Nocandy"] = "Méline";
hand_france["Coatenea"] = "Pauline";
hand_france["Valentini"] = "Chloé";
hand_france["Lassource"] = "Coralie";
hand_france["Zaadi"] = "Grace";
std::cout << "map hand_france : " << std::endl << hand_france << std::endl;
ft::map<std::string, std::string> cpy_hand_france(hand_france);
std::cout << "ft::map<std::string, std::string> cpy_hand_france(hand_france);" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
std::cout << "// Test to modify the new copied map" << std::endl;
cpy_hand_france["Kouyaté"] = "Aissatou";
std::cout << "cpy_hand_france[\"Kouyaté\"] = \"Aissatou\";" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
ft::map<std::string, std::string> artists_world;
std::cout << "For a string, string map top world artists :" << std::endl << std::endl;
artists_world["<NAME>"] = "drivers license";
artists_world["The Weekend"] = "Save Your Tears";
artists_world["<NAME>"] = "Calling My Phone";
artists_world["The Weekend"] = "Blinding Lights";
artists_world["<NAME>"] = "DAKITI";
artists_world["<NAME>"] = "Bandido";
artists_world["24kGoldn"] = "Mood";
std::cout << "map artists_world : " << std::endl << artists_world << std::endl;
cpy_hand_france = artists_world;
std::cout << "cpy_hand_france = artists_world;" << std::endl << std::endl;
std::cout << "map cpy_hand_france : " << std::endl << cpy_hand_france << std::endl;
test_copy_std();
}
void test_swap_std(void)
{
print_header("STD SWAP TEST");
std::cout << "For a <int, string> map banana_box;" << std::endl;
std::cout << "For a <int, string> map apple_box;" << std::endl;
std::map<int, std::string> banana_box;
std::map<int, std::string> apple_box;
banana_box[34] = "🍌";
banana_box[59] = "🍌";
banana_box[32] = "🍌";
banana_box[2] = "🍌";
banana_box[492] = "🍌";
banana_box[56] = "🍌";
apple_box[92] = "🍎";
apple_box[9] = "🍎";
apple_box[103] = "🍎";
apple_box[293] = "🍎";
apple_box[93] = "🍎";
apple_box[663] = "🍎";
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
banana_box.swap(apple_box);
std::cout << "apple_box.swap(banana_box);" << std::endl << std::endl;
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
apple_box.swap(banana_box);
std::cout << "apple_box.swap(banana_box);" << std::endl << std::endl;
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
next_test();
}
void test_swap(void)
{
print_header("FT SWAP TEST");
std::cout << "For a <int, string> map banana_box;" << std::endl;
std::cout << "For a <int, string> map apple_box;" << std::endl;
ft::map<int, std::string> banana_box;
ft::map<int, std::string> apple_box;
banana_box[34] = "🍌";
banana_box[59] = "🍌";
banana_box[32] = "🍌";
banana_box[2] = "🍌";
banana_box[492] = "🍌";
banana_box[56] = "🍌";
apple_box[92] = "🍎";
apple_box[9] = "🍎";
apple_box[103] = "🍎";
apple_box[293] = "🍎";
apple_box[93] = "🍎";
apple_box[663] = "🍎";
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
banana_box.swap(apple_box);
std::cout << "apple_box.swap(banana_box);" << std::endl << std::endl;
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
apple_box.swap(banana_box);
std::cout << "apple_box.swap(banana_box);" << std::endl << std::endl;
std::cout << "banana_box :" << std::endl << banana_box << std::endl;
std::cout << "apple_box :" << std::endl << apple_box << std::endl << std::endl;
test_swap_std();
}
static void test_key_compare_std(void)
{
print_header("STD KEY COMPARE TEST");
std::map<char,int> mymap;
std::map<char,int>::key_compare mycomp = mymap.key_comp();
mymap['a']=100;
mymap['b']=200;
mymap['c']=300;
mymap['d']=400;
mymap['e']=500;
mymap['f']=600;
mymap['g']=700;
mymap['h']=800;
std::cout << "For a <char, int> \"mymap\" map : " << std::endl << mymap << std::endl;
std::cout << "For a comparaison object \"mycomp\" = mymap.key_comp()" << std::endl << std::endl;
std::cout << "For a char as highest key in map : char highest = mymap.rbegin()->first;" << std::endl << std::endl;
char highest = mymap.rbegin()->first; // key value of last element
std::map<char,int>::iterator it = mymap.begin();
std::cout << "iterator it = mymap.begin();" << std::endl << std::endl;
std::cout << "while (mycomp((*it).first, highest) == true)" << std::endl;
std::cout << " std::cout << it->first << \" => \" << it->second << std::endl;" << std::endl;
std::cout << " it++;" << std::endl << std::endl;
std::cout << "=" << std::endl << std::endl;
while (mycomp((*it).first, highest))
{
std::cout << it->first << " => " << it->second << std::endl;
it++;
}
next_test();
}
static void test_key_compare(void)
{
print_header("FT KEY COMPARE TEST");
ft::map<char,int> mymap;
ft::map<char,int>::key_compare mycomp = mymap.key_comp();
mymap['a']=100;
mymap['b']=200;
mymap['c']=300;
mymap['d']=400;
mymap['e']=500;
mymap['f']=600;
mymap['g']=700;
mymap['h']=800;
std::cout << "For a <char, int> \"mymap\" map : " << std::endl << mymap << std::endl;
std::cout << "For a comparaison object \"mycomp\" = mymap.key_comp()" << std::endl << std::endl;
std::cout << "For a char as highest key in map : char highest = mymap.rbegin()->first;" << std::endl << std::endl;
char highest = mymap.rbegin()->first; // key value of last element
ft::map<char,int>::iterator it = mymap.begin();
std::cout << "iterator it = mymap.begin();" << std::endl << std::endl;
std::cout << "while (mycomp((*it).first, highest) == true)" << std::endl;
std::cout << " std::cout << it->first << \" => \" << it->second << std::endl;" << std::endl;
std::cout << " it++;" << std::endl << std::endl;
std::cout << "=" << std::endl << std::endl;
while (mycomp((*it).first, highest))
{
std::cout << it->first << " => " << it->second << std::endl;
it++;
}
std::cout << std::endl;
test_key_compare_std();
}
static void test_value_compare_std(void)
{
print_header("STD VALUE COMPARE TEST");
std::map<char,int> mymap;
mymap['h']=100;
mymap['g']=200;
mymap['f']=300;
mymap['e']=400;
mymap['d']=500;
mymap['c']=600;
mymap['b']=700;
mymap['a']=800;
std::cout << "For a <char, int> \"mymap\" map : " << std::endl << mymap << std::endl;
std::cout << "For a char as highest pair in map : char highest = *(mymap.rbegin());" << std::endl << std::endl;
std::pair<char, int> highest = *(mymap.rbegin());
std::cout << "iterator it = mymap.begin();" << std::endl << std::endl;
std::map<char,int>::iterator it = mymap.begin();
std::cout << "while (mymap.value_comp()(*it, highest))" << std::endl;
std::cout << " std::cout << it->first << \" => \" << it->second << std::endl;" << std::endl;
std::cout << " it++;" << std::endl << std::endl;
std::cout << "=" << std::endl << std::endl;
while (mymap.value_comp()(*it, highest))
{
std::cout << it->first << " => " << it->second << std::endl;
it++;
}
std::cout << std::endl;
next_test();
}
static void test_value_compare(void)
{
print_header("FT VALUE COMPARE TEST");
ft::map<char,int> mymap;
mymap['h']=100;
mymap['g']=200;
mymap['f']=300;
mymap['e']=400;
mymap['d']=500;
mymap['c']=600;
mymap['b']=700;
mymap['a']=800;
std::cout << "For a <char, int> \"mymap\" map : " << std::endl << mymap << std::endl;
std::cout << "For a char as highest pair in map : char highest = *(mymap.rbegin());" << std::endl << std::endl;
ft::pair<char, int> highest = *(mymap.rbegin());
std::cout << "iterator it = mymap.begin();" << std::endl << std::endl;
ft::map<char,int>::iterator it = mymap.begin();
std::cout << "while (mymap.value_comp()(*it, highest))" << std::endl;
std::cout << " std::cout << it->first << \" => \" << it->second << std::endl;" << std::endl;
std::cout << " it++;" << std::endl << std::endl;
std::cout << "=" << std::endl << std::endl;
while (mymap.value_comp()(*it, highest))
{
std::cout << it->first << " => " << it->second << std::endl;
it++;
}
std::cout << std::endl;
test_value_compare_std();
}
static void test_iterator_constructor_std(void)
{
print_header("STD ITERATOR CONSTRUCTOR");
std::cout << "For std::map<std::string, std::string> map_countries" << std::endl;
std::map<std::string, std::string> map_countries;
map_countries["New-york"] = "USA";
map_countries["Sydney"] = "Australia";
map_countries["Paris"] = "France";
map_countries["New-Delhi"] = "India";
map_countries["Berlin"] = "Germany";
map_countries["Brest"] = "France";
map_countries["Prague"] = "Czech Republic";
map_countries["Dublin"] = "Prague";
std::cout << "map_countries :" << std::endl << map_countries << std::endl;
std::map<std::string, std::string> cpy_map_countries(map_countries.begin(), map_countries.end());
std::cout << "std::map<std::string, std::string> cpy_map_countries(map_countries.begin(), map_countries.end());" << std::endl;
std::cout << "cpy_map_countries :" << std::endl << cpy_map_countries << std::endl;
next_test();
}
static void test_iterator_constructor(void)
{
print_header("FT ITERATOR CONSTRUCTOR");
std::cout << "For ft::map<std::string, std::string> map_countries" << std::endl;
ft::map<std::string, std::string> map_countries;
map_countries["New-york"] = "USA";
map_countries["Sydney"] = "Australia";
map_countries["Paris"] = "France";
map_countries["New-Delhi"] = "India";
map_countries["Berlin"] = "Germany";
map_countries["Brest"] = "France";
map_countries["Prague"] = "Czech Republic";
map_countries["Dublin"] = "Prague";
std::cout << "map_countries :" << std::endl << map_countries << std::endl;
ft::map<std::string, std::string> cpy_map_countries(map_countries.begin(), map_countries.end());
std::cout << "ft::map<std::string, std::string> cpy_map_countries(map_countries.begin(), map_countries.end());" << std::endl;
std::cout << "cpy_map_countries :" << std::endl << cpy_map_countries << std::endl;
test_iterator_constructor_std();
}
static void test_operations_std(void)
{
print_header("STD OPERATIONS");
std::cout << "#-- COUNT FUNCTION --#" << std::endl << std::endl;
std::cout << "For a <int, int> map int_int_map;" << std::endl << std::endl;
std::map<int, int> int_int_map;
int_int_map[19] = 19;
int_int_map[12] = 12;
int_int_map[53] = 53;
int_int_map[24] = 24;
int_int_map[82] = 82;
int_int_map[23] = 23;
int_int_map[49] = 49;
int_int_map[59] = 59;
int_int_map[98] = 98;
int_int_map[87] = 87;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "int_int_map.count(33453) : " << int_int_map.count(33453) << std::endl;
std::cout << "int_int_map.count(98) : " << int_int_map.count(98) << std::endl;
std::cout << "int_int_map.count(12) : " << int_int_map.count(12) << std::endl;
std::cout << "int_int_map.count(49) : " << int_int_map.count(49) << std::endl;
std::cout << "int_int_map.count(442) : " << int_int_map.count(442) << std::endl << std::endl;
std::cout << "#-- LOWER BOUND FUNCTION --#" << std::endl << std::endl;
std::cout << "(*int_int_map.lower_bound(23)).first : " << (*int_int_map.lower_bound(23)).first << std::endl;
std::cout << "(*int_int_map.lower_bound(1)).first : " << (*int_int_map.lower_bound(1)).first << std::endl;
std::cout << "(*int_int_map.lower_bound(59)).first : " << (*int_int_map.lower_bound(59)).first << std::endl;
std::cout << "#-- UPPER BOUND FUNCTION --#" << std::endl << std::endl;
std::cout << "(*int_int_map.upper_bound(23)).first : " << (*int_int_map.upper_bound(23)).first << std::endl;
std::cout << "(*int_int_map.upper_bound(1)).first : " << (*int_int_map.upper_bound(1)).first << std::endl;
std::cout << "(*int_int_map.upper_bound(59)).first : " << (*int_int_map.upper_bound(59)).first << std::endl;
std::cout << "#-- EQUAL RANGE FUNCTION --#" << std::endl << std::endl;
std::pair<std::map<int, int>::iterator,std::map<int, int>::iterator> ret;
std::pair<std::map<int, int>::const_iterator,std::map<int, int>::const_iterator> ret_const;
ret = int_int_map.equal_range(1);
std::cout << "ret = int_int_map.equal_range(1);" << std::endl;
std::cout << "*(ret.first) : " << *(ret.first) << std::endl;
std::cout << "*(ret.second) : " << *(ret.second) << std::endl << std::endl;
ret_const = int_int_map.equal_range(59);
std::cout << "ret_const = int_int_map.equal_range(59);" << std::endl;
std::cout << "*(ret_const.first) : " << *(ret_const.first) << std::endl;
std::cout << "*(ret_const.second) : " << *(ret_const.second) << std::endl << std::endl;
std::cout << std::endl;
next_test();
}
static void test_operations(void)
{
print_header("FT OPERATIONS");
std::cout << "#-- COUNT FUNCTION --#" << std::endl << std::endl;
std::cout << "For a <int, int> map int_int_map;" << std::endl << std::endl;
ft::map<int, int> int_int_map;
int_int_map[19] = 19;
int_int_map[12] = 12;
int_int_map[53] = 53;
int_int_map[24] = 24;
int_int_map[82] = 82;
int_int_map[23] = 23;
int_int_map[49] = 49;
int_int_map[59] = 59;
int_int_map[98] = 98;
int_int_map[87] = 87;
std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
std::cout << "int_int_map.count(33453) : " << int_int_map.count(33453) << std::endl;
std::cout << "int_int_map.count(98) : " << int_int_map.count(98) << std::endl;
std::cout << "int_int_map.count(12) : " << int_int_map.count(12) << std::endl;
std::cout << "int_int_map.count(49) : " << int_int_map.count(49) << std::endl;
std::cout << "int_int_map.count(442) : " << int_int_map.count(442) << std::endl << std::endl;
std::cout << "#-- LOWER BOUND FUNCTION --#" << std::endl << std::endl;
ft::map<int, int>::iterator it;
ft::map<int, int>::const_iterator it_const;
std::cout << "(*int_int_map.lower_bound(23)).first : " << \
(*(it = int_int_map.lower_bound(23))).first << \
std::endl;
std::cout << "(*int_int_map.lower_bound(1)).first : " << \
(*(it_const = int_int_map.lower_bound(1))).first << \
std::endl;
std::cout << "(*int_int_map.lower_bound(59)).first : " << \
(*(it = int_int_map.lower_bound(59))).first << \
std::endl << std::endl;
std::cout << "#-- UPPER BOUND FUNCTION --#" << std::endl << std::endl;
std::cout << "(*int_int_map.upper_bound(23)).first : " << \
(*(it = int_int_map.upper_bound(23))).first << \
std::endl;
std::cout << "(*int_int_map.upper_bound(1)).first : " << \
(*(it_const = int_int_map.upper_bound(1))).first << \
std::endl;
std::cout << "(*int_int_map.upper_bound(59)).first : " << \
(*(it = int_int_map.upper_bound(59))).first << \
std::endl << std::endl;
std::cout << "#-- EQUAL RANGE FUNCTION --#" << std::endl << std::endl;
ft::pair<ft::map<int, int>::iterator,ft::map<int, int>::iterator> ret;
ft::pair<ft::map<int, int>::const_iterator,ft::map<int, int>::const_iterator> ret_const;
ret = int_int_map.equal_range(1);
std::cout << "ret = int_int_map.equal_range(1);" << std::endl;
std::cout << "*(ret.first) : " << *(ret.first) << std::endl;
std::cout << "*(ret.second) : " << *(ret.second) << std::endl << std::endl;
ret_const = int_int_map.equal_range(59);
std::cout << "ret_const = int_int_map.equal_range(59);" << std::endl;
std::cout << "*(ret_const.first) : " << *(ret_const.first) << std::endl;
std::cout << "*(ret_const.second) : " << *(ret_const.second) << std::endl << std::endl;
test_operations_std();
}
template <typename T>
struct strLenLess
{
bool operator()(const T &lhs, const T &rhs) const
{
return (lhs.size() < rhs.size());
}
};
template <typename T>
struct strLenGreater
{
bool operator()(const T &lhs, const T &rhs) const
{
return (lhs.size() > rhs.size());
}
};
static void test_other_compare_std(void)
{
print_header("STD OTHER COMPARE TEST");
std::map<int, int, std::greater<int> > mymap;
std::cout << "std::map<int, int, std::greater<int> > mymap;" << std::endl << std::endl;
mymap[59] = 59;
mymap[26] = 26;
mymap[68] = 68;
mymap[7] = 7;
mymap[43] = 43;
mymap[65] = 65;
mymap[77] = 77;
mymap[1] = 1;
std::cout << "mymap : " << std::endl << mymap << std::endl;
std::map<std::string, std::string, strLenLess<std::string> > str_str_map;
std::cout << "std::map<std::string, std::string, strLenGreater<int> > std_str_map;" << std::endl << std::endl;
str_str_map["Fils"] = "Fils";
str_str_map["Corde"] = "Corde";
str_str_map["Cactus"] = "Cactus";
str_str_map["Section"] = "Section";
str_str_map["Feuillet"] = "Feuillet";
str_str_map["Effacement"] = "Effacement";
str_str_map["Radiographie"] = "Radiographie";
std::cout << "str_str_map : " << std::endl << str_str_map << std::endl;
std::map<std::string, std::string, strLenGreater<std::string> > another_map;
std::cout << "std::map<std::string, std::string, strLenGreater<int> > another_map;" << std::endl << std::endl;
another_map["Fils"] = "Fils";
another_map["Corde"] = "Corde";
another_map["Cactus"] = "Cactus";
another_map["Section"] = "Section";
another_map["Feuillet"] = "Feuillet";
another_map["Effacement"] = "Effacement";
another_map["Radiographie"] = "Radiographie";
std::cout << "another_map : " << std::endl << another_map << std::endl;
next_test();
}
static void test_other_compare(void)
{
print_header("FT OTHER COMPARE TEST");
ft::map<int, int, std::greater<int> > mymap;
std::cout << "ft::map<int, int, std::greater<int> > mymap;" << std::endl << std::endl;
mymap[59] = 59;
mymap[26] = 26;
mymap[68] = 68;
mymap[7] = 7;
mymap[43] = 43;
mymap[65] = 65;
mymap[77] = 77;
mymap[1] = 1;
std::cout << "mymap : " << std::endl << mymap << std::endl;
ft::map<std::string, std::string, strLenLess<std::string> > str_str_map;
std::cout << "ft::map<std::string, std::string, strLenGreater<int> > std_str_map;" << std::endl << std::endl;
str_str_map["Fils"] = "Fils";
str_str_map["Corde"] = "Corde";
str_str_map["Cactus"] = "Cactus";
str_str_map["Section"] = "Section";
str_str_map["Feuillet"] = "Feuillet";
str_str_map["Effacement"] = "Effacement";
str_str_map["Radiographie"] = "Radiographie";
std::cout << "str_str_map : " << std::endl << str_str_map << std::endl;
ft::map<std::string, std::string, strLenGreater<std::string> > another_map;
std::cout << "ft::map<std::string, std::string, strLenGreater<int> > another_map;" << std::endl << std::endl;
another_map["Fils"] = "Fils";
another_map["Corde"] = "Corde";
another_map["Cactus"] = "Cactus";
another_map["Section"] = "Section";
another_map["Feuillet"] = "Feuillet";
another_map["Effacement"] = "Effacement";
another_map["Radiographie"] = "Radiographie";
std::cout << "another_map : " << std::endl << another_map << std::endl;
test_other_compare_std();
}
int main(void)
{
test_operator_brackets();
test_iterator();
test_reverse_iterator();
test_erase_by_key();
test_erase_by_iterators();
test_clear();
test_find();
test_insert();
test_copy();
test_swap();
test_key_compare();
test_value_compare();
test_iterator_constructor();
test_operations();
test_other_compare();
test_other_compare();
return (0);
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* const_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/01 16:07:03 by jereligi #+# #+# */
/* Updated: 2021/03/16 15:24:29 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CONST_ITERATOR_HPP
#define CONST_ITERATOR_HPP
#include "iterator.hpp"
namespace ft
{
template <typename T>
class const_iterator
{
public:
static const bool is_iterator = true;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
const_iterator(void) {};
const_iterator(const T* src) { _ptr = src; };
const_iterator(Iterator<T> const &src) { _ptr = src.operator->(); };
const_iterator(const_iterator const &src) { *this = src; } ;
virtual ~const_iterator() {};
const_iterator &operator=(const_iterator const &src) {
_ptr = src.operator->();
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != | > | >= | < | <= *****
*******************************************/
bool operator==(const_iterator const& src) const {
return (_ptr == src._ptr);
};
bool operator!=(const_iterator const& src) const {
return (_ptr != src._ptr);
};
bool operator>(const_iterator const& src) const {
return (_ptr > src._ptr);
};
bool operator>=(const_iterator const& src) const {
return (_ptr >= src._ptr);
};
bool operator<(const_iterator const& src) const {
return (_ptr < src._ptr);
};
bool operator<=(const_iterator const& src) const {
return (_ptr <= src._ptr);
};
/*******************************************
***** Operator Arithmetics *****
***** + | - | ++ | -- | += | -= *****
*******************************************/
const_iterator operator+(difference_type src) {
return (const_iterator(_ptr + src));
};
const_iterator operator-(difference_type src) {
return (const_iterator(_ptr - src));
};
difference_type operator+(const_iterator src) {
return (_ptr + src._ptr);
};
difference_type operator-(const_iterator src) {
return (_ptr - src._ptr);
};
const_iterator operator++() {
_ptr++;
return (*this);
};
const_iterator operator++(int) {
_ptr++;
return (const_iterator(_ptr - 1));
};
const_iterator operator--() {
_ptr--;
return (*this);
};
const_iterator operator--(int) {
_ptr--;
return (const_iterator(_ptr + 1));
};
void operator+=(difference_type src) {
_ptr += src;
};
void operator-=(difference_type src) {
_ptr -= src;
};
/*******************************************
***** Operator deferencing *****
***** * | [] | -> *****
*******************************************/
const T& operator*() const {
return (*_ptr);
};
const T& operator[](difference_type src) const {
return (*(_ptr + src));
};
const T* operator->() {
return (_ptr);
};
const T* operator->() const {
return (_ptr);
};
private:
const T* _ptr;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* reverse_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/25 11:06:31 by jereligi #+# #+# */
/* Updated: 2021/03/16 16:33:43 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef REVERSE_ITERATOR_HPP
#define REVERSE_ITERATOR_HPP
#include "../../utils.hpp"
#include "iterator.hpp"
namespace ft
{
template <typename T, typename Node>
class reverse_iterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
reverse_iterator(void) {};
reverse_iterator(Node* src) { _node = src; };
reverse_iterator(Iterator<T, Node> const &src) { *this = src; } ;
reverse_iterator(const reverse_iterator &src) { _node = src.operator->(); };
virtual ~reverse_iterator() {};
reverse_iterator &operator=(reverse_iterator const &src) {
_node = src._node;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator==(reverse_iterator const& src) const {
return (_node == src._node);
};
bool operator!=(reverse_iterator const& src) const {
return (_node != src._node);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
reverse_iterator operator++() {
_node = _node->prev;
return (*this);
};
reverse_iterator operator++(int) {
reverse_iterator tmp = *this;
--(*this);
return (tmp);
};
reverse_iterator operator--() {
_node = _node->next;
return (*this);
};
reverse_iterator operator--(int) {
reverse_iterator tmp = *this;
++(*this);
return (tmp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
const_reference operator*() const {
return (_node->val);
};
reference operator*() {
return (_node->val);
};
Node* operator->() {
return (_node);
};
Node* operator->() const {
return (_node);
};
private:
Node *_node;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 10:49:10 by jereligi #+# #+# */
/* Updated: 2021/03/17 14:21:19 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef STACK_HPP
#define STACK_HPP
#include "../list/list.hpp"
namespace ft
{
template <class T, class Container = list<T> >
class stack
{
public:
typedef typename list<T>::value_type value_type;
typedef typename list<T>::size_type size_type;
typedef Container container_type;
explicit stack (const container_type& ctrn = container_type()) : _container(ctrn) {};
stack(stack const &src) : _container(src._container) {};
stack &operator=(stack const &src) {
_container = src._container;
return (*this);
}
virtual ~stack() {};
bool empty() const {
return (_container.empty());
}
size_type size() const {
return (_container.size());
}
value_type& top() {
return (_container.back());
}
const value_type& top() const {
return (_container.back());
}
void push (const value_type& val) {
_container.push_back(val);
}
void pop() {
_container.pop_back();
}
template <class Tx, class Container_x>
friend bool operator== (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator!= (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator< (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator<= (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator> (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator>= (const stack<Tx,Container_x>& lhs, const stack<Tx,Container_x>& rhs);
private:
container_type _container;
};
template <class T, class Container>
bool operator== (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container == rhs._container);
}
template <class T, class Container>
bool operator!= (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container != rhs._container);
}
template <class T, class Container>
bool operator< (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container < rhs._container);
}
template <class T, class Container>
bool operator<= (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container <= rhs._container);
}
template <class T, class Container>
bool operator> (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container > rhs._container);
}
template <class T, class Container>
bool operator>= (const stack<T,Container>& lhs, const stack<T,Container>& rhs) {
return (lhs._container >= rhs._container);
}
}
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/03 14:06:14 by jereligi #+# #+# */
/* Updated: 2021/04/03 14:11:21 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef UTILS_TESTER_HPP
# define UTILS_TESTER_HPP
# include <vector>
# include <iostream>
# include <memory>
# include "../map.hpp"
# define FT_TEST false
# define STD_TEST true
template <typename Tkey, typename Tvalue>
std::ostream &operator<<(std::ostream &o, std::pair<Tkey, Tvalue> const &i)
{
std::cout << \
"key = " << i.first << ", value = " << i.second << " ";
return (o);
};
template <class Tkey, class Tvalue, class Compare>
std::ostream &operator<<(std::ostream &o, ft::map<Tkey, Tvalue, Compare> &i)
{
if (i.size() == 0)
{
o << "{}";
return (o);
}
for (typename ft::map<Tkey, Tvalue, Compare>::const_iterator it = i.begin();
it != i.end();
it++)
o << *it << std::endl;
return (o);
};
template <typename Tkey, typename Tvalue>
std::ostream &operator<<(std::ostream &o, std::map<Tkey, Tvalue> &i)
{
if (i.size() == 0)
{
o << "{}";
return (o);
}
for (typename std::map<Tkey, Tvalue>::const_iterator it = i.begin();
it != i.end();
it++)
o << *it << std::endl;
return (o);
};
template <typename Tkey, typename Tvalue, class Compare>
std::ostream &operator<<(std::ostream &o, std::map<Tkey, Tvalue, Compare> &i)
{
if (i.size() == 0)
{
o << "{}";
return (o);
}
for (typename std::map<Tkey, Tvalue, Compare>::const_iterator it = i.begin();
it != i.end();
it++)
o << *it << std::endl;
return (o);
};
void print_header(std::string content)
{
std::cout << content << std::endl;
}
void menu(std::vector<void (*)()> lst_funs, std::vector<std::string> lst_messages, std::string title);
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_essentials.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 15:27:38 by jereligi #+# #+# */
/* Updated: 2021/03/17 16:53:02 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
void test_constructors_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor fill" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "std::list<int> lst(10, 10);" << COLOR_RESET << std::endl;
std::list<int> lst(10, 10);
std::cout << std::endl << "lst = { ";
for (std::list<int>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_GREEN << "std::list<std::string> lst2(10, \"coucou\");" << COLOR_RESET << std::endl;
std::list<std::string> lst2(10, "coucou");
std::cout << std::endl << "lst2 = { ";
for (std::list<std::string>::iterator it = lst2.begin(); it != lst2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor range" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "std::list<std::string> lst3(lst2.begin(), lst2.end());" << COLOR_RESET << std::endl;
std::list<std::string> lst3(lst2.begin(), lst2.end());
std::cout << std::endl << "lst3 = { ";
for (std::list<std::string>::iterator it = lst3.begin(); it != lst3.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor copy" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "std::list<std::string> lst4;" << COLOR_RESET << std::endl;
std::list<std::string> lst4;
lst4 = lst3;
std::cout << COLOR_GREEN << "lst4 = lst3;" << COLOR_RESET << std::endl << std::endl;
std::cout << "lst4 = { ";
for (std::list<std::string>::iterator it = lst4.begin(); it != lst4.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
next_test();
}
void test_constructors(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test construtor " << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor fill" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "ft::list<int> lst(10, 10);" << COLOR_RESET << std::endl;
ft::list<int> lst(10, 10);
std::cout << std::endl << "lst = { ";
for (ft::list<int>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_GREEN << "ft::list<std::string> lst2(10, \"coucou\");" << COLOR_RESET << std::endl;
ft::list<std::string> lst2(10, "coucou");
std::cout << std::endl << "lst2 = { ";
for (ft::list<std::string>::iterator it = lst2.begin(); it != lst2.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor range" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "ft::list<std::string> lst3(lst2.begin(), lst2.end());" << COLOR_RESET << std::endl;
ft::list<std::string> lst3(lst2.begin(), lst2.end());
std::cout << std::endl << "lst3 = { ";
for (ft::list<std::string>::iterator it = lst3.begin(); it != lst3.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::cout << COLOR_YELLOW <<"constructor copy" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_GREEN << "ft::list<std::string> lst4;" << COLOR_RESET << std::endl;
ft::list<std::string> lst4;
lst4 = lst3;
std::cout << COLOR_GREEN << "lst4 = lst3;" << COLOR_RESET << std::endl << std::endl;
std::cout << "lst4 = { ";
for (ft::list<std::string>::iterator it = lst4.begin(); it != lst4.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
test_constructors_std();
}
void test_essentials_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "push_back :" << COLOR_RESET << std::endl;
std::cout << " For list of ints : EMPTY" << std::endl;
std::list<int> lst1;
std::cout << "lst1.push_back(10);" << std::endl;
std::cout << "lst1.push_back(20);" << std::endl;
std::cout << "lst1.push_back(30);" << std::endl << std::endl;
lst1.push_back(10);
lst1.push_back(20);
lst1.push_back(30);
std::cout << COLOR_YELLOW << "back :" << COLOR_RESET << std::endl;
std::cout << " With the same list :" << std::endl;
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "pop_back :" << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl;
lst1.pop_back();
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl;
lst1.pop_back();
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl << std::endl;
lst1.pop_back();
std::cout << "lst1.push_back(42);" << std::endl;
lst1.push_back(42);
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl << std::endl;
lst1.pop_back();
std::cout << "Size of lst1 = " << COLOR_GREEN << lst1.size() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "push_front :" << COLOR_RESET << std::endl;
std::cout << " For list of ints : EMPTY" << std::endl;
std::list<int> lst2;
std::cout << "lst2.push_front(10);" << std::endl;
std::cout << "lst2.push_front(20);" << std::endl;
std::cout << "lst2.push_front(30);" << std::endl << std::endl;
lst2.push_front(10);
lst2.push_front(20);
lst2.push_front(30);
std::cout << COLOR_YELLOW << "front :" << COLOR_RESET << std::endl;
std::cout << " With the same list :" << std::endl;
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "pop_front :" << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl;
lst2.pop_front();
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl;
lst2.pop_front();
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl << std::endl;
lst2.pop_front();
std::cout << "lst2.push_front(42);" << std::endl;
lst2.push_front(42);
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl << std::endl;
lst2.pop_front();
std::cout << "Size of lst2 = " << COLOR_GREEN << lst2.size() << COLOR_RESET << std::endl << std::endl << std::endl;
next_test();
}
void test_essentials(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test essentials | push_front | push_back | \
pop_front | pop_back | front | back " << std::endl << std::endl;
std::cout << COLOR_YELLOW << "push_back :" << COLOR_RESET << std::endl;
std::cout << " For list of ints : EMPTY" << std::endl;
ft::list<int> lst1;
std::cout << "lst1.push_back(10);" << std::endl;
std::cout << "lst1.push_back(20);" << std::endl;
std::cout << "lst1.push_back(30);" << std::endl << std::endl;
lst1.push_back(10);
lst1.push_back(20);
lst1.push_back(30);
std::cout << COLOR_YELLOW << "back :" << COLOR_RESET << std::endl;
std::cout << " With the same list :" << std::endl;
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "pop_back :" << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl;
lst1.pop_back();
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl;
lst1.pop_back();
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl << std::endl;
lst1.pop_back();
std::cout << "lst1.push_back(42);" << std::endl;
lst1.push_back(42);
std::cout << "lst1.back() = " << COLOR_GREEN << lst1.back() << COLOR_RESET << std::endl;
std::cout << "lst1.pop_back();" << std::endl << std::endl;
lst1.pop_back();
std::cout << "Size of lst1 = " << COLOR_GREEN << lst1.size() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "push_front :" << COLOR_RESET << std::endl;
std::cout << " For list of ints : EMPTY" << std::endl;
ft::list<int> lst2;
std::cout << "lst2.push_front(10);" << std::endl;
std::cout << "lst2.push_front(20);" << std::endl;
std::cout << "lst2.push_front(30);" << std::endl << std::endl;
lst2.push_front(10);
lst2.push_front(20);
lst2.push_front(30);
std::cout << COLOR_YELLOW << "front :" << COLOR_RESET << std::endl;
std::cout << " With the same list :" << std::endl;
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "pop_front :" << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl;
lst2.pop_front();
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl;
lst2.pop_front();
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl << std::endl;
lst2.pop_front();
std::cout << "lst2.push_front(42);" << std::endl;
lst2.push_front(42);
std::cout << "lst2.front() = " << COLOR_GREEN << lst2.front() << COLOR_RESET << std::endl;
std::cout << "lst2.pop_front();" << std::endl << std::endl;
lst2.pop_front();
std::cout << "Size of lst2 = " << COLOR_GREEN << lst2.size() << COLOR_RESET << std::endl << std::endl << std::endl;
test_essentials_std();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_iterator.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 15:55:29 by jereligi #+# #+# */
/* Updated: 2021/03/17 16:41:23 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "constant.hpp"
void test_operator_over_ite_std(void)
{
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::list<bool> lst;
lst.push_back(true);
lst.push_back(false);
lst.push_back(false);
lst.push_back(true);
lst.push_back(false);
lst.push_back(true);
std::cout << std::endl << "For a bool list lst = { ";
for (std::list<bool>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
std::list<bool>::iterator it_begin = lst.begin();
std::list<bool>::iterator it_end = lst.end();
std::cout << "For it_begin = lst.begin()" << std::endl;
std::cout << "For it_end = lst.end()" << std::endl << std::endl;
std::cout << "it_begin == it_end = " << COLOR_GREEN << std::boolalpha << (it_begin == it_end) << COLOR_RESET << std::endl;
std::cout << "it_begin == it_begin = " << COLOR_GREEN << std::boolalpha << (it_begin == it_begin) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "operator!=() " << COLOR_RESET << std::endl;
std::cout << "it_begin != it_end = " << COLOR_GREEN << std::boolalpha << (it_begin != it_end) << COLOR_RESET << std::endl;
std::cout << "it_begin != it_begin = " << COLOR_GREEN << std::boolalpha << (it_begin != it_begin) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "operator*() " << COLOR_RESET << std::endl << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl << std::endl;
next_test();
}
void test_operator_over_ite(void)
{
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test overload operator | == | != | * " << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "operator==() " << COLOR_RESET << std::endl;
ft::list<bool> lst;
lst.push_back(true);
lst.push_back(false);
lst.push_back(false);
lst.push_back(true);
lst.push_back(false);
lst.push_back(true);
std::cout << std::endl << "For a bool list lst = { ";
for (ft::list<bool>::iterator it = lst.begin(); it != lst.end(); it++)
std::cout << COLOR_CYAN << std::boolalpha << COLOR_RESET << *it << " ";
std::cout << "}" << std::endl << std::endl;
ft::list<bool>::iterator it_begin = lst.begin();
ft::list<bool>::iterator it_end = lst.end();
std::cout << "For it_begin = lst.begin()" << std::endl;
std::cout << "For it_end = lst.end()" << std::endl << std::endl;
std::cout << "it_begin == it_end = " << COLOR_GREEN << std::boolalpha << (it_begin == it_end) << COLOR_RESET << std::endl;
std::cout << "it_begin == it_begin = " << COLOR_GREEN << std::boolalpha << (it_begin == it_begin) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "operator!=() " << COLOR_RESET << std::endl;
std::cout << "it_begin != it_end = " << COLOR_GREEN << std::boolalpha << (it_begin != it_end) << COLOR_RESET << std::endl;
std::cout << "it_begin != it_begin = " << COLOR_GREEN << std::boolalpha << (it_begin != it_begin) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "operator*() " << COLOR_RESET << std::endl << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl;
std::cout << "*(it_begin++) = " << COLOR_GREEN << std::boolalpha << *(it_begin++) << COLOR_RESET << std::endl << std::endl;
test_operator_over_ite_std();
}
void test_iterator_std(void)
{
std::list<std::string> lst;
std::cout << COLOR_BLUE << "----- std::list -----" << COLOR_RESET << std::endl << std::endl;
std::cout << "For a string list : { youtube, twitch, reddit, facebook }" << std::endl;
lst.push_back("youtube");
lst.push_back("twitch");
lst.push_back("reddit");
lst.push_back("facebook");
std::cout << "For it.begin != it.end();" << std::endl;
std::cout << "++it;" << std::endl;
for (std::list<std::string>::iterator it = lst.begin(); it != lst.end(); ++it)
std::cout << COLOR_GREEN << *it << COLOR_RESET << std::endl;
std::cout << std::endl;
std::cout << "*(lst.begin()) = " << COLOR_GREEN << *(lst.begin()) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "---- ITERATOR OVERLOADS ----" << COLOR_RESET << std::endl;
std::list<std::string>::iterator it2 = lst.begin();
std::cout << "it2 = lst.begin();" << std::endl;
std::cout << "++it2 = " << COLOR_GREEN << *(++it2) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl;
std::cout << "--it2 = " << COLOR_GREEN << *(--it2) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl << std::endl;
std::cout << "it2++ = " << COLOR_GREEN << *(it2++) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl;
std::cout << "it2-- = " << COLOR_GREEN << *(it2--) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl << std::endl;
next_test();
}
void test_iterator(void)
{
ft::list<std::string> lst;
std::cout << ft_list << std::endl;
std::cout << COLOR_CYAN << "Test iterator | begin | end | it++ | it-- " << COLOR_RESET << std::endl << std::endl;
std::cout << "For a string list : { youtube, twitch, reddit, facebook }" << std::endl;
lst.push_back("youtube");
lst.push_back("twitch");
lst.push_back("reddit");
lst.push_back("facebook");
std::cout << "For it.begin != it.end();" << std::endl;
std::cout << "++it;" << std::endl;
for (ft::list<std::string>::iterator it = lst.begin(); it != lst.end(); ++it)
std::cout << COLOR_GREEN << *it << COLOR_RESET << std::endl;
std::cout << std::endl;
std::cout << "*(lst.begin()) = " << COLOR_GREEN << *(lst.begin()) << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "---- ITERATOR OVERLOADS ----" << COLOR_RESET << std::endl;
ft::list<std::string>::iterator it2 = lst.begin();
std::cout << "it2 = lst.begin();" << std::endl;
std::cout << "++it2 = " << COLOR_GREEN << *(++it2) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl;
std::cout << "--it2 = " << COLOR_GREEN << *(--it2) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl << std::endl;
std::cout << "it2++ = " << COLOR_GREEN << *(it2++) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl;
std::cout << "it2-- = " << COLOR_GREEN << *(it2--) << COLOR_RESET << std::endl;
std::cout << *it2 << std::endl << std::endl;
test_iterator_std();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Jeanxavier <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/04 11:46:10 by jereligi #+# #+# */
/* Updated: 2021/04/03 18:49:04 by Jeanxavier ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIST_HPP
#define LIST_HPP
#include "../utils.hpp"
#include "./iterator/iterator.hpp"
#include "./iterator/const_iterator.hpp"
#include "./iterator/reverse_iterator.hpp"
#include "./iterator/const_reverse_iterator.hpp"
#include <algorithm>
#include <limits>
template <typename T>
struct Node
{
Node *prev;
Node *next;
T val;
};
namespace ft
{
template <class T, class Allocator = std::allocator<T> >
class list
{
public:
typedef T value_type;
typedef Allocator allocator_type;
typedef typename std::size_t size_type;
typedef typename std::ptrdiff_t difference_type;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef Node<T> node_type;
typedef typename ft::Iterator<T, node_type> iterator;
typedef typename ft::const_iterator<T, node_type> const_iterator;
typedef typename ft::reverse_iterator<T, node_type> reverse_iterator;
typedef typename ft::const_reverse_iterator<T, node_type> const_reverse_iterator;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
//default
explicit list (const allocator_type& alloc = allocator_type())
{
_node = new Node<T>;
_node->next = _node;
_node->prev = _node;
// _node->val = 0;
_size = 0;
_alloc = alloc;
}
//fill
explicit list (size_type n, const value_type& val = value_type(),
const allocator_type& alloc = allocator_type())
{
_node = new Node<T>;
_node->next = _node;
_node->prev = _node;
// _node->val = 0;
_size = 0;
_alloc = alloc;
for (size_type i = 0; i < n; i++)
push_back(val);
}
//range
template <class InputIterator>
list (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type(),
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
_node = new Node<T>;
_node->next = _node;
_node->prev = _node;
// _node->val = 0;
_size = 0;
_alloc = alloc;
while (first != last)
{
push_back(*first);
first++;
}
}
//copy
list (const list& x)
{
_node = new Node<T>;
_node->next = _node;
_node->prev = _node;
// _node->val = 0;
_size = 0;
_alloc = allocator_type();
*this = x;
}
//destructor
virtual ~list(){
this->clear();
delete _node;
}
list& operator=(const list& x)
{
clear();
for (const_iterator it = x.begin(); it != x.end(); it++)
push_back(*it);
return (*this);
}
/*******************************************
***** Iterators *****
*******************************************/
iterator begin() {
return (iterator(_node->next));
}
const_iterator begin() const {
return (const_iterator(_node->next));
}
iterator end() {
return (iterator(_node));
}
const_iterator end() const
{
return (const_iterator(_node));
}
reverse_iterator rbegin() {
return (reverse_iterator(_node));
}
const_reverse_iterator rbegin() const {
return (const_reverse_iterator(_node));
}
reverse_iterator rend() {
return (reverse_iterator(_node->prev));
}
const_reverse_iterator rend() const {
return (reverse_const_iterator(_node->prev));
}
/*******************************************
***** Capacity *****
*******************************************/
bool empty() const
{
if (_size > 0)
return (0);
return (1);
}
size_type size() const {
return (_size);
}
size_type max_size() const {
return (std::numeric_limits<difference_type>::max() / (sizeof(Node<T>) / 2 ?: 1));
}
void resize (size_type n, value_type val = value_type())
{
if (n < _size)
{
while (n < _size)
pop_back();
}
else
{
for (size_type i = _size; i < n; i++)
push_back(val);
}
}
/*******************************************
***** Element access *****
*******************************************/
reference front() {
return (_node->next->val);
}
const_reference front() const {
return (front());
}
reference back() {
return (_node->prev->val);
}
const_reference back() const {
return (back());
}
/*******************************************
***** Modifiers *****
*******************************************/
template <class InputIterator>
void assign (InputIterator first, InputIterator last,
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
if (empty() == 0)
clear();
while (first != last)
{
push_back(*first);
first++;
}
}
void assign (size_type n, const value_type& val)
{
if (empty() == 0)
clear();
for (size_type i = 0; i < n; i++)
push_back(val);
}
iterator insert (iterator position, const value_type& val)
{
Node<T> *new_elem = new Node<T>;
Node<T> *tmp = position.operator->();
new_elem->val = val;
new_elem->next = tmp->prev->next;
new_elem->prev = tmp->prev;
tmp->prev->next = new_elem;
tmp->prev = new_elem;
_size++;
return (--position);
}
void insert(iterator position, size_type n, const value_type& val)
{
for (size_type i = 0; i < n; i++)
insert(position, val);
}
template <class InputIterator>
void insert (iterator position, InputIterator first, InputIterator last,
typename ft::enable_if<InputIterator::is_iterator, InputIterator>::type = NULL)
{
while (first != last)
{
insert(position, *first);
first++;
}
}
iterator erase (iterator position)
{
Node<T> *tmp = position.operator->();
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
delete tmp;
_size--;
return (position);
}
iterator erase (iterator first, iterator last)
{
while (first != last)
erase(first++);
return (first);
}
void push_back (const value_type& val)
{
Node<T> *new_node = new Node<T>;
new_node->next = _node;
new_node->prev = _node->prev;
new_node->val = val;
_node->prev->next = new_node;
_node->prev = new_node;
_size++;
}
void pop_back()
{
Node<T> *tmp = _node->prev;
_node->prev->prev->next = _node;
_node->prev = _node->prev->prev;
delete tmp;
_size--;
}
void push_front (const value_type& val)
{
Node<T> *new_node = new Node<T>;
new_node->next = _node->next;
new_node->prev = _node;
new_node->val = val;
_node->next->prev = new_node;
_node->next = new_node;
_size++;
}
void pop_front()
{
Node<T> *tmp = _node->next;
_node->next = _node->next->next;
delete tmp;
_size--;
}
void clear()
{
while (_size > 0)
pop_back();
}
void swap (list& x)
{
Node<T> *tmp = _node;
size_type tmp_size = _size;
_node = x._node;
x._node = tmp;
_size = x._size;
x._size = tmp_size;
}
/*******************************************
***** List operations *****
*******************************************/
void splice (iterator position, list& x)
{
splice(position, x, x.begin(), x.end());
}
void splice(iterator position, list& x, iterator i)
{
Node<T> *node = i.operator->();
Node<T> *dest = position.operator->();
// delete node from x
node->next->prev = node->prev;
node->prev->next = node->next;
// init node
node->next = dest;
node->prev = dest->prev;
// add node
dest->prev->next = node;
dest->prev = node;
x._size--;
_size++;
}
void splice(iterator position, list& x, iterator first, iterator last)
{
while (first != last)
splice(position, x, first++);
}
void remove (const value_type& val)
{
iterator tmp;
for (iterator it = begin(); it != end(); it++)
{
if (*it == val)
{
tmp = ++it;
erase(--it);
it = --tmp;
}
}
}
template <class Predicate>
void remove_if (Predicate pred)
{
iterator tmp;
for (iterator it = begin(); it != end(); it++)
{
if (pred(*it))
{
tmp = ++it;
erase(--it);
it = --tmp;
}
}
}
void unique()
{
iterator elem = begin();
iterator next = ++begin();
while (next != end())
{
if (*elem == *next)
{
erase(elem);
}
elem = next;
++next;
}
}
template <class BinaryPredicate>
void unique (BinaryPredicate binary_pred)
{
iterator elem = begin();
iterator next = ++begin();
while (next != end())
{
if (binary_pred(*next, *elem) == 1)
{
erase(next);
elem = begin();
next = ++begin();
}
else
{
elem = next;
++next;
}
}
}
void merge (list& x)
{
merge(x, _comp);
}
template <class Compare>
void merge (list& x, Compare comp)
{
iterator it_x = x.begin();
iterator it_this = begin();
while (it_x != x.end() && it_this != end())
{
if (comp(*it_x, *it_this))
splice(it_this, x, it_x++);
else
it_this++;
}
while (it_x != x.end())
splice(end(), x, it_x++);
}
void sort()
{
sort(_comp);
}
template <class Compare>
void sort(Compare comp)
{
iterator elem = begin();
iterator next = ++begin();
while (next != end())
{
if (*elem != *next && comp(*elem, *next) == 0)
{
splice(elem, *this, next);
elem = begin();
next = ++begin();
}
else
{
elem = next;
next++;
}
}
}
void reverse()
{
Node<T> *elem;
Node<T> *tmp;
iterator it = begin();
while (it != --end())
{
elem = it.operator->();
tmp = elem->prev;
elem->prev = elem->next;
elem->next = tmp;
it++;
}
}
private:
Node<T> *_node;
size_type _size;
allocator_type _alloc;
static bool _comp(T &x, T &y) {
return (x < y);
}
};
template <class T, class Alloc>
bool operator== (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
typename ft::list<T>::const_iterator it_r = rhs.begin();
typename ft::list<T>::const_iterator it_l = lhs.begin();
if (lhs.size() != rhs.size())
return (false);
while (it_l != lhs.end() && it_r != rhs.end() && *it_l == *it_r)
{
it_l++;
it_r++;
}
return (it_l == lhs.end() && it_r == rhs.end());
}
template <class T, class Alloc>
bool operator!= (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
return (!(lhs == rhs));
}
template <class T, class Alloc>
bool operator< (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
typename ft::list<T>::const_iterator it_r = rhs.begin();
typename ft::list<T>::const_iterator it_l = lhs.begin();
if (lhs == rhs)
return (false);
while (it_l != lhs.end() && it_r != rhs.end() && *it_l == *it_r)
{
it_l++;
it_r++;
}
if (*it_l < *it_r)
return (true);
return (false);
}
template <class T, class Alloc>
bool operator<= (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
if (lhs == rhs)
return (true);
return (lhs < rhs);
}
template <class T, class Alloc>
bool operator> (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
typename ft::list<T>::const_iterator it_r = rhs.begin();
typename ft::list<T>::const_iterator it_l = lhs.begin();
if (lhs == rhs)
return (false);
while (it_l != lhs.end() && it_r != rhs.end() && *it_l == *it_r)
{
it_l++;
it_r++;
}
if (*it_l > *it_r)
return (true);
return (false);
}
template <class T, class Alloc>
bool operator>= (const list<T,Alloc>& lhs, const list<T,Alloc>& rhs)
{
if (lhs == rhs)
return (true);
return (lhs > rhs);
}
template <class T, class Alloc>
void swap (list<T,Alloc>& x, list<T,Alloc>& y) {
x.swap(y);
}
template < class T >
std::ostream& operator <<(std::ostream& s, ft::list<T>& lst)
{
s << "{ ";
for (typename list<T>::const_iterator it = lst.begin(); it != lst.end(); it++)
s << *it << " ";
s << "}";
return s;
}
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/25 11:06:31 by jereligi #+# #+# */
/* Updated: 2021/03/08 15:25:42 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ITERATOR_HPP
#define ITERATOR_HPP
#include "../../utils.hpp"
namespace ft
{
template <typename T>
class Iterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
Iterator(void) {};
Iterator(T* src) { _ptr = src; };
Iterator(Iterator const &src) { *this = src; } ;
virtual ~Iterator() {};
Iterator &operator=(Iterator const &src) {
_ptr = src.operator->();
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != | > | >= | < | <= *****
*******************************************/
bool operator==(Iterator const& src) const {
return (_ptr == src._ptr);
};
bool operator!=(Iterator const& src) const {
return (_ptr != src._ptr);
};
bool operator>(Iterator const& src) const {
return (_ptr > src._ptr);
};
bool operator>=(Iterator const& src) const {
return (_ptr >= src._ptr);
};
bool operator<(Iterator const& src) const {
return (_ptr < src._ptr);
};
bool operator<=(Iterator const& src) const {
return (_ptr <= src._ptr);
};
/*******************************************
***** Operator Arithmetics *****
***** + | - | ++ | -- | += | -= *****
*******************************************/
Iterator operator+(difference_type src) {
return (Iterator(_ptr + src));
};
Iterator operator-(difference_type src) {
return (Iterator(_ptr - src));
};
difference_type operator+(Iterator src) {
return (_ptr + src._ptr);
};
difference_type operator-(Iterator src) {
return (_ptr - src._ptr);
};
Iterator operator++() {
_ptr++;
return (*this);
};
Iterator operator++(int) {
_ptr++;
return (Iterator(_ptr - 1));
};
Iterator operator--() {
_ptr--;
return (*this);
};
Iterator operator--(int) {
_ptr--;
return (Iterator(_ptr + 1));
};
void operator+=(difference_type src) {
_ptr += src;
};
void operator-=(difference_type src) {
_ptr -= src;
};
/*******************************************
***** Operator deferencing *****
***** * | [] | -> *****
*******************************************/
T& operator*() {
return (*_ptr);
};
const T* operator*() const {
return (*_ptr);
};
T& operator[](difference_type src) {
return (*(_ptr + src));
};
const T& operator[](difference_type src) const {
return (*(_ptr + src));
};
T* operator->() {
return (_ptr);
};
T* operator->() const {
return (_ptr);
};
private:
T* _ptr;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* queue.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 10:49:10 by jereligi #+# #+# */
/* Updated: 2021/03/17 14:36:17 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include "../list/list.hpp"
namespace ft
{
template <class T, class Container = list<T> >
class queue
{
public:
typedef typename list<T>::value_type value_type;
typedef typename list<T>::size_type size_type;
typedef Container container_type;
explicit queue (const container_type& ctrn = container_type()) : _container(ctrn) {};
queue(queue const &src) : _container(src._container) {};
queue &operator=(queue const &src) {
_container = src._container;
return (*this);
}
virtual ~queue() {};
bool empty() const {
return (_container.empty());
}
size_type size() const {
return (_container.size());
}
value_type& front() {
return (_container.front());
}
const value_type& front() const {
return (_container.front());
}
value_type& back() {
return (_container.back());
}
const value_type& back() const {
return (_container.back());
}
void push (const value_type& val) {
_container.push_back(val);
}
void pop() {
_container.pop_front();
}
template <class Tx, class Container_x>
friend bool operator== (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator!= (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator< (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator<= (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator> (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
template <class Tx, class Container_x>
friend bool operator>= (const queue<Tx,Container_x>& lhs, const queue<Tx,Container_x>& rhs);
private:
container_type _container;
};
template <class T, class Container>
bool operator== (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container == rhs._container);
}
template <class T, class Container>
bool operator!= (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container != rhs._container);
}
template <class T, class Container>
bool operator< (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container < rhs._container);
}
template <class T, class Container>
bool operator<= (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container <= rhs._container);
}
template <class T, class Container>
bool operator> (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container > rhs._container);
}
template <class T, class Container>
bool operator>= (const queue<T,Container>& lhs, const queue<T,Container>& rhs) {
return (lhs._container >= rhs._container);
}
}
#endif<file_sep>
#include <iostream>
#include <list>
#include "list.hpp"
int main(void)
{
std::list<int> l1(2, 42);
std::list<int> l2(1, 1);
l2.push_back(2);
l2.push_back(3);
l2.push_back(4);
l2.push_back(5);
l1.insert(l1.begin(), ++(l2.begin()), --(l2.end()));
std::list<int>::iterator it;
for (it = l1.begin(); it != l1.end(); it++)
std::cout << *it << std::endl;
it = ++(l1.begin());
++it;
l1.erase(it, --(l1.end()));
l1.push_back(89);
std::cout << std::endl;
for (it = l1.begin(); it != l1.end(); it++)
std::cout << *it << std::endl;
it = ++l2.begin();
++it;
++it;
l1.splice(++l1.begin(), l2, it);
std::cout << std::endl << "Splice : " << std::endl;
for (it = l1.begin(); it != l1.end(); it++)
std::cout << *it << std::endl;
l2.push_back(5);
l2.push_back(2);
l2.push_back(3);
l2.push_back(3);
std::cout << std::endl << "l2" << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.unique();
std::cout << std::endl << "l2 unique" << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.sort();
std::cout << std::endl << "l2 sort" << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l2.push_back(9);
l2.push_back(12);
std::list<int> l3(1, 1);
l3.push_back(8);
l3.push_back(11);
l3.push_back(10);
l3.push_back(50);
l2.sort();
std::cout << std::endl << "l2 sort" << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
l3.sort();
std::cout << std::endl << "l3 sort" << std::endl;
for (it = l3.begin(); it != l3.end(); it++)
std::cout << *it << std::endl;
l2.merge(l3);
std::cout << std::endl << "l2 merge" << std::endl;
for (it = l2.begin(); it != l2.end(); it++)
std::cout << *it << std::endl;
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* const_reverse_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/01 16:07:03 by jereligi #+# #+# */
/* Updated: 2021/04/03 15:15:22 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CONST_REVERSE_ITERATOR_HPP
#define CONST_REVERSE_ITERATOR_HPP
#include "iterator.hpp"
namespace ft
{
template <typename T, typename Node>
class const_reverse_iterator
{
public:
static const bool is_iterator = true;
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
const_reverse_iterator(void) {};
const_reverse_iterator(const Node* src) { _node = src; };
const_reverse_iterator(Iterator<T, Node> const &src) { _node = src.operator->(); };
const_reverse_iterator(const_reverse_iterator const &src) { *this = src; } ;
virtual ~const_reverse_iterator() {};
const_reverse_iterator &operator=(const_reverse_iterator const &src) {
_node = src._node;
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != *****
*******************************************/
bool operator==(const_reverse_iterator const& src) const {
return (_node == src._node);
};
bool operator!=(const_reverse_iterator const& src) const {
return (_node != src._node);
};
/*******************************************
***** Operator Arithmetics *****
***** ++ | -- *****
*******************************************/
const_reverse_iterator operator++() {
_node = _node->prev;
return (*this);
};
const_reverse_iterator operator++(int) {
const_reverse_iterator tmp = *this;
--(*this);
return (tmp);
};
const_reverse_iterator operator--() {
_node = _node->next;
return (*this);
};
const_reverse_iterator operator--(int) {
const_reverse_iterator tmp = *this;
++(*this);
return (tmp);
};
/*******************************************
***** Operator deferencing *****
***** * | -> *****
*******************************************/
const_reference operator*() const {
return (*_node);
};
const Node* operator->() const {
return (_node);
};
private:
const Node *_node;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tester_stack.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 16:12:08 by jereligi #+# #+# */
/* Updated: 2021/03/18 16:37:30 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <stack>
#include "stack.hpp"
#define COLOR_RESET "\033[0m"
#define COLOR_RED "\033[1;31m"
#define COLOR_BLUE "\033[1;34m"
#define COLOR_GREEN "\033[1;32m"
#define COLOR_WHITE "\033[1;37m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_CYAN "\033[1;36m"
#define clear_terminal "\x1B[2J\x1B[H"
#define ft_stack COLOR_BLUE << "----- ft::stack -----" << COLOR_RESET << std::endl
#define std_stack COLOR_BLUE << "----- std::stack -----" << COLOR_RESET << std::endl
void next_test()
{
std::string buf;
std::cout << COLOR_GREEN << "press enter for continu..." << COLOR_RESET;
std::getline (std::cin, buf);
std::cout << clear_terminal << std::endl;
}
static void test_non_member_ope_std()
{
std::cout << std_stack << std::endl;
std::stack<int> st_nums_one;
std::stack<int> st_nums_two;
st_nums_one.push(0);
st_nums_one.push(1);
st_nums_one.push(10);
st_nums_one.push(11);
st_nums_one.push(100);
st_nums_one.push(101);
st_nums_one.push(110);
st_nums_one.push(111);
std::cout << "st_nums_one.push(0);" << std::endl;
std::cout << "st_nums_one.push(1);" << std::endl;
std::cout << "st_nums_one.push(10);" << std::endl;
std::cout << "st_nums_one.push(11);" << std::endl;
std::cout << "st_nums_one.push(100);" << std::endl;
std::cout << "st_nums_one.push(101);" << std::endl;
std::cout << "st_nums_one.push(110);" << std::endl;
std::cout << "st_nums_one.push(111);" << std::endl << std::endl;
st_nums_two.push(0);
st_nums_two.push(1);
st_nums_two.push(10);
st_nums_two.push(11);
st_nums_two.push(100);
st_nums_two.push(101);
st_nums_two.push(110);
st_nums_two.push(111);
st_nums_two.push(1000);
std::cout << "st_nums_two.push(0);" << std::endl;
std::cout << "st_nums_two.push(1);" << std::endl;
std::cout << "st_nums_two.push(10);" << std::endl;
std::cout << "st_nums_two.push(11);" << std::endl;
std::cout << "st_nums_two.push(100);" << std::endl;
std::cout << "st_nums_two.push(101);" << std::endl;
std::cout << "st_nums_two.push(110);" << std::endl;
std::cout << "st_nums_two.push(111);" << std::endl;
std::cout << "st_nums_two.push(1000);" << std::endl << std::endl;
std::cout << "#- EQUAL & NON-EQUAL -#" << std::endl << std::endl;
std::cout << "st_nums_one == st_nums_one : " << std::boolalpha << (st_nums_one == st_nums_one) << std::endl;
std::cout << "st_nums_one == st_nums_two : " << std::boolalpha << (st_nums_one == st_nums_two) << std::endl << std::endl;
std::cout << "st_nums_one != st_nums_one : " << std::boolalpha << (st_nums_one != st_nums_one) << std::endl;
std::cout << "st_nums_one != st_nums_two : " << std::boolalpha << (st_nums_one != st_nums_two) << std::endl << std::endl;
std::cout << "#- SUPERIOR & EQUAL-SUPERIOR -#" << std::endl << std::endl;
std::cout << "st_nums_one < st_nums_one = " << (st_nums_one < st_nums_one) << std::endl;
std::cout << "st_nums_one < st_nums_two = " << (st_nums_one < st_nums_two) << std::endl;
std::cout << "st_nums_two < st_nums_one = " << (st_nums_two < st_nums_one) << std::endl;
std::cout << "st_nums_one <= st_nums_one = " << (st_nums_one <= st_nums_one) << std::endl;
std::cout << "st_nums_one <= st_nums_two = " << (st_nums_one <= st_nums_two) << std::endl;
std::cout << "st_nums_two <= st_nums_one = " << (st_nums_two <= st_nums_one) << std::endl << std::endl;
std::cout << "#- INFERIOR & EQUAL-INFERIOR -#" << std::endl << std::endl;
std::cout << "st_nums_one > st_nums_one = " << (st_nums_one > st_nums_one) << std::endl;
std::cout << "st_nums_one > st_nums_two = " << (st_nums_one > st_nums_two) << std::endl;
std::cout << "st_nums_two > st_nums_one = " << (st_nums_two > st_nums_one) << std::endl;
std::cout << "st_nums_one >= st_nums_one = " << (st_nums_one >= st_nums_one) << std::endl;
std::cout << "st_nums_one >= st_nums_two = " << (st_nums_one >= st_nums_two) << std::endl;
std::cout << "st_nums_two >= st_nums_one = " << (st_nums_two >= st_nums_one) << std::endl << std::endl;
next_test();
}
static void test_non_member_ope()
{
std::cout << ft_stack << std::endl;
ft::stack<int> st_nums_one;
ft::stack<int> st_nums_two;
st_nums_one.push(0);
st_nums_one.push(1);
st_nums_one.push(10);
st_nums_one.push(11);
st_nums_one.push(100);
st_nums_one.push(101);
st_nums_one.push(110);
st_nums_one.push(111);
std::cout << "st_nums_one.push(0);" << std::endl;
std::cout << "st_nums_one.push(1);" << std::endl;
std::cout << "st_nums_one.push(10);" << std::endl;
std::cout << "st_nums_one.push(11);" << std::endl;
std::cout << "st_nums_one.push(100);" << std::endl;
std::cout << "st_nums_one.push(101);" << std::endl;
std::cout << "st_nums_one.push(110);" << std::endl;
std::cout << "st_nums_one.push(111);" << std::endl << std::endl;
st_nums_two.push(0);
st_nums_two.push(1);
st_nums_two.push(10);
st_nums_two.push(11);
st_nums_two.push(100);
st_nums_two.push(101);
st_nums_two.push(110);
st_nums_two.push(111);
st_nums_two.push(1000);
std::cout << "st_nums_two.push(0);" << std::endl;
std::cout << "st_nums_two.push(1);" << std::endl;
std::cout << "st_nums_two.push(10);" << std::endl;
std::cout << "st_nums_two.push(11);" << std::endl;
std::cout << "st_nums_two.push(100);" << std::endl;
std::cout << "st_nums_two.push(101);" << std::endl;
std::cout << "st_nums_two.push(110);" << std::endl;
std::cout << "st_nums_two.push(111);" << std::endl;
std::cout << "st_nums_two.push(1000);" << std::endl << std::endl;
std::cout << "#- EQUAL & NON-EQUAL -#" << std::endl << std::endl;
std::cout << "st_nums_one == st_nums_one : " << std::boolalpha << (st_nums_one == st_nums_one) << std::endl;
std::cout << "st_nums_one == st_nums_two : " << std::boolalpha << (st_nums_one == st_nums_two) << std::endl << std::endl;
std::cout << "st_nums_one != st_nums_one : " << std::boolalpha << (st_nums_one != st_nums_one) << std::endl;
std::cout << "st_nums_one != st_nums_two : " << std::boolalpha << (st_nums_one != st_nums_two) << std::endl << std::endl;
std::cout << "#- SUPERIOR & EQUAL-SUPERIOR -#" << std::endl << std::endl;
std::cout << "st_nums_one < st_nums_one = " << (st_nums_one < st_nums_one) << std::endl;
std::cout << "st_nums_one < st_nums_two = " << (st_nums_one < st_nums_two) << std::endl;
std::cout << "st_nums_two < st_nums_one = " << (st_nums_two < st_nums_one) << std::endl;
std::cout << "st_nums_one <= st_nums_one = " << (st_nums_one <= st_nums_one) << std::endl;
std::cout << "st_nums_one <= st_nums_two = " << (st_nums_one <= st_nums_two) << std::endl;
std::cout << "st_nums_two <= st_nums_one = " << (st_nums_two <= st_nums_one) << std::endl << std::endl;
std::cout << "#- INFERIOR & EQUAL-INFERIOR -#" << std::endl << std::endl;
std::cout << "st_nums_one > st_nums_one = " << (st_nums_one > st_nums_one) << std::endl;
std::cout << "st_nums_one > st_nums_two = " << (st_nums_one > st_nums_two) << std::endl;
std::cout << "st_nums_two > st_nums_one = " << (st_nums_two > st_nums_one) << std::endl;
std::cout << "st_nums_one >= st_nums_one = " << (st_nums_one >= st_nums_one) << std::endl;
std::cout << "st_nums_one >= st_nums_two = " << (st_nums_one >= st_nums_two) << std::endl;
std::cout << "st_nums_two >= st_nums_one = " << (st_nums_two >= st_nums_one) << std::endl << std::endl;
test_non_member_ope_std();
}
static void test_push_std()
{
std::cout << std_stack << std::endl;
std::stack<int> st_nums;
std::cout << "ft::stack<int> st_nums;" << std::endl << std::endl;
// TEST EMPTY FUNCTION
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
// TEST PUSH ONE ITEM
st_nums.push(42);
std::cout << "st_nums.push(42);" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
// TEST PUSH MANY ITEMS
st_nums.push(56);
std::cout << "st_nums.push(56);" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
// TEST POP FUNCTION
st_nums.pop();
std::cout << "st_nums.pop();" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
st_nums.pop();
std::cout << "st_nums.pop();" << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
next_test();
}
void test_push()
{
std::cout << ft_stack << std::endl;
ft::stack<int> st_nums;
std::cout << "ft::stack<int> st_nums;" << std::endl << std::endl;
// TEST EMPTY FUNCTION
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
// TEST PUSH ONE ITEM
st_nums.push(42);
std::cout << "st_nums.push(42);" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
// TEST PUSH MANY ITEMS
st_nums.push(56);
std::cout << "st_nums.push(56);" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
// TEST POP FUNCTION
st_nums.pop();
std::cout << "st_nums.pop();" << std::endl << std::endl;
std::cout << "st_nums.top() = " << st_nums.top() << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
st_nums.pop();
std::cout << "st_nums.pop();" << std::endl << std::endl;
std::cout << "st_nums.size() = " << std::boolalpha << st_nums.size() << std::endl << std::endl;
std::cout << "st_nums.empty() = " << std::boolalpha << st_nums.empty() << std::endl << std::endl;
test_push_std();
}
int main(void)
{
test_push();
test_non_member_ope();
return 0;
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* iterator_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 16:12:17 by jereligi #+# #+# */
/* Updated: 2021/03/04 10:49:04 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../vector.hpp"
#include "constant.hpp"
void iterator_incrementers()
{
std::cout << ft_vector << std::endl;
// FT_VECTOR
ft::vector<int> vec;
ft::vector<int>::iterator it;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(42);
std::cout << COLOR_CYAN << "Test iterator incrementers" << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_BLUE << "Test ft::vector i++ | ++i | --i | i-- :" << COLOR_RESET << std::endl;
it = vec.begin();
std::cout << "it = vec.begin();" << std::endl;
std::cout << "*it = " << *it << std::endl;
std::cout << "*(it++) = " << *(it++) << std::endl;
std::cout << "*it = " << *it << std::endl;
std::cout << "*(it--) = " << *(it--) << std::endl;
std::cout << "*it = " << *it << std::endl;
std::cout << "*(++it) = " << *(++it) << std::endl;
std::cout << "*it = " << *it << std::endl;
std::cout << "*(--it) = " << *(--it) << std::endl;
std::cout << "*it = " << *it << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1;
std::vector<int>::iterator ite;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(5);
vec1.push_back(42);
std::cout << COLOR_BLUE << "Test std::vector i++ | ++i | --i | i-- :" << COLOR_RESET << std::endl;
ite = vec1.begin();
std::cout << "it = vec.begin();" << std::endl;
std::cout << "*it = " << *ite << std::endl;
std::cout << "*(it++) = " << *(ite++) << std::endl;
std::cout << "*it = " << *ite << std::endl;
std::cout << "*(it--) = " << *(ite--) << std::endl;
std::cout << "*it = " << *ite << std::endl;
std::cout << "*(++it) = " << *(++ite) << std::endl;
std::cout << "*it = " << *ite << std::endl;
std::cout << "*(--it) = " << *(--ite) << std::endl;
std::cout << "*it = " << *ite << std::endl << std::endl;
next_test();
}
void iterator_arithmetics()
{
std::cout << ft_vector << std::endl ;
std::cout << COLOR_CYAN << "Test Iterator Arithmetics" << std::endl;
// FT_VECTOR
ft::vector<int> vec;
ft::vector<int>::iterator it;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(42);
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_BLUE << "Test ft::vector i + | i - | i += | i -= :" << COLOR_RESET << std::endl;
it = vec.begin();
std::cout << "it = vec.begin();" << std::endl;
std::cout << "*(it + 0) = " << *(it + 0) << std::endl;
std::cout << "*(it + 1) = " << *(it + 1) << std::endl;
std::cout << "*(it + 5) = " << *(it + 5) << std::endl << std::endl;
it = vec.end() - 1;
std::cout << "it = v.end() - 1;" << std::endl;
std::cout << "*(it - 0) = " << *(it - 0) << std::endl;
std::cout << "*(it - 1) = " << *(it - 1) << std::endl;
std::cout << "*(it - 5) = " << *(it - 5) << std::endl << std::endl;
std::cout << "(*it += 2) = " << (*it += 2) << std::endl;
std::cout << "(*it -= 1) = " << (*it -= 1) << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1;
std::vector<int>::iterator ite;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(5);
vec1.push_back(42);
std::cout << COLOR_BLUE << "Test std::vector i + | i - | i += | i -= :" << COLOR_RESET << std::endl;
ite = vec1.begin();
std::cout << "it = vec.begin();" << std::endl;
std::cout << "*(it + 0) = " << *(ite + 0) << std::endl;
std::cout << "*(it + 1) = " << *(ite + 1) << std::endl;
std::cout << "*(it + 5) = " << *(ite + 5) << std::endl << std::endl;
ite = vec1.end() - 1;
std::cout << "it = v.end() - 1;" << std::endl;
std::cout << "*(it - 0) = " << *(ite - 0) << std::endl;
std::cout << "*(it - 1) = " << *(ite - 1) << std::endl;
std::cout << "*(it - 5) = " << *(ite - 5) << std::endl << std::endl;
std::cout << "(*it += 2) = " << (*ite += 2) << std::endl;
std::cout << "(*it -= 1) = " << (*ite -= 1) << std::endl << std::endl;
next_test();
}
void iterator_booleans()
{
std::cout << ft_vector << std::endl;
std::cout << COLOR_CYAN << "Test Iterator Booleans" << std::endl;
// FT_VECTOR
ft::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(42);
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_BLUE << "Test ft::vector < | > | <= | >= | == | != :" << COLOR_RESET << std::endl;
ft::vector<int>::iterator it_beg = vec.begin();
ft::vector<int>::iterator it_end = vec.end();
std::cout << "it_beg = vec.begin()" << std::endl;
std::cout << "it_end = vec.end()" << std::endl << std::endl;
std::cout << "it_beg < it_end is " << std::boolalpha << (it_beg < it_end) << std::endl;
std::cout << "it_end < it_beg is " << std::boolalpha << (it_end < it_beg) << std::endl;
std::cout << "it_beg > it_end is " << std::boolalpha << (it_beg > it_end) << std::endl;
std::cout << "it_end > it_beg is " << std::boolalpha << (it_end > it_beg) << std::endl << std::endl;
std::cout << "it_beg <= it_end is " << std::boolalpha << (it_beg <= it_end) << std::endl;
std::cout << "it_end <= it_beg is " << std::boolalpha << (it_end <= it_beg) << std::endl;
std::cout << "it_end <= it_end is " << std::boolalpha << (it_end <= it_end) << std::endl;
std::cout << "it_beg >= it_end is " << std::boolalpha << (it_beg >= it_end) << std::endl;
std::cout << "it_end >= it_beg is " << std::boolalpha << (it_end >= it_beg) << std::endl;
std::cout << "it_end >= it_end is " << std::boolalpha << (it_end >= it_end) << std::endl << std::endl;
std::cout << "it_beg == it_end is " << std::boolalpha << (it_beg == it_end) << std::endl;
std::cout << "it_beg == it_beg is " << std::boolalpha << (it_beg == it_beg) << std::endl;
std::cout << "it_beg != it_end is " << std::boolalpha << (it_beg != it_end) << std::endl;
std::cout << "it_beg != it_beg is " << std::boolalpha << (it_beg != it_beg) << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(5);
vec1.push_back(42);
std::cout << COLOR_BLUE << "Test std::vector < | > | <= | >= | == | != :" << COLOR_RESET << std::endl << std::endl;
std::vector<int>::iterator ite_beg = vec1.begin();
std::vector<int>::iterator ite_end = vec1.end();
std::cout << "it_beg < it_end is " << std::boolalpha << (ite_beg < ite_end) << std::endl;
std::cout << "it_end < it_beg is " << std::boolalpha << (ite_end < ite_beg) << std::endl;
std::cout << "it_beg > it_end is " << std::boolalpha << (ite_beg > ite_end) << std::endl;
std::cout << "it_end > it_beg is " << std::boolalpha << (ite_end > ite_beg) << std::endl << std::endl;
std::cout << "it_beg <= it_end is " << std::boolalpha << (ite_beg <= ite_end) << std::endl;
std::cout << "it_end <= it_beg is " << std::boolalpha << (ite_end <= ite_beg) << std::endl;
std::cout << "it_end <= it_end is " << std::boolalpha << (ite_end <= ite_end) << std::endl;
std::cout << "it_beg >= it_end is " << std::boolalpha << (ite_beg >= ite_end) << std::endl;
std::cout << "it_end >= it_beg is " << std::boolalpha << (ite_end >= ite_beg) << std::endl;
std::cout << "it_end >= it_end is " << std::boolalpha << (ite_end >= ite_end) << std::endl << std::endl;
std::cout << "it_beg == it_end is " << std::boolalpha << (ite_beg == ite_end) << std::endl;
std::cout << "it_beg == it_beg is " << std::boolalpha << (ite_beg == ite_beg) << std::endl;
std::cout << "it_beg != it_end is " << std::boolalpha << (ite_beg != ite_end) << std::endl;
std::cout << "it_beg != it_beg is " << std::boolalpha << (ite_beg != ite_beg) << std::endl << std::endl;
next_test();
}
void iterator_deference()
{
std::cout << ft_vector << std::endl;
std::cout << COLOR_CYAN << "Test Iterator deference" << std::endl;
// FT_VECTOR
ft::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(42);
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_BLUE << "Test ft::vector * | [] | -> :" << COLOR_RESET << std::endl;
ft::vector<int>::iterator it = vec.begin();
ft::vector<int>::iterator ite = vec.end() - 1;
std::cout << "it = vec.begin()" << std::endl;
std::cout << "*it = " << *it << std::endl;
*it = 43;
std::cout << "*it = " << *it << std::endl << std::endl;
std::cout << "it[0] = " << it[0] << std::endl;
it[0] = 9;
std::cout << "it[0] = " << it[0] << std::endl;
std::cout << "*(it = ite) = " << *(it = ite) << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(5);
vec1.push_back(42);
std::cout << COLOR_BLUE << "Test std::vector * | [] | -> :" << COLOR_RESET << std::endl;
std::vector<int>::iterator itb = vec1.begin();
std::vector<int>::iterator iten = vec1.end() - 1;
std::cout << "it = vec.begin()" << std::endl;
std::cout << "*it = " << *itb << std::endl;
*itb = 43;
std::cout << "*it = " << *itb << std::endl << std::endl;
std::cout << "it[0] = " << itb[0] << std::endl;
itb[0] = 9;
std::cout << "it[0] = " << itb[0] << std::endl;
std::cout << "*(it = ite) = " << *(itb = iten) << std::endl << std::endl;
next_test();
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tester_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 16:12:32 by jereligi #+# #+# */
/* Updated: 2021/03/08 15:23:13 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "iterator_vector.cpp"
#include "reverse_iterator.cpp"
#include "capacity_vector.cpp"
#include "element_acces_vector.cpp"
#include "modifiers_vector.cpp"
void next_test()
{
std::string buf;
std::cout << COLOR_GREEN << "press enter for continu..." << COLOR_RESET;
std::getline (std::cin, buf);
std::cout << clear_terminal << std::endl;
}
int main(void)
{
capacity_vector();
element_acces();
ft_modifiers_vector();
std_modifiers_vector();
iterator_incrementers();
iterator_arithmetics();
iterator_booleans();
iterator_deference();
reverse_iterator_incrementers();
reverse_iterator_arithmetics();
reverse_iterator_booleans();
reverse_iterator_deference();
return (0);
}<file_sep>#include "queue.hpp"
#include "../list/list.hpp"
int main(void)
{
ft::list<int> l(2,42);
ft::queue<int> q(l);
ft::queue<int> q2(l);
l.push_back(41);
q2.push(41);
std::cout << "queue size : " << q.size() << std::endl;
q.push(43);
std::cout << " == : " << std::boolalpha << (q == q2) << std::endl;
std::cout << " != : " << std::boolalpha << (q != q2) << std::endl;
std::cout << " < : " << std::boolalpha << (q < q2) << std::endl;
std::cout << " <= : " << std::boolalpha << (q2 <= q2) << std::endl;
std::cout << " > : " << std::boolalpha << (q > q2) << std::endl;
std::cout << " >= : " << std::boolalpha << (q >= q2) << std::endl;
while (!q.empty())
{
std::cout << ' ' << q.front();
q.pop();
}
return (0);
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* reverse_iterator.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/25 11:06:31 by jereligi #+# #+# */
/* Updated: 2021/03/08 15:24:33 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef REVERSE_ITERATOR_HPP
#define REVERSE_ITERATOR_HPP
#include "iterator.hpp"
namespace ft
{
template <typename T>
class reverse_iterator
{
public:
static const bool is_iterator = true;
typedef typename std::ptrdiff_t difference_type;
/*******************************************
***** Member Functions (Coplien Form) *****
*******************************************/
reverse_iterator(void) {};
reverse_iterator(T* src) { _ptr = src; };
reverse_iterator(reverse_iterator const &src) { *this = src; } ;
reverse_iterator(Iterator<T> const &src) { _ptr = src.operator->(); };
virtual ~reverse_iterator() {};
reverse_iterator &operator=(reverse_iterator const &src) {
_ptr = src.operator->();
return (*this);
};
/*******************************************
***** Operator Boolean *****
***** == | != | > | >= | < | <= *****
*******************************************/
bool operator==(reverse_iterator const& src) const {
return (_ptr == src._ptr);
};
bool operator!=(reverse_iterator const& src) const {
return (_ptr != src._ptr);
};
bool operator>(reverse_iterator const& src) const {
return (_ptr < src._ptr);
};
bool operator>=(reverse_iterator const& src) const {
return (_ptr <= src._ptr);
};
bool operator<(reverse_iterator const& src) const {
return (_ptr > src._ptr);
};
bool operator<=(reverse_iterator const& src) const {
return (_ptr >= src._ptr);
};
/*******************************************
***** Operator Arithmetics *****
***** + | - | ++ | -- | += | -= *****
*******************************************/
reverse_iterator operator+(difference_type src) {
return (reverse_iterator(_ptr - src));
};
reverse_iterator operator-(difference_type src) {
return (reverse_iterator(_ptr + src));
};
difference_type operator+(reverse_iterator src) {
return (_ptr - src._ptr);
};
difference_type operator-(reverse_iterator src) {
return (_ptr + src._ptr);
};
reverse_iterator operator++() {
_ptr--;
return (*this);
};
reverse_iterator operator++(int) {
_ptr--;
return (reverse_iterator(_ptr + 1));
};
reverse_iterator operator--() {
_ptr++;
return (*this);
};
reverse_iterator operator--(int) {
_ptr++;
return (reverse_iterator(_ptr - 1));
};
void operator+=(difference_type src) {
_ptr -= src;
};
void operator-=(difference_type src) {
_ptr += src;
};
/*******************************************
***** Operator deferencing *****
***** * | [] | -> *****
*******************************************/
T& operator*() {
return (*_ptr);
};
const T* operator*() const {
return (*_ptr);
};
T& operator[](difference_type src) {
return (*(_ptr + src));
};
const T& operator[](difference_type src) const {
return (*(_ptr + src));
};
T* operator->() {
return (_ptr);
};
T* operator->() const {
return (_ptr);
};
private:
T* _ptr;
};
}
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* modifiers_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/04 11:36:28 by jereligi #+# #+# */
/* Updated: 2021/04/03 14:03:22 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../vector.hpp"
#include "constant.hpp"
void ft_modifiers_vector()
{
std::cout << ft_vector << std::endl;
// tester [] | at | front | back
// FT_VECTOR
std::cout << COLOR_CYAN << "Test Modifiers vector" << COLOR_RESET << std::endl<< std::endl;
ft::vector<int> vec(4,42);
std::cout << COLOR_CYAN << "Test ft::vector assign | push_back | pop_back | insert \
| erase | swap | clear" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec.assign(2, 120);
std::cout << "vec.assign(2, 120)" << std::endl;
vec.push_back(7);
vec.push_back(8);
std::cout << "vec.push_back(7)" << std::endl;
std::cout << "vec.push_back(8)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec.pop_back();
std::cout << "vec.pop_back()" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec.pop_back();
std::cout << "vec.pop_back()" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
ft::vector<int>::iterator it = vec.begin();
vec.insert(it, 1);
vec.insert(it + 2, 9);
std::cout << "it = vec.begin()" << std::endl;
std::cout << "vec.insert(it, 1)" << std::endl;
std::cout << "vec..insert(it + 2, 9)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec.insert(it + 1, 4, 0);
std::cout << "vec.insert(it + 1, 4, 0)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
// it = vec.begin();
// vec.insert(it, it + 2, it + 4);
// std::cout << "vec.insert(it, it + 4, it + 6);" << std::endl;
// std::cout << COLOR_YELLOW << "vector {";
// for (size_t i = 0; i < vec.size(); i++)
// {
// std::cout << vec[i];
// if (i + 1 != vec.size())
// std::cout << ", ";
// else
// std::cout << "}" << COLOR_RESET << std::endl << std::endl;
// }
it = vec.begin();
vec.erase(it + 2);
std::cout << "vec.erase(2)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
it = vec.begin();
vec.erase(it + 1, it + 7);
std::cout << "vec.erase(it + 1, it + 7)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
ft::vector<int> foo(3,100); // three ints with a value of 100
ft::vector<int> bar(5,50); // five ints with a value of 200
std::cout << "ft::vector<int> foo(3,100);" << std::endl \
<< "ft::vector<int> bar(5,50);" << std::endl << std::endl;
std::cout << "foo.swap(bar)" << std::endl;
foo.swap(bar);
std::cout << "foo contains:";
for (unsigned i=0; i<foo.size(); i++)
std::cout << ' ' << foo[i];
std::cout << std::endl;
std::cout << "bar contains:";
for (unsigned i=0; i<bar.size(); i++)
std::cout << ' ' << bar[i];
std::cout << std::endl << std::endl;
vec.clear();
std::cout << "vec.clear | vec.empty is " << std::boolalpha << vec.empty() << std::endl << std::endl;
}
void std_modifiers_vector()
{
// tester [] | at | front | back
// std_VECTOR
std::vector<int> vec1(4,42);
std::cout << COLOR_CYAN << "Test std::vector assign | push_back | pop_back | insert \
| erase | swap | clear" << COLOR_RESET << std::endl << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec1.assign(2, 120);
std::cout << "vec.assign(2, 120)" << std::endl;
vec1.push_back(7);
vec1.push_back(8);
std::cout << "vec.push_back(7)" << std::endl;
std::cout << "vec.push_back(8)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec1.pop_back();
std::cout << "vec.pop_back()" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec1.pop_back();
std::cout << "vec.pop_back()" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::vector<int>::iterator it = vec1.begin();
vec1.insert(it, 1);
vec1.insert(it + 2, 9);
std::cout << "it = vec.begin()" << std::endl;
std::cout << "vec.insert(it, 1)" << std::endl;
std::cout << "vec..insert(it + 2, 9)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
vec1.insert(it + 1, 4, 0);
std::cout << "vec.insert(it + 1, 4, 0)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
// it = vec1.begin();
// vec1.insert(it, it + 2, it + 4);
// std::cout << "vec.insert(it, it + 4, it + 6);" << std::endl;
// std::cout << COLOR_YELLOW << "vector {";
// for (size_t i = 0; i < vec1.size(); i++)
// {
// std::cout << vec1[i];
// if (i + 1 != vec1.size())
// std::cout << ", ";
// else
// std::cout << "}" << COLOR_RESET << std::endl << std::endl;
// }
it = vec1.begin();
vec1.erase(it + 2);
std::cout << "vec.erase(2)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
it = vec1.begin();
vec1.erase(it + 1, it + 7);
std::cout << "vec.erase(it + 1, it + 7)" << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i];
if (i + 1 != vec1.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::vector<int> foo(3,100); // three ints with a value of 100
std::vector<int> bar(5,50); // five ints with a value of 200
std::cout << "ft::vector<int> foo(3,100);" << std::endl \
<< "ft::vector<int> bar(5,50);" << std::endl << std::endl;
std::cout << "foo.swap(bar)" << std::endl;
foo.swap(bar);
std::cout << "foo contains:";
for (unsigned i=0; i<foo.size(); i++)
std::cout << ' ' << foo[i];
std::cout << std::endl;
std::cout << "bar contains:";
for (unsigned i=0; i<bar.size(); i++)
std::cout << ' ' << bar[i];
std::cout << std::endl << std::endl;
vec1.clear();
std::cout << "vec.clear | vec.empty is " << std::boolalpha << vec1.empty() << std::endl << std::endl;
next_test();
}<file_sep>#include <map>
#include "map.hpp"
#include <vector>
#include <iostream>
#include "utils.hpp"
// (*it).first
// it.operator->()->first
// map->operator[]('i');
int main ()
{
ft::map<char, int> *map = new ft::map<char, int>();
// ft::map<char, int>::iterator it;
// ft::map<char, int>::iterator ite;
// map->operator[]('i');
map->insert(ft::pair<char, int>('c', 1));
map->insert(ft::pair<char, int>('f', 1));
map->insert(ft::pair<char, int>('b', 2));
std::cout << "max_size : " << map->max_size() << std::endl;
std::map<char, int> *map2 = new std::map<char, int>();
map2->insert(std::pair<char, int>('c', 1));
map2->insert(std::pair<char, int>('f', 1));
map2->insert(std::pair<char, int>('b', 2));
std::cout << "max_size : " << map2->max_size() << std::endl;
// map->insert(ft::pair<char, int>('a', 2));
// map->insert(ft::pair<char, int>('d', 3));
// map->insert(ft::pair<char, int>('e', 2));
// map->insert(ft::pair<char, int>('g', 2));
// for (it = map->begin(); it != map->end(); it++)
// std::cout << "first :" << (*it).first << std::endl;
// it = map->find('c');
// std::cout << "it : " << (*it).first << std::endl;
// map->erase(it);
// // std::cout << std::endl;
// for (it = map->begin(); it != map->end(); it++)
// std::cout << "second :" << (*it).first << std::endl;
// std::cout << std::endl << std::endl;
// ft::map<int, int> int_int_map;
// int_int_map[66] = 66;
// int_int_map[47] = 47;
// int_int_map[74] = 74;
// int_int_map[54] = 54;
// int_int_map[71] = 71;
// int_int_map[53] = 53;
// int_int_map[59] = 59;
// int_int_map[69] = 69;
// int_int_map[72] = 72;
// std::cout << "int_int_map : " << std::endl << int_int_map << std::endl;
// ft::map<int, int>::iterator itx = int_int_map.begin();
// std::cout << "ft::map<int, int>::iterator itx = int_int_map.begin();" << std::endl;
// itx = int_int_map.find(66);
// // itx++;
// // itx++;
// // itx++;
// // itx++;
// std::cout << "itx++" << std::endl;
// std::cout << "itx++" << std::endl;
// std::cout << "itx++" << std::endl;
// std::cout << "itx++" << std::endl << std::endl;
// std::cout << "*itx : " << *itx << std::endl << std::endl;
// int_int_map.erase(itx);
// std::cout << "int_int_map.erase(it);" << std::endl << std::endl;
// ft::map<char, int>::reverse_iterator rit;
// rit = map->rbegin();
// std::cout << (*rit).first << std::endl;
// rit--;
// std::cout << (*rit).first << std::endl;
// map->clear();
// it = map->begin();
// std::cout << (*it).first << std::endl;
return 0;
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* element_acces_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/04 10:47:43 by jereligi #+# #+# */
/* Updated: 2021/03/04 11:36:53 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../vector.hpp"
#include "constant.hpp"
void element_acces()
{
std::cout << ft_vector << std::endl;
// tester [] | at | front | back
// FT_VECTOR
ft::vector<int> vec(4,42);
std::cout << COLOR_CYAN << "Test Element access vector" << COLOR_RESET << std::endl;
std::cout << COLOR_YELLOW << "vector {";
for (size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i];
if (i + 1 != vec.size())
std::cout << ", ";
else
std::cout << "}" << COLOR_RESET << std::endl << std::endl;
}
std::cout << COLOR_CYAN << "Test ft::vector [] | at | front | back" << COLOR_RESET << std::endl << std::endl;
std::cout << "vec[0] = " << vec[0] << std::endl;
vec.push_back(43);
std::cout << "vec.push_back(43)" << std::endl;
std::cout << "vec[4] = " << vec[4] << std::endl;
std::cout << "vec.at(4) = " << vec.at(4) << std::endl;
std::cout << "vec.at(0) = " << vec.at(0) << std::endl;
vec[0] = 50;
std::cout << "vec[0] = 50 | vec.front() = " << vec.front() << std::endl;
std::cout << "vec.back() = " << vec.back() << std::endl;
vec.push_back(9);
std::cout << "vec.push_back(9) | vec.back() = " << vec.back() << std::endl << std::endl;
// STD_VECTOR
std::vector<int> vec1(4, 42);
std::cout << COLOR_CYAN << "Test std::vector [] | at | front | back" << COLOR_RESET << std::endl << std::endl;
std::cout << "vec[0] = " << vec1[0] << std::endl;
vec1.push_back(43);
std::cout << "vec.push_back(43)" << std::endl;
std::cout << "vec[4] = " << vec1[4] << std::endl;
std::cout << "vec.at(4) = " << vec1.at(4) << std::endl;
std::cout << "vec.at(0) = " << vec1.at(0) << std::endl;
vec1[0] = 50;
std::cout << "vec[0] = 50 | vec.front() = " << vec1.front() << std::endl;
std::cout << "vec.back() = " << vec1.back() << std::endl;
vec1.push_back(9);
std::cout << "vec.push_back(9) | vec.back() = " << vec1.back() << std::endl << std::endl;
next_test();
}
|
be97084bed5208c25dcda55e0e768c2722985d72
|
[
"Markdown",
"C++"
] | 37
|
C++
|
Jean-xavierr/42Ft_containers
|
f156709dc39aa9bf332131a7c226c85cbecd5f10
|
59650fa6fc04c918a42c51fc735ff10d3a44c286
|
refs/heads/main
|
<repo_name>enderfree/alg<file_sep>/if_while/if_while10.c
#include<stdio.h>
int main()
{
int var;
int numberOfOdd = 0;
int numberOfEven = 0;
int sumOfOdd = 0;
int sumOfEven = 0;
char yesOrNo;
do{
printf("Do you want to enter an integer? (Y 0r N)\n");
scanf("%c", &yesOrNo);
if(yesOrNo != 'N')
{
printf("\n\nPlease enter it here: ");
scanf("%d", &var);
if(var % 2 = 1)
{
++numberOfOdd;
sumOfOdd += var;
}
else
{
++numberOfEven;
sumOfEven += var;
}
}
}while(yesOrNo != 'N')
print("\n\nNumber of odd integers = " + numberOfOdd +
"\nNumber of even integers = " + numberOfEven +
"\nSumm of those odd numbers = " + sumOfOdd +
"\nSumm of those even numbers = " + sumOfEven);
}<file_sep>/pointZero/pointZero display fix.c
#include<stdio.h>
#include<math.h>
// int main()
// {
// const int stop = 6; //how many row in my tables and how long is a row
// int n = 1;
// for(int n = 1; n < stop; + n) //each iteration of this for will create a new row
// {
// for(int i = 1; i < stop; ++i) //first table
// {
// printf("%d", n++);
// }
// printf(" "); //to separates the two tables
// for(int point = n; point > 1; --point) //place the points
// {
// printf(".");
// }
// for(int zero = 0; zero < stop - n; ++zero) //place the zeros
// {
// printf("0");
// }
// printf("\n"); //change row before going back to the initial for
// n -= stop - 2; //we start from a different value (-2 because I used strict conditions)
// }
// return 0;
// }
int main()
{
const int startingNumber = 1;
const int stop = 6; //-1 = how many row in my tables and how long is a row
for(int n = startingNumber; n < stop; ++n) //each iteration of this for will create a new row
{
for(int i = 1; i < stop; ++i) //first table //last number of a row == firstNumberOfThisRow + stop - 2
{ //first number of the last row == firstNumberOfTheFirstRow + stop - 2
int numberToPrint = n + i - 1;
int lenghtiestNumber = 4; //it need to be preinitialized //any single digit number could have done the trick
if((int)log10(startingNumber) + 1 > (int)log10(startingNumber + stop - 2 + stop - 2) + 1) //I should really do a method for this simple calculus
{
lenghtiestNumber = startingNumber;
}
else
{
lenghtiestNumber = startingNumber + stop - 2 + stop - 2;
}
int numberToPrintLenght = (int)log10(numberToPrint) + 1;
do
{
if(i != 1)
printf("-");
++numberToPrintLenght;
} while (numberToPrintLenght < (int)log10(lenghtiestNumber) + 1);
printf("%d", numberToPrint); //the last number printed will be (stop-1)*2-1
}
printf(" "); //to separates the two tables
for(int point = n; point > 1; --point) //place the points
{
printf(".");
}
for(int zero = 0; zero < stop - n; ++zero) //place the zeros
{
printf("0");
}
printf("\n"); //change row before going back to the initial for
}
return 0;
}<file_sep>/final.c
#include <stdio.h>
int main()
{
int n;
printf("How far should we print? (int): ");
scanf("%d", &n);
printf("\n");
int pattern[n][n];
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < i + 1; ++j)
{
pattern[i][j] = i + 1;
printf("%d", pattern[i][j]);
}
printf("\n");
}
}<file_sep>/if_while/if_while3.c
void main()
{
int i = 1499;
while(i<2700 && (++i % 5) && i%7)
{
printf(i);
}
}<file_sep>/if_while/if_while7.c
#include<stdio.h>
int main() //the pow function already serve that purpose
{
int base;
int exponant;
printf("Please, give us a base: ");
scanf("%d", base);
printf("\nPlease, give us the exponant: ");
scanf("%d", exponant);
int i = 1;
while (i < exponant)
{
base *= base;
++i;
}
printf(base);
}<file_sep>/array-exercises.c
/******************************************************************************************************************
420AP1AS, F2020
mmk @ lasallecollege
Arrays - notes and exercises
v 1.0
An array is a data-structure that holds multiple variables of the same type.
This following is an array that holds some integers values
_____________________________________________________________________________________
10 | 54 | 80 | 90 | 30 | 25 | 5 | 3 | 50 | 51 |
________|_______|_______|_______|_______|______|_________|_________|________|________|
The array has the following attributes:
name: like any variable, you need to give the array a name
size: how many elements do you want to store in the array?
data-type: the type of elements you will be storing in the array (char, float, int, string...)
And like any variable, you need to declare the array, so that space in memory is reserved for it.
Use the attributes above to declare the array like so:
the D E C L A R A T I O N ------>>> data-type array-name [ size ] <<<-------
int numbers [10]
This declaration reads: numbers is an array of integers and of size 10 (ie. it can hold 10 elements).
But after the declaration, the array is empty*.
________________________________________________________________________________________
| | | | | | | | | |
________|_______|_______|_______|_______|______|_________|________|________|________|___
In the case of a variable, we do one of the following:
int a; // this is a declaration that will later be followed by an assignment
int a = 1; // this is a simultaneous declaration and initialization
We can do the same for the arrays!
int numbers[10]; // this is a simple declaration
int numbers[10] = {10, 54, 80, 90, 30, 25, 5, 3, 50, 51} // and this is a simultaneous declaration and initialization.
int numbers[] = {10, 54, 80, 90, 30, 25, 5, 3, 50, 51} // this is also valid. You don't really need to keep the size between []
// It is determined by the number of elements between { }
-------------------->>> Once you declare the size of the array, you CANNOT change it! <<<--------------------------------------
the I N D E X
The 10 elements of the array are akin to 10 variables.
In order to access them, you need to know their position in the array.
This is known as the "index". If the array size = n, then:
The first element is stored at index 0, and
The last element is stored at index n-1.
________________________________________________________________________________________
| | | | | | | | | |
________|_______|_______|_______|_______|______|_________|________|________|________|___
0 1 2 3 4 5 6 7 8 9 <<<----- the indexes
Consider every slot in the array as a variable. Here, there are 10.
Typically, we access and manipulate variables with the names we give them.
You may ask: but what are the names of these variables?? The ones in the array... Well, simply:
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
numbers[5]
numbers[6]
numbers[7]
numbers[8]
numbers[9]
You use the array name and follow it by the position you're interested in between square brackets.
Imagine you're headed home. You live at:
123 sunshine street <==> array name, numbers. But that's not enough. Now, you need the apt.
Apt 13 <==> index. This now tells you which position you are accessing in the array
Anything related to access and assignment that you can do with a single variable, you can do here:
num = 1;
numbers[0] = 1;
num = num + 1;
numbers[1] = numbers[1] +1;
printf("%d", num);
printf("%d", numbers[2]);
scanf("%d", &num);
scanf("%d", &numbers[3]);
and so on ...
ITERATING OVER THE ARRAY
Remember the for loops and all those patterns..?
for (int index=0; index < size; index++){
// do whatever you want with array_name[index]
// give it a try!
// this iterates over index/location 0 all the way to index/location n-1
// your index serves as an iterator...
}
Remember with loops, we use the iterator as a counter.
For example, print "hello world" 5 times. The iterator can run from 0 to 4, 1 to 5, 100, to 104, ... it doesn't matter.
All that matters is that the loop runs 5 times.
But in loops, we have also used the iterator for its value...
Recall the example where we iterated from 1500-2700 and printed nums divisble by 5 and 7.
In that case, we used the iterator's value : i = 1500, 1505, 1510, 1515, ... 2700.
We can do the same with arrays!
Sometimes the value of the INDEX (0 to n-1) won't matter. See spreadsheet with grades example.
In the example of the array numbers above, we have no use for the value of the index.
On the other hand, say I want to store the height of a 4 years old toddler at every one of his/her birthdays.
Instead of storing this info in 5 variables, you store it in an array: float height[5];
And you use the index of the array, to represent the year... See spreadsheet with height example.
Birth: 51.5cm -->> height[0] = 51.5
1st bday: 74cm -->> height[1] = 74
2nd bday: 86cm -->> height[2] = 86
3rd bday: 95cm -->> height[3] = 95
4th bday: 100cm -->> height[4] = 100
________________________________________________________
51.5 | 74 | 86 | 95 | 100 |
____________|_________|_________|_________|__________|__
0 1 2 3 4
for (int i=0; i<5; i++){ // looping to take info in and fill the array
printf("How tall was the child at year %d?", i);
scanf("%f", &height[i]);
}
printf("Thank you! Please verify the following information:\n ");
for (int i=0; i<5; i++){ // looping to print out the values in the array. same construct as above... just different body!
printf("At year %d, the child was %fcm tall!\n", i, height[i]);
} // i is the index and height[i] is the value stored in the array height at that index.
*********************************************************************************************************/
/*
Exercise 1.
A program prompts the user to enter students' grades, which it subsequently stores in an array.
The program needs to ask the user how many students are there in class in order to create the array.
Once this is done, the program will compute and printout the following:
class average,
max grade, and
min grade
*/
int main()
{
int classSize = 0; //in case of a failiure to catch the answer
printf("How many student is there in this class? ");
scanf("%d", &classSize);
printf("\n");
int grades[classSize];
int gradeAvarage = 0;
int maxGrade = 0;
int minGrade = 100;
for(int i = 0; i < classSize; ++i)
{
printf("\nStudent %d grade: ", i);
scanf("%d", &grades[i]);
gradeAvarage += grades[i];
if(grades[i] > maxGrade)
{
maxGrade = grades[i];
}
if(grades[i] < minGrade)
{
minGrade = grades[i];
}
}
gradeAvarage /= classSize;
printf("\n\nClass avarage: %d\nMax grade: %d\nMin grade: %d", gradeAvarage, maxGrade, minGrade);
return 0;
}
/*
Exercise 2.
Write a program that reads characters in an array A and copies them into an array B, such that
the characters in array B are in reverse order.
Display the content of both arrays.
*/
int main()
{
char A[4] = {'C', 'H', 'A', 'R'};
char B[4]; //A && B would have the same variable for their size
for(int i = 3; i >= 0; --i) //3 is my last index (well thechnically I think that index 4 exist but contain an end value)
{
B[3-i] = A[i];
}
printf("A B\n\n");
for (int i = 0; i < 4; ++i)
{
printf("%c %c\n", A[i], B[i]);
}
return 0;
}
/*
Exercise 3.
Declare and initialize an array num[10] of type int, such that the value at index i is i+1.
Then, write code to replace the values in the array with their square.
*/
int main()
{
int num[10];
for(int i = 0; i < 10; ++i)
{
num[i] = i + 1;
}
for(int i = 0; i < 10; ++i)
{
num[i] *= num[i];
}
return 0;
}
/*
Exercise 4.
Write a program that merges two sorted arrays into one, discarding duplicates.
You will need to create a third array that can hold the elements of both arrays.
*/
int main()
{
int sortedArray1[5] = {0, 1, 2, 3, 4};
int sortedArray2[5] = {5, 6, 7, 8, 9};
int combinedSize = sizeof(sortedArray1)/sizeof(int) + sizeof(sortedArray2)/sizeof(int)
int combinedArrays[combinedSize];
int combinedArraysIndex = 0;
for(int i = 0; i < sizeof(sortedArray1)/sizeof(int); ++i)
{
bool alreadyThere = 0;
for(int j = 0; j < combinedArraysIndex; ++j)
{
if(combinedArrays[j] == sortedArray1[i]) //lets just hope that this will compare values, not references
{
alreadyThere = 1;
break;
}
}
if(!alreadyThere)
{
combinedArrays[combinedArrayIndex] = sortedArray1[i];
}
++combinedArrayIndex;
}
for(int i = 0; i < sizeof(sortedArray2)/sizeof(int); ++i)
{
bool alreadyThere = 0;
for(int j = 0; j < combinedArraysIndex; ++j)
{
if(combinedArrays[j] == sortedArray2[i]) //we wont learn methods before object programming right? //bool LooksForIfNumberIsAlreadyInArray(int number, int Array[])
{
alreadyThere = 1;
break;
}
}
if(!alreadyThere)
{
combinedArrays[combinedArrayIndex] = sortedArray2[i];
}
++combinedArrayIndex;
}
return 0;
}
/*
Exercise 5.
Given an array of integers, in which elements are duplicated a number of times, create a parallel array
frequency, that uses the index value to store the frequency of occurrence of a number in the previous array.
E.g. in the following array there are 2 x 5s, 3 x 8s, 2 x 4s, 1 x 9 and 1 x 7.
________________________________________________________________________________________
5 | 5 | 4 | 7 | 8 | 8 | 8 | 4 | 9 |
_________|________|________|________|________|_______|__________|_________|_________|_
0 1 2 3 4 5 6 7 8
The expected output should be an array named frequency. You must determine its size.
This is what it should look like.
________________________________________________________________________________________
| 2 | 2 | 1 | | | | | |
_________|________|________|________|________|_______|__________|_________|_________|_
0 1 2 3 4 5 6 7 8 9
*/
int main()
{
int array[9] = {5, 5, 4, 7, 8, 8, 8, 4, 9};
int frequancy[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //the size of this array must not be == to the size of the one it will scan but it's highest value + 1
printf("The array: [");
for(int i = 0; i < 9; ++i)
{
printf("%d", array[i]);
if(i != 8) //8 will be the last value of i that will paas by this line
{
printf(", ");
}
else
{
printf("]\n");
}
++frequancy[array[i]];
}
printf("contains: \n");
for(int i = 0; i < 10; ++i)
{
printf("%d %d\n", frequancy[i], i);
}
return 0;
}
/*
Exercises 32-36, 38, 42, 54, 58 @ https://www.w3resource.com/c-programming-exercises/array/index.php
*/<file_sep>/pointZero/pointZero.c
#include<stdio.h>
// int main()
// {
// const int stop = 6; //how many row in my tables and how long is a row
// int startingNumber = 1;
// for(int n = 1; n < stop; ++n) //each iteration of this for will create a new row
// {
// for(int i = 1; i < stop; ++i) //first table
// {
// printf("%d", startingNumber++);
// }
// printf(" "); //to separates the two tables
// for(int point = n; point > 1; --point) //place the points
// {
// printf(".");
// }
// for(int zero = 0; zero < stop - n; ++zero) //place the zeros
// {
// printf("0");
// }
// printf("\n"); //change row before going back to the initial for
// startingNumber -= stop - 2; //we start from a different value (-2 because I used strict conditions)
// }
// return 0;
// }
int main()
{
const int stop = 6; //-1 = how many row in my tables and how long is a row
for(int n = 1; n < stop; ++n) //each iteration of this for will create a new row
{
for(int i = 1; i < stop; ++i) //first table
{
printf("%d", n + i - 1);
}
printf(" "); //to separates the two tables
for(int point = n; point > 1; --point) //place the points
{
printf(".");
}
for(int zero = 0; zero < stop - n; ++zero) //place the zeros
{
printf("0");
}
printf("\n"); //change row before going back to the initial for
}
return 0;
}<file_sep>/if_while/if_while8.c
#include<stdio.h>
#include <stdlib.h>
int main()
{
int hiddenNumber = rand() % 8 + 1; //rand() generate a random number between 0 and 1 so % the number that we want will give a nmber between 0 and itself
int guess = 0;
int numberOfTries = 0;
printf("Guess which number I am thinking of~ (between 1 and 9) \n");
while (guess != hiddenNumber)
{
++numberOfTries;
if(numberOfTries != 1;)
{
printf("\nNo, that's not it~\n");
}
scanf("%d", &guess);
}
printf("\nAww, you got it, it took you " + numberOfTries + "tries~");
}<file_sep>/if_while/if_while4.c
#include<stdio.h>
int maint()
{
const int startingMultiplicator = 1;
const int endingMultiplicator = 12;
int chosenValue; //the value for what we will print the multiplication table
printf("Which interger do you whant to multiply? ");
scanf("%d", chosenValue);
printf("\n
\n
Multiplication table of " + chosenValue + " from " + startingMultiplicator + " to " + endingMultiplicator);
int i = startingMultiplicator;
while (i <= endingMultiplicator)
{
printf("\n" +
i + " X " + chosenValue + " = " + i*chosenValue);
++i;
}
}<file_sep>/Parallel_and_2D_Arrays.c
/******************************************************************************************************************
420AP1AS, F2020
mmk @ lasallecollege
PARALLEL ARRAYS, Leveraging the INDEXES, and 2-Dimensional ARRAYS - notes and exercises
v 1.0
PARALLEL ARRAYS - INTRO
Parallel arrays are 2 or more arrays of the same size that allow us to store related information
across the arrays. The catch is to store related information across the same index.
Let's assume we want to store student grades.
Abrar
Barbara
Bilet
David
Darryl
--------------
<NAME>.
<NAME>.
Dinh
Hanen
Massimo
Sarah
Yucheng
Yuji
Yuri
Yushuo
Arrays names and grades will store names of students and their respective grades.
I.e., names[i] will store a student's name, and grades[i] will store this particular's student's grade.
Darryl's name is stored in names[4] and his grade will be stored in the parallel array grades,
at the same index, 4, grades[4].
names
________________________________________________________________
Ab|Barb | Bil | Dav | Darl | <NAME> |<NAME> ...| Sarah|
______|_____|_____|______|______|_________|____________|________
0 1 2 3 4 5 n-1
grades
___________________________________________________________________
87 |76 |65 | 95 | 85 | 90 | ...... |89
________|______|______|_______|_______|______|____________|____
0 1 2 3 4 5 n-1
SIN
___________________________________________________________________
870 |760 |651 | 950 | 852 | | ...... |891
________|______|______|_______|_______|______|____________|____
0 1 2 3 4 n-1
In order to find Sarah's grade, we need to find where Sarah and her actual grade live (index)
So we iterate over names looking for Sarah, and once we've found her, we retrieve her grade
from grades using the same index.
//finding Sarah's grade
for (int i=0; i<n; i++){
if(strcmp(names[i],"Sarah")){ // this compares strings names[i] and Sarah, returns 1 if equal, 0 otherwise
printf("Sarah's grade is %d", grades[i]);
}
}
// another question could be: retrieve the students whose sin no. starts with 8
// now, you iterate through SIN checking each if sin[i] starts with 8
// if the answer is yes, retrieve the names of the students from array names using those indexes
PARALLEL ARRAYS FOR FREQUENCY COUNTS
Sometimes, we are intersted in counting frequency.
What is the frequency of letters that appear in the following words?
occurrence, def.: the presence of the letter
frequency of occurrence, def.: how many times is it present?
An example to count frequency of letters.
Use an array to store the alphabet
alphabet
_______________________________________________ which character is held at index 9
A | B | C | D |E | F | G | H | I| Z | char x = alphabet[9]
_________|____|___|____|___|___|____|___|___|___| return x
0 1 2 3 4 5 6 7 8 ..25
Say we are looking to store the frequency of the letters in the name Diego
letter: freq
D: 1 printf("%c is the %d letter in the alphabet and occurs %d time(s)", alphabet[8], i+1, frequencia[8])
I: 1 --->> I is the 9th letter of the alphabet and occurs 1 time(s)
E: 1
G: 1 printf("%c is the %d letter in the alphabet and occurs %d time(s)", alphabet[9], i, frequencia[9])
O: 1 -->> but if I choose to start my frequency array at index 1... then ^^^
frequencia de los letras (of letters in Diego's name)
_______________________________________________
| | | 1 | 1 | | | 1 | | 1| <<<--- store the frequency
_________|____|___|____|___|___|____|___|___|___|
0 1 2 3 4 ... 9 <<<--- use the index to represent the letter
Another example
pneumoultramicroscopcilicovulcanoconiotico
supercalifragilisticexpialidocious
S:3 A:3 T:1
U:2 L:3 X:1
P:2 O:2 D:1
E:2 I:7
R:2 F:1
C:3 G:1
alphabet
____________________________________________
A | B | C | D |E | F | G | H | Z |
_________|____|___|____|___|___|____|___|___|
0 1 2 3 4 ... 25
frequency
________________________________________________________________________
| | | | | | | | | <<<--- fill in freq here
____|___|________|________|________|______|_________|________|_________|
0 1 2 3 4 5 25 <<<--- index here
LEVERAGING THE INDEX AS VALUE/INFORMATION (ALPHABET LETTER FREQUENCY)
Sometimes, we can skip the parallell array step and leverage the index directly.
- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
This is an example of using an iterator for its value, not just for looping.
no: 1500- 2700
output: no that were divisible by 5 and 7
for (int i=1500; i<=2700; i=i+5)
if i%7 ==0
printf("%d", i);
M I S S I S S I P P I
M: 1 count_m
I: 4 count_i
S: 4 count_s
P: 2 count_p
________________________________________________________________________________________
| | 4 | | | 1 | 2 | 4 | |
_________|________|________|________|________|_______|__________|_________|_________|___
0 1.... 9 ..... 13 .... 16 ... 19.... 26
A.... I ..... M .... P ... S .... Z
LEVERAGING THE INDEX (GRADE DISTRIBUTION)
Here's another example of index leveraging
________________________________________________________________________________________
75 | 55 | 84 | 78 | 88 | 83 | 98 | 94 | 99 | grades
_________|________|________|________|________|_______|__________|_________|_________|_
0 1 2 3 4 5 6 7 8
how many students have < 60 x1
60-69 0
70-79 x2
80-89 x3
90-100 x3
___________________________________________________________________________________________
1 | | | | | | | 2 | 3 | 3| distribution
_________|________|________|________|________|_______|__________|_________|_________|___|__
0 1 2 3 4 5 6 7 8 9 <<< --- Range of grades
Create an array of size 10 and store in index i the number of grades that appear in range i0-i9.
Or store in 0 the number of grades that are less than 60, signaling failing.
// switch example with range (only on ints and char)
// iterating over array grades
// for every grade = grades[i]
switch(grade){
case 0 ... 59: distribution[0]++; break;
case 60 ... 69: distribution[6]++; break;
case 70 ... 79: distribution[7]++; break;
case 80 ... 89: distribution[8]++; break;
case 90 ... 100: distribution[9]++; break;
default: printf("Invalid grade entry!\n");
}
LEVERAGING THE INDEX (DECK OF CARDS)
Parallel arrays & 2-D arrays
Let's play Poker! This is a 52-cards deck.
_______________________________________________________________
Hearts | ACE 2 3 4 5 6 7 8 9 10 Jack Queen King |
Diamond | ACE 2 3 4 5 6 7 8 9 10 Jack Queen King |
Clubs | ACE 2 3 4 5 6 7 8 9 10 Jack Queen King |
Spade | ACE 2 3 4 5 6 7 8 9 10 Jack Queen King |
|______________________________________________________________|
How do I store a hand of 5 cards?
2 of Hearts
Ace of Spades
7 of Clubs
King of Hearts
7 of Diamonds
Well, I could create an array and use its value to match the cards, such that:
Index - Card
0 - Joker
1 - ace
2 - 2
.
.
.
10 - 10
11 - Jack
12 - Queen
13 - King
You have different options:
Use the 0 for the joke (although we dont have jokers in poker, but in case we play a diff game)
Use the 0 for the king, followed by 1 for the ace, and finish at 12 for the queen
Use the 0 for the 1, and do a little adjustment when you are searching/printing.... not my fav.
You really want to keep your code as simple and adjustable.
So, let's store the ace at index 1, the king at index 13, and the rest in between.
my hand
___________________________________________________________________________________________________
| 1 | 1 | | | | | 2 | | | | | | 1 |
________|________|________|________|________|_______|______|____|_____|______|____|___|______|______|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 <<<--- index represents cards
Ok! now, I have my hand stored, but I have no idea which families these numbers/images belong to.
This is where parallel arrays can come in handy.
I can create one array for every suit. And in that array, I can store the information.
___________________________________________________________________________________________________
| | | | | | | 1 | | | | | | | diamond
________|________|________|________|________|_______|______|____|_____|______|____|___|______|_____|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 <<<--- index represents cards
___________________________________________________________________________________________________
| 1 | | | | | | | | | | | | | spade
________|________|________|________|________|_______|______|____|_____|______|____|___|______|______|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 <<<--- index represents cards
___________________________________________________________________________________________________
| | | | | | | 1 | | | | | | | clubs
________|________|________|________|________|_______|______|____|_____|______|____|___|______|_____|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 <<<--- index represents cards
___________________________________________________________________________________________________
| | 1 | | | | | | | | | | | 1 | hearts
________|________|________|________|________|_______|______|____|_____|______|____|___|______|______|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 <<<--- index represents cards
If you are comfortable handling one data structure (courtesy of S. Fauteux) you could use one array!!
______________________________________________________________________
1 2 | 3 13| 1 2 3 | 12 13 | 1 2 3 | 12 13 | 1 2 | 12 13| mydeck (52 cards)
________|_______|_______|________|________|_______|______|________|__ size = 52
0 ... 12 13 ... 25 26 .... 38 39 ...... 51 <<<<---- suits are stored sequentially
Hearts index/13 = 0, for 0<=i<=12
Diamonds index/13 = 1, for 13<=i<=25
Clubs index/13 = 2, for 26<=i<=38
Spade index/13 = 3, for 39<=i<=51
Here, you use the index to indicate the suit. And you store the value of the card directly in the array.
If you store the cards in order, then:
2 of Hearts <<<-- index 1
Ace of Spades <<<--- index 39
7 of Clubs <<<--- index 32
King of Hearts <<<--- index 12
7 of Diamonds <<<---- index 19
Now, to store your hand, you can use one array.
In *this* array, the index is not being used for its value. It's simply there to hold 5 element (cards).
____________________________________________
1 | 39 | 32 | 12 | 19 | my hand
________|_______|_______|________|________|_ <<<---- find the index of that card and store it here
0 1 2 3 4
The values in the array are the indexes of array mydeck!
for (int i=0; i<5; i++){
mydeck[i] <<--- the value of the card is stored at index i in array mydeck
myhand[i]/3 <<<--- the suit can be obtained by dividing myhand[i] (which is the index in my deck) by 13
switch(myhand[i]/13){ <<<--- and switching on the result!
case 0: hearts; break;
case 1: diamonds; break;
case 2: clubs; break;
case 3: spade; break;
default: something's off;
}
}
2-D arrays
Store information in a tabulated format! Everything that we've seen for arrays applies with one added [].
We still need the size (n) and we still start with index 0 and go to index n-1
Simple array decalaration: type + name + [size]; (size: number of elements in the array)
2-D array declaration: type + name + [rows][cols]; <<<--- always rows first, then columns.
int my_hand[4][14] <<<---- YES! I have 4 rows and 14 cols.
int my_hand[14][4] <<<---- YES! But now I have 14 rows and 4 columns.
I can also initialize the values in the array like so:
2D array declaration & Initialization:
int numbers[2][2] = {{1,2}, {3,4}}; <<<--- notice the nested {}, these represent the values in rows 0, 1, 2, ...
int numbers[2][2] = {1, 2, 3, 4}; <<<--- or I can do without the nested {}, and the 2D array will fill up one row at a time.
Without specifying the size:
int numbers[][] = {1, 2, 3, 4}; <<<--- I can have the same initialization without specifying the size.
int numbers[][] = {{1,2}, {3,4}};
_______
| 1 | 2 |
|___|___|
| 3 | 4 |
|___|___|
Now, coming back to the poker example.
I can grab all the parallel arrays and put them in one 2D-array:
- the row will represent the suit, and
- the columns will represent the cards
Much like
my_hand
__0____1_____2___3____4____5_____6______7_____8_____9____10____11____12_____13___
0|__0__|____|_____|___|____|_____|_____|__1__|_____|_____|_____|____|______|_______ (diamonds)
1|__0__|____|__1__|___|____|_____|_____|_____|_____|_____|_____|____|______|____1__ (hearts)
2|__0__|_1__|_____|___|____|_____|_____|_____|_____|_____|_____|____|______|_______ (spades)
3|__0__|____|_____|___|____|_____|_____|__1__|_____|_____|_____|____|______|_______ (clubs)
for (int i=0; i<=3; i++)
for (int j=0; j<=13; j++)
printf("%d", my_hand[i][j])
if (my_hand[i][j] == 1)
printf("a %d of ", j)
switch(i){
case 0: printf("diamonds"); break;
case 1: printf("hearts"); break;
case 2: printf("spades"); break;
case 3: printf("clubs"); break;
default: printf("something's off!");
}
Say, for some unconventional reason, you happened to be iterating over the columns, then the rows,
when you need to access the slot, you still need to access in a [row][column] order:
for (int j=0; j<=13; j++) <<<--- notice iterating over columns
for (int i=0; i<=3; i++) <<<--- notice iterating over the rows
my_hand[i][j] <<<--- notice access [row][columns]
In the above 2D-array, we had the following representation:
// row: 0 for Diamonds
// row: 1 for Hearts
// row: 2 for Spades
// row: 3 for Clubs
for access or assignment: my_hand[row-index][col-index]
2 of Hearts if this was a single array: hearts[2]=1, in a 4x14 array: my_hand[1][2]=1;
Ace of Spades my_hand[2][1]=1
7 of Clubs my_hand[3][7]=1
King of Hearts my_hand[1][13]=1
7 of Diamonds my_hand[0][7]=1
Queen of Spade my_hands[2][12]=1
King of Diamonds my_hands[0][13]=1
Ace of Clubs my_hand[3][1]=1
5 of Hearts my_hand[1][5]=1
4 of Clubs my_hand[3][4]=1
int x = my_hand[i][j]
If I return the 5 of Hearts to the deck,
my_hand[1][5]=0
What if my I had a double deck?
my_hand[1][5]--; or:
my_hand[1][5]= my_hand[1][5]-1;
for (int j=0; j<=13; j++)
for (int i=0; i<=3; i++)
my_hand[i][j]
Get rid of the 2 of Hearts
my_hand[2][1]--; // double deck
my_hand[2][1]=0; // single deck
for(int i=0; i<4; i++)
for(int row=0; row<4; row++)
for(int r=0; r<4; r++)
for(int i=0; i<4; i++) // iterates over the row
for (int j=0; j<=13; j++) // iterates over the col
//for (int j=1; j<=13; j++) // start at j=1 bc. this col isn't holding anything
if(my_hand[i][j]>0)
//if(my_hand[i][j]>=1)
//if(my_hand[i][j]==1) // only for one deck!
//printf("%d", my_hand[i][j]) // will print everything
printf("%d of %d", j, i);
*********************************************************************************************************/
/*
Exercise 1
Prompt the user for two integers m and n, and return an nxm grid where the value in the (i,j) position
is computed as follows: i+mj.
Below is an example of a 5x6 grid
0 5 10 15 20 25
1 6 11 16 21 26
2 7 12 17 22 27
3 8 13 18 23 28
4 9 14 15 24 29
*/
int m;
int n;
printf("Please give us an int: ");
scanf("%d", &m);
printf("\nPlease give us another int: ");
scanf("%d", &n);
int nxm[5][6];
for(int i = 0; i < 5; ++i)
{
for(int j = 0; j < 6; ++i)
{
nxm[i][j] = i+m*j;
}
}
/*
Exercise 2
Prompt the user to enter a number n. The examples below hold for n=6.
a/ Use a 2D array to print the following pattern up to line n
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
*/
int n;
printf("How far should we print? (int): ");
scanf("%d", &n);
printf("\n");
int pattern[n][n];
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < i + 1; ++j)
{
pattern[i][j] = i + 1;
printf("%d", pattern[i][j]);
}
printf("\n");
}
/*
b/ Use 2D array to print n lines in the following pattern.
x
x x
x x x
x x x x
x x x x x
x x x x x x
*/
int n = 5;
char pattern[n][n];
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < i + 1; ++j)
{
pattern[i][j] = 'x';
printf("%c ", pattern[i][j]);
}
printf("\n");
}
/*
Exercise 3
Ask the user to type in 9 numbers in 3 rows of 3 numbers each. Your job is to:
a/ read the numbers in a two-dimensional array,
b/ compute the sum of each row and each column, and
c/ output the array as well as the row and column sums in the following format:
ARRAY: ROW SUM
1 2 3 6
3 3 3 9
3 2 1 6
COLUMN SUMS:
7 7 7
*/
int array[3][3];
printf("Populate the 3x3 array.\n");
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
printf("\nColumn%d row%d: ", i + 1, j + 1);
scanf("%d", &array[i][j]);
}
}
int col1Sum = 0;
int col2Sum = 0;
int col3Sum = 0;
printf("Array: Row Sum:\n");
for(int i = 0; i < 3; ++i)
{
int rowSum = 0;
for(int j = 0; j < 3; ++j)
{
printf("%d ", array[i][j]);
rowSum += array[i][j];
switch (i)
{
case 0: col1Sum += array[i][j]; break;
case 1: col2Sum += array[i][j]; break;
case 2: col3Sum += array[i][j]; break;
default: printf("Switch out of range (did i got bigger?)");
}
}
printf(" %d\n", rowSum);
}
printf("Column Sum: \n %d %d %d", col1Sum, col2Sum, col3Sum);
/*
Exercise 4
Write a program that allows a user to play tic tac toe. The program should ask for moves
alternating between player X and player O (alternatively, the second player can be the computer).
The program displays the game positions as follows:
1 2 3
4 5 6
7 8 9
The players enter their moves by entering the position number. After each move, the program displays
the changed board. A sample configuration would be:
X X O
4 5 6
O 8 9
The game ends when:
a/ a player has 3 Xs or 3 Os spanning across the board, horizontally, vertically, or diagonally, or
b/ there are no moves that can be made
*/
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
void DisplayGameBoard(char gameBoard[5][5])
{
printf("\n\n");
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
printf("%c", gameBoard[i][j]);
}
printf("\n");
}
}
void TurnPosToPosXY(int pos, int* posX, int* posY)
{
switch (pos)
{
case 1: *posX = 0; *posY = 0; break;
case 2: *posX = 2; *posY = 0; break;
case 3: *posX = 4; *posY = 0; break;
case 4: *posX = 0; *posY = 2; break;
case 5: *posX = 2; *posY = 2; break;
case 6: *posX = 4; *posY = 2; break;
case 7: *posX = 0; *posY = 4; break;
case 8: *posX = 2; *posY = 4; break;
case 9: *posX = 4; *posY = 4; break;
default: printf("Problem with the switch in MakeBotMove();");
}
}
int MakeBotMove(char gameBoard[5][5])
{
int pos;
int posX;
int posY;
do
{
pos = rand() % 8 + 1;
TurnPosToPosXY(pos, &posX, &posY);
}
while(gameBoard[posY][posX] == 'X' || gameBoard[posY][posX] == 'O');
return pos;
}
bool CheckIfGameIsFinish(char gameBoard[5][5])
{
bool isGameWon = 0;
bool isGameTie = 0;
//Horizontal Lines
for (int i = 0; i < 5; i += 2)
{
if(gameBoard[i][0] == gameBoard[i][2])
{
if(gameBoard[i][2] == gameBoard[i][4])
{
isGameWon = 1; break;
}
}
}
if(!isGameWon)
{
//Vertical Lines
for (int i = 0; i < 5; i += 2)
{
if(gameBoard[0][i] == gameBoard[2][i])
{
if(gameBoard[2][i] == gameBoard[4][i])
{
isGameWon = 1; break;
}
}
}
}
if(!isGameWon)
{
//Diadonal lines
if((gameBoard[0][0] == gameBoard[2][2] && gameBoard[2][2] == gameBoard[4][4]) || (gameBoard[0][4] == gameBoard[2][2] && gameBoard[2][2] == gameBoard[4][0]))
{
isGameWon = 1;
}
}
bool isBoardFull = 1;
if(!isGameWon)
{
for (int x = 0; x < 5; x += 2)
{
for(int y = 0; y < 5; y += 2)
{
if(gameBoard[x][y] != 'X' && gameBoard[x][y] != 'O')
{
isBoardFull = 0;
break;
}
}
if(!isBoardFull) break;
}
}
if(isGameWon)
{
printf("\n\nWell played!\n");
return 1;
}
if(!isGameWon && isBoardFull)
{
printf("\n\nTie!\n");
return 1;
}
return 0;
}
void ManageTurns(bool isSoloGame, bool isPlayer1Turn, char gameBoard[5][5], char player1Char)
{
do{
int move;
char charToPlace;
int posX;
int posY;
do{
if(isPlayer1Turn)
{
if(isSoloGame)
{
printf("\n\nYour turn!");
}
else
{
printf("\n\nPlayer1 turn: ");
}
scanf("%d", &move);
charToPlace = player1Char;
}
else
{
if(isSoloGame)
{
printf("\n\nMy turn!");
move = MakeBotMove(gameBoard);
}
else
{
printf("\n\nPlayer2 turn: ");
scanf("%d", &move);
}
if(player1Char == 'X')
{
charToPlace = 'O';
}
else
{
charToPlace = 'X';
}
}
if(move > 0 && move < 10)
{
TurnPosToPosXY(move, &posX, &posY);
}
} while (move < 1 || move > 9 || gameBoard[posY][posX] == 'X' || gameBoard[posY][posX] == 'O');
gameBoard[posY][posX] = charToPlace;
if(isPlayer1Turn)
{
isPlayer1Turn = 0;
}
else
{
isPlayer1Turn = 1;
}
DisplayGameBoard(gameBoard);
}while (!CheckIfGameIsFinish(gameBoard));
}
void StartGame(bool isSoloGame/*, int difficulty*/) //I might add a dificulty option later
{
char player1Char;
do
{
printf("\n\nChoose your character:\nDo you want to play as X or O?\n");
scanf(" %c", &player1Char);
player1Char = toupper(player1Char);
}
while (player1Char != 'X' && player1Char != 'O');
char gameBoard[5][5] = {
{'1','|','2','|','3'},
{'-','+','-','+','-'},
{'4','|','5','|','6'},
{'-','+','-','+','-'},
{'7','|','8','|','9'}
};
DisplayGameBoard(gameBoard);
printf("(type the number of the posistion you want to place your character when it is your turn to make your move)");
bool isPlayer1Turn = 0;
if(player1Char == 'O')
{
isPlayer1Turn = 1;
}
ManageTurns(isSoloGame, isPlayer1Turn, gameBoard, player1Char);
}
void GenerateOptionsMenu()
{
printf("No options were implemented yet\n");
}
bool GenerateMainMenu()
{
printf("TicTacToe! (type the number to select an option)\n\n1. Solo\n2. Multiplayer\n3. Options\n4. Exit\n\n");
int choice;
scanf("%d", &choice);
switch (choice)
{
case 1: StartGame(1); break;
case 2: StartGame(0); break;
case 3: GenerateOptionsMenu(); break;
case 4: printf("\n\nbye bye!"); return 1;
default: printf("\n\nGG but you'll have better luck whit an option from the menu\n\n");
}
return 0;
}
int main()
{
bool closeProgram = 0;
do
{
closeProgram = GenerateMainMenu();
}
while(!closeProgram);
return 0;
}
/*
Exercise 5
Write a program to assign passenger seats in an airplane. Assume a small airplane with seats numbered as
follows:
1 A B C D
2 A B C D
3 A B C D
4 A B C D
5 A B C D
6 A B C D
7 A B C D
The program should display the seat pattern, marking with an 'X' the seats already assigned. For example,
after seats 1A, 2B, and 4C are taken, the display should look like:
1 X X C D
2 A B C D
3 A B C D
4 A B X D
5 A B C D
6 A B C D
7 A B C D
After displaying the seats available, the program prompts for the seats desired, the user types in a seat,
and then a display of available seats is updated. This continues until all seats are filled or until the user
signals that the program should end. If the user types in a seat that is already assigned, the program should
say that the seat is occupied and ask for another choice.
*/<file_sep>/spring.c
#include<stdio.h>
//<NAME>
//9/21/2020
//...?
int main()
{
int day;
int month;
int year;
char messageBase[] = "We are in ";
printf("\nMonth number: ");
for(;;)
{
scanf("%d", month);
if(month < 1 || month > 12)
{
printf("\nPlease enter a number between 1 and 12\n")
}
else break;
}
printf("\nYear: ");
scanf("%d", year);
printf("Day number: ");
for(;;)
{
scanf("%d", day);
if(day < 1 || day > 31 || (month == 2 && day > 28 + FindLeapYear(year)) || (month % 2 == 0 && day > 30))
{
printf("\nThis day doesn't appear in this month!\n
Please try again!\n")
}
else break;
}
if((month > 3 && month < 6) || (month == 3 && day > 20) || (month == 6 && day < 21)) //season change the 21st
{
printf(messageBase + "spring!");
}
else if((month > 6 && month < 9) || (month == 6 && day > 20) || (month == 9 && day < 21))
{
printf(messageBase + "summer!");
}
else if((month > 9 && month < 12) || (month == 9 && day > 20) || (month == 12 && day < 21))
{
printf(messageBase + "fall!");
}
else //if((month< 3 || month == 12) || (month == 12 && day > 20) || (month == 3 && day < 21)) //the in comment condition was for practice
{
printf(messageBase + "Winter");
}
int FindLeapYears(int year)
{
if(year == 2000 || (year % 4 = 0 && (year % 100 != 0 || year % 400 == 0)))
{
return 1;
}
return 0;
}
enum dayOfTheWeak{Sunday, Mondy, Thuesday, Fryday, Thursday, Wendsday, Saturday}
void WriteDayOfTheWeak(int y, int m)
{
float y0 = y - (14-m)/12;
float x = y0 + y0/4 - y0/100 + y0/400;
float m0 = m + 12 * ((14-m)/12)-2;
int d0 = (d + x + (31 * m0)/12) % 7;
printf("It's a " + dayOfTheWeak[d0])
}
}<file_sep>/patterns exercises/neverEndingSuite.c
int main()
{
int n= 1;
for(int i = 1; i < 6; ++i)
{
for(int limit = n + i; n < limit ; ++n)
{
printf("%d ", n);
}
printf("\n");
}
return 0;
}<file_sep>/C.c
#include<stdio.h>
//<NAME>
//9/11/2020
//Debora thingny remake
int main() {
int firstNote = -1;
int secondNote = -1;
int thirdNote = -1;
printf("What is your first note?\n");
scanf("%d", firstNote);
printf("\nWhat is your second note?\n");
scanf("%d", secondNote);
printf("\nWhat is your third note?\n");
scanf("%d", thirdNote);
float avg = (firstNote + secondNote + thirdNote) / 3
if(avg < 60){printf("You failled!")}
else{printf("You might have a future after all...")}
return 2;
}<file_sep>/FauteuxSamuelProgFinal.c
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
struct Smartphone
{
char brand[15];
char nameAndOrModel[20];
int screenSize[2];
int memory;
int cameraResolution;
float prices[3];
int nbInStock;
};
struct Smartphone smartphones[50];
int k = 0; //k keeps the number of items that were inserted in smartphones but why the heck is it called k?
bool CheckIfUserWantToContinue(char yesNoQuestion[])
{
char choice;
do{
printf("\n\n%s (y for yes, n for no)\n", yesNoQuestion);
scanf(" %c", &choice);
}while(!(tolower(choice) == 'y' || tolower(choice) == 'n'));
if(choice == 'y')
{
return 1;
}
return 0;
}
void PopulateInventory()
{
char doYouWantToContinue[] = "Insert another product?";
do{
printf("\n\nBrand: ");
scanf("%s", smartphones[k].brand);
printf("\nName and/or model: "); //this make me feel like it should be two field but the instructions make me doubt this
scanf("%s", smartphones[k].nameAndOrModel);
printf("\nScreen width (in inches): ");
scanf(" %d", &smartphones[k].screenSize[0]); //the space before the %d is mendatory (it get rid of trailling ints)
printf("\nScreen height (in inches): ");
scanf("%d", &smartphones[k].screenSize[1]);
printf("\nMemory (in G): "); //phone memory is always a clean Gigabyte number
scanf("%d", &smartphones[k].memory);
printf("\nCamera resolution: "); //camera resolution tend to be represented by the width only, idk why
scanf("%d", &smartphones[k].cameraResolution);
printf("\nNumber in stock: ");
scanf("%d", &smartphones[k].nbInStock);
printf("\n\nPrices: \nNo plan: ");
scanf("%f", &smartphones[k].prices[0]);
printf("\nOne year plan: ");
scanf("%f", &smartphones[k].prices[1]);
printf("\nTwo years plan: ");
scanf("%f", &smartphones[k].prices[2]);
++k;
}while (CheckIfUserWantToContinue(doYouWantToContinue));
}
void DisplayInventoryEntry(int smartphoneIndex)
{
printf("\n\nBrand: %s\nName and/or model: %s\nScreen size: %dX%d\nMemory: %dG\nCamera resolution: %dp\nNumber in stock: %d\n\nPrices: \nNo plan: $%.2f\nOne year plan: $%.2f\nTwo years plan: $%.2f\n", smartphones[smartphoneIndex].brand, smartphones[smartphoneIndex].nameAndOrModel, smartphones[smartphoneIndex].screenSize[0], smartphones[smartphoneIndex].screenSize[1], smartphones[smartphoneIndex].memory, smartphones[smartphoneIndex].cameraResolution, smartphones[smartphoneIndex].nbInStock, smartphones[smartphoneIndex].prices[0], smartphones[smartphoneIndex].prices[1], smartphones[smartphoneIndex].prices[2]);
}
void Searchbybrand(char brand[15])
{
bool found = 0;
for (int i = 0; i < k; ++i)
{
if(strcmp(smartphones[i].brand, brand) == 0)
{
found = 1;
DisplayInventoryEntry(i);
}
}
if(!found)
{
printf("Sorry, Mr. User, we are out of %s phones", brand);
}
}
void ProcessPurchase(int i)
{
if(smartphones[i].nbInStock > 0)
{
char confirmPurchase[] = "Please type Y to confirm your purchase: ";
int choice;
do{
printf("\n\nDo you want: \n 1. No plan for $%.2f\n 2. One year plan for $%.2f\n 3. Two year plan for $%.2f\n(Select the number to make your choice)\n", smartphones[i].prices[0], smartphones[i].prices[1], smartphones[i].prices[2]);
scanf("%d", &choice);
}while(choice < 1 || choice > 3);
printf("\nThis will cost $%.2f", smartphones[i].prices[choice-1]);
if(!CheckIfUserWantToContinue(confirmPurchase))
{
return;
}
--smartphones[i].nbInStock;
printf("\n\nCongratulations! You now own the new %s %s", smartphones[i].brand, smartphones[i].nameAndOrModel);
}
else
{
printf("\n\nSorry, we have 0 %s %s in stock!", smartphones[i].brand, smartphones[i].nameAndOrModel);
}
}
bool SearchByModel(char model[], int* searchedModelIndex)
{
*searchedModelIndex = 0;
bool found = 0;
for (int i = 0; i < k; ++i)
{
if(strcmp(model, smartphones[i].nameAndOrModel) == 0)
{
found = 1;
*searchedModelIndex = i;
break;
}
}
return found;
}
void BuyAnItem()
{
char buySomeMore[] = "Do you want to purchase another item? ";
do{
char desiredModel[15];
int desiredModelIndex;
printf("\n\nPlease type the name of the disired model: ");
scanf("%s", desiredModel);
if(!SearchByModel(desiredModel, &desiredModelIndex))
{
printf("\n\nSorry we didn't find that model in our inventory");
}
else
{
ProcessPurchase(desiredModelIndex);
}
}while(CheckIfUserWantToContinue(buySomeMore));
}
void ReturnPhone()
{
char returnSomeMore[] = "Do you want to return another item? ";
do{
char desiredModel[15];
int desiredModelIndex;
printf("\n\nPlease type the name of the model you want to return: ");
scanf("%s", desiredModel);
if(!SearchByModel(desiredModel, &desiredModelIndex))
{
printf("\n\nSorry we can't accept this return.");
}
else
{
++smartphones[desiredModelIndex].nbInStock;
printf("\n\nReturn completed, here's your money!");
}
}while(CheckIfUserWantToContinue(returnSomeMore));
}
bool Exit(bool keepGoing)
{
if(keepGoing)
{
return 0;
}
else
{
return 1;
}
}
bool GenerateMainMenu()
{
printf("Type the number to select an option\n\n1. Populate inventory\n2. Display all items of a brand\n3. Buy an item\n4. Return an Item\n5. Display inventory content\n6. Exit the system\n\n");
int choice;
scanf("%d", &choice);
switch (choice)
{
case 1: PopulateInventory(); break;
case 2: ;
char searchForAnotherBrand[] = "Search for another brand? ";
do{
char brand[15];
printf("Which brand are you looking for? ");
scanf("%s", brand);
Searchbybrand(brand);
}while(CheckIfUserWantToContinue(searchForAnotherBrand)); //the guide lines start to be very bothersome, I preferred my own naming convetion and my while was out of the case
break;
case 3: BuyAnItem(); break;
case 4: ReturnPhone(); break;
case 5:
for (int i = 0; i < k; ++i)
{
DisplayInventoryEntry(i);
}
break;
case 6: return Exit(0);
default: printf("\n\nUnknown option\n\n");
}
return 0;
}
int main()
{
bool closeProgram = 0;
do
{
closeProgram = GenerateMainMenu();
}
while(!closeProgram);
return 0;
}<file_sep>/if_while/if_while6.c
#include<stdio.h>
int main()
{
int numberToFactorize;
printf("Which integer do you want to factorize? \n");
scanf("%d", numberToFactorize);
int f = numberToFactorize;
while(f > 1)
{
--f;
numberToFactorize *= f;
}
printf(numberToFactorize);
}<file_sep>/if_while/if-while-exercises.c
/*
F2020-420AP1AS
Exercises: Conditional Statement & While Loop
mmk, v1.0
Conditional Statements Exercises:
https://w3resource.com/c-programming-exercises/conditional-statement/index.php
While loop (and conditional) exercises:
1. Write a program to print numbers from 1 to 10.
2. Write a program that prints all the numbers from 0 to 6 except 3 and 6.
3. Write a program to print the numbers between 1500 and 2700 that are divisible by 5 and 7.
4. Write a program that prompts the user to input a positive integer.
It should then print the multiplication table of that number.
5. Write a program that prompts the user to input a positive integer.
It should then output a message indicating whether the number is a prime number.
6. Write a program to find the factorial value of any number entered through the keyboard.
n! = n x (n-1)!
7. Two numbers are entered through the keyboard.
Write a program to find the value of one number raised to the power of another.
8. Write a program to guess a number between 1 to 9. If the user guesses wrong, then
the prompt appears again until the guess is correct. On a successful guess, the user will get a
"Well guessed!" message, and the program will exit.
9. Write a program to calculate the sum of first 10 natural number.
10. Write a program that reads a set of integers, and then prints the following:
the number of even integers,
the number of odd integers,
the sum of the even integers, and
that of the odd integers.
*/<file_sep>/patterns exercises/suitePyramid.c
#include <stdio.h>
int main()
{
for(int i = 1; i < 6; ++i)
{
for(int n = 0; n < i; ++n)
{
printf("%d ", i + n);
}
printf("\n");
}
return 0;
}<file_sep>/if_while/if_while1.c
void main()
{
int i = 0;
while(i<10)
{
printf(++i); //thx (I did it in 3)
//++i increment and then return the value
}
}<file_sep>/pointZero/pointZeroClass.c
#include <stdio.h>
int main()
{
const int stop = 6; //-1 = how many row in my tables and how long is a row
//n is const firstNumber in later versions //n = firstNumber since we don't modify const
for(int n = 1; n < stop; ++n) //each iteration of this for will create a new row
{
for(int i = 1; i < stop; ++i) //first table
{
printf("%d", n + i - 1); //this looks weird if you don't look at the display
}
printf(" "); //to separates the two tables
for(int point = n; point > 1; --point) //place the points
{
printf(".");
}
for(int zero = 0; zero<stop-n; ++zero) //place the zeros
{
printf("0");
}
printf("\n"); //change row before going back to the initial for
}
return 0;
} //iteration 1, n = 1, n < 6 is t, exec 18 to 35; ++n; n = 2;
//iteration 2, n = 2, n < 6 is t, exec 18 to 35; ++n; n = 3;
//iteration 3, n = <file_sep>/patterns exercises/upsidedownSuitePyramid.c
#include <stdio.h>
int main()
{
for(int i = 1; i < 6; ++i)
{
for(int n = 5; n > 5 - i; --n) //I should assing 5 to a new constant StartingValue
{
printf("%d ", n);
}
printf("\n");
}
return 0;
}<file_sep>/patterns exercises/1Hypotenuse.c
#include <stdio.h>
int main()
{
for(int i = 5; i > 0; --i)
{
for(int n = 6 - i; n > 0 ; --n) //I should assing 5 to a new constant StartingValue
{
printf("%d ", n);
}
printf("\n");
}
return 0;
}<file_sep>/if_while/if_while5.c
#include<stdio.h>
int main()
{
printf("Please give us a positive integer. \n");
int givenInteger;
scanf("%d", givenInteger);
if(givenInteger == 0 || givenInteger == 1)
{
printf("\n0 and 1 arn't consider as prime number");
break;
}
i = 2; //prime number can only be divide by 1 and themselves so I am looking between those value
while(i < givenInteger)
{
if(givenInteger % i == 0)
{
printf("\n" + givenInteger + " is a prime number!");
break;
}
}
printf("\n" + givenInteger + " in not a prime number. ")
}
|
4812c223638cd8a3ae76e5d6bada509ae83580d4
|
[
"C"
] | 22
|
C
|
enderfree/alg
|
01d425ce5dd2d3c172b5e0bc9ceb305c4e31af58
|
046b59ecc680efb3c4fbb04c6886f225287e4bcd
|
refs/heads/master
|
<file_sep>package com.priyam.spring;/**
* Created by dni_tahniat on 24/1/2017.
*/
import com.priyam.spring.entity.Student;
import com.priyam.spring.repository.StudentRepo;
import com.priyam.spring.service.IStudentService;
import com.priyam.spring.service.StudentServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class MockServiceTest {
private static final Logger logger = LoggerFactory.getLogger(MockServiceTest.class);
// @Autowired
private IStudentService studentService;
// @Autowired
// @MockBean
private StudentRepo studentRepoMock;
@Before
public void setUp(){
logger.info("Inside Before :: setUp() ..");
studentRepoMock= mock(StudentRepo.class);
studentService=new StudentServiceImpl(studentRepoMock);
logger.info("Inside Before :: setUp() finished successfully..");
}
@Test
public void testFindByID(){
logger.info("Inside testFindByID ..");
// studentRepoMock= mock(StudentRepo.class);
// studentService=new StudentServiceImpl(studentRepoMock);
Student s1=new Student(1,"Ashraf","011");
Student s2=new Student(2,"Billgates","012");
Student s3=new Student(3,"Catstevens","013");
List<Student> s2List=new ArrayList<Student>();
s2List.add(s2);
// Student x=s2List.get(0);
// logger.info("x is : "+x.getId());
when(studentRepoMock.save(s1)).thenReturn(s1);
when(studentRepoMock.save(s2)).thenReturn(s2);
when(studentRepoMock.save(s3)).thenReturn(s3);
when(studentRepoMock.findById(2)).thenReturn(s2List);
// when(studentRepoMock.findByName("Ashraf").get(0)).thenReturn(s1);
logger.info("expected : "+s2List.get(0).getId()+" ; actual : "+studentService.findById(2).getId());
assertEquals(s2List.get(0),studentService.findById(2));
// assertEquals(s2,studentService.findByName("Ashraf").get(0));
// when(studentRepoMock.findById(1)).thenReturn(null);
// Student student_x=studentService.findById(1);
// assertEquals(student_x,null);
logger.info("Inside testFindByID :: finished successully..");
}
}
<file_sep># StudentCourseRegistration-SpringBoot-OracleDB
A Sample Spring Boot CRUD application which demonstrates features of Spring Boot and it's seamless integration with Oracle Database.
<br/>
<b>Project Structure : </b><i>StudentCourseRegistration-SpringBoot-OracleDB/project structure.PNG</i><br>
<b>View in browser : </b><i>StudentCourseRegistration-SpringBoot-OracleDB/view in browser.PNG</i><br>
<b>IDE Used :</b> Intellij IDEA 2016.3<br/>
<b>Java Version Used :</b> 1.8<br/><br/>
<b>Dependencies (Maven) :</b><br/>
- JDBC
- Oracle
- Thymeleaf
- Web
- JPA
<b>Oracle DB integration :</b><br/>
- Driver version : 172.16.58.3<br/>
- Add Oracle JDBC driver in your local maven repository :
<a href="https://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/">https://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/</a><br/>
- Add these lines within dependencies in pom.xml (maven) : <br/>
```
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>172.16.58.3</version>
</dependency>
```
- Configure Oracle Database properties in application.properties : <br/>
```
#spring.datasource.url=jdbc:mysql://localhost:3306/_SCHEMA_NAME
#spring.datasource.username=_YOUR_USERNAME
#spring.datasource.password=_YOUR_<PASSWORD>
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#spring.jpa.hibernate.ddl-auto=update
#server.port=9080
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@_SERVER_IP:_SERVER_PORT:_SERVICE_ID
spring.datasource.username=_YOUR_USERNAME
spring.datasource.password=_<PASSWORD>
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true
server.port=8080
```
<b>Application URL :</b> <a href="http://localhost:8080/StudentApp/create/">http://localhost:8080/StudentApp/create/</a><br/><br/>
<b>pom.xml</b><br/>
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.priyam.spring</groupId>
<artifactId>springoracledbcrud-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringOracleDBCRUD-Demo</name>
<description>SpringOracleDBCRUD-Demo</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/oracle/ojdbc6 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>172.16.58.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>mysql</groupId>-->
<!--<artifactId>mysql-connector-java</artifactId>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
<file_sep>package com.priyam.spring.service;/**
* Created by dni_tahniat on 23/1/2017.
*/
import com.priyam.spring.entity.Student;
import com.priyam.spring.repository.StudentRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Transactional
@Service
public class StudentServiceImpl implements IStudentService{
private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
private StudentRepo studentRepo;
public StudentServiceImpl(StudentRepo studentRepo){
this.studentRepo=studentRepo;
}
public StudentRepo getStudentRepo() {
return studentRepo;
}
public void setStudentRepo(StudentRepo studentRepo) {
this.studentRepo = studentRepo;
}
@Override
public List<Student> findAll() {
List<Student> Studentlist=new ArrayList<>();
Iterator<Student> iterator=studentRepo.findAll().iterator();
while(iterator.hasNext()){
Studentlist.add(iterator.next());
}
return Studentlist;
}
@Override
public Student findById(int id) {
return studentRepo.findById(id).get(0);
}
@Override
public List<Student> findByName(String name) {
return studentRepo.findByName(name);
}
@Override
public List<Student> findByNameLike(String name) {
return studentRepo.findByNameLike(name);
}
@Override
public void removeStudent(int id) {
studentRepo.delete(id);
}
@Override
public Student addStudent(Student student) {
if(student!=null) {
studentRepo.save(student);
}else{
logger.error("Student data cannot be null.");
}
return student;
}
@Override
public void editStudent(Student Student) {
Student c=findById(Student.getId());
if(c!=null) {
studentRepo.save(Student);
}else{
logger.error("Student data doesn't exist");
}
}
@Override
public List<Student> findStudentsWithEvenID() {
return studentRepo.findStudentsWithEvenID();
}
}
<file_sep>package com.priyam.spring.service;/**
* Created by dni_tahniat on 23/1/2017.
*/
import com.priyam.spring.entity.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public interface IStudentService {
static final Logger logger = LoggerFactory.getLogger(IStudentService.class);
public List<Student> findAll();
public Student findById(int id);
public List<Student> findByName(String name);
public List<Student> findByNameLike (String name);
public void removeStudent(int id);
public Student addStudent(Student customer);
public void editStudent(Student customer);
public List<Student> findStudentsWithEvenID();
}
<file_sep>package com.priyam.spring;
import com.priyam.spring.entity.Student;
import com.priyam.spring.repository.StudentRepo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MockDALTest {
//REPOSITORY TEST ...
static final Logger logger = LoggerFactory.getLogger(MockDALTest.class);
@Autowired
private StudentRepo studentRepo;
@Test
public void findAll() {
Iterable<Student> students = studentRepo.findAll();
assertTrue(students != null);
// assertTrue(size!=0);
}
@Test
public void findById() {
int iter = 0;
int match = 0;
Iterable<Student> students = studentRepo.findAll();
Student firstStudent = null;
if (students != null) {
for (Student student : students) {
if (iter == 0) {
firstStudent = student;
match++;
} else {
if (student.getId()==firstStudent.getId()) {
match++;
}
}
iter++;
}
if (iter != 0) {
// Student firstStudent=students.iterator().next();
if (firstStudent != null) {
// logger.info("findById :: 1st student name : " + firstStudent.getName() + " ; phone : " + firstStudent.getPhone());
int findByNameSizeDB = studentRepo.findById(firstStudent.getId()).size();
// logger.info("findById :: newStudent student name : " + firstStudent.getName() + " ; phone : " + firstStudent.getPhone());
//
// assertEquals(firstStudent.getId(), newStudent.getId());
// assertEquals(firstStudent.getName(), newStudent.getName());
assertEquals(match,findByNameSizeDB);
} else {
assertTrue(false);
}
} else {
logger.info("findById :: student list size 0");
}
}
}
@Test
public void findbyName() {
int iter = 0;
int match = 1;
Iterable<Student> students = studentRepo.findAll();
Student firstStudent = null;
if (students != null) {
for (Student student : students) {
if (iter == 0) {
firstStudent = student;
} else {
if (student.getName().compareTo(firstStudent.getName()) == 0) {
match++;
}
}
iter++;
}
if (iter != 0) {
// Student firstStudent=students.iterator().next();
if (firstStudent != null) {
// logger.info("findById :: 1st student name : " + firstStudent.getName() + " ; phone : " + firstStudent.getPhone());
int findByNameSizeDB = studentRepo.findByName(firstStudent.getName()).size();
// logger.info("findById :: newStudent student name : " + firstStudent.getName() + " ; phone : " + firstStudent.getPhone());
//
// assertEquals(firstStudent.getId(), newStudent.getId());
// assertEquals(firstStudent.getName(), newStudent.getName());
assertEquals(match,findByNameSizeDB);
} else {
assertTrue(false);
}
} else {
logger.info("findById :: student list size 0");
}
}
}
}
<file_sep>package com.priyam.spring.repository;/**
* Created by dni_tahniat on 23/1/2017.
*/
import com.priyam.spring.entity.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentRepo extends CrudRepository<Student,Integer>{
static final Logger logger = LoggerFactory.getLogger(StudentRepo.class);
public List<Student> findById(int id);
public List<Student> findByName(String name);
public List<Student> findByNameLike (String name);
@Query("select c from Student c where mod (id, 2) = 0")
public List<Student> findStudentsWithEvenID();
public List<Student> findByPhone(String phone);
}
|
a27f498378c8bab6782c5132c78373f4d3ececea
|
[
"Markdown",
"Java"
] | 6
|
Java
|
tahniat-ashraf/StudentCourseRegistration-SpringBoot-OracleDB
|
bd0a197e5ce526445a7272546450a3e47909ef25
|
34f2f12296ea49f6934c3160b7c7090365085dce
|
refs/heads/master
|
<repo_name>maleowy/CodeJamRunner<file_sep>/CodeJamRunner/Enums/ProblemEnum.cs
namespace CodeJamRunner.Enums
{
public enum ProblemEnum
{
A,
B,
C,
D,
E
}
}
<file_sep>/CodeJamRunner/Program.cs
using System;
using System.IO;
using CodeJamRunner.Enums;
namespace CodeJamRunner
{
class MainClass
{
public static void Main (string[] args)
{
string YEAR = "2017";
RoundEnum ROUND = RoundEnum.QualificationRound;
ProblemEnum PROBLEM = ProblemEnum.A;
FileTypeEnum FILE_TYPE = FileTypeEnum.Test;
int ATTEMPT = 0;
Run(YEAR, ROUND, PROBLEM, FILE_TYPE, ATTEMPT);
}
private static void Run(string year, RoundEnum round, ProblemEnum problem, FileTypeEnum fileType, int attempt)
{
Prepare(year, round, problem);
Type testCaseType = Type.GetType($"CodeJamRunner.CodeJam_{year}_{round}_{problem}");
ITestCase testCase = null;
try
{
testCase = (ITestCase) Activator.CreateInstance(testCaseType);
}
catch
{
Console.WriteLine("Show All Files and add generated folder to the Solution");
Console.ReadLine();
}
if (testCase != null)
{
new Problem(testCase)
{
FileType = fileType,
Attempt = attempt
}.Run();
}
}
private static void Prepare(string year, RoundEnum round, ProblemEnum problem)
{
var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, year, round.ToString(), problem.ToString());
dir = dir.Replace("\\bin\\Debug", "");
Directory.CreateDirectory(dir);
var filePath = Path.Combine(dir, $"CodeJam_{year}_{round}_{problem}.cs");
if (File.Exists(filePath))
return;
File.WriteAllText(filePath, @"using System;
using System.Collections.Generic;
namespace CodeJamRunner
{
public class CodeJam_" + year + "_" + round + "_" + problem + @" : ITestCase
{
public string GetTitle()
{
return """ + problem + @""";
}
public Func<string, int> LinesPerTestCase()
{
return x => 1;
}
public string Run(List<string> lines)
{
return """ + problem + @""";
}
}
}");
File.WriteAllText(Path.Combine(dir, "test.in"), @"3
1
2
3");
File.WriteAllText(Path.Combine(dir, "test.out"), @"Case #1: A
Case #2: A
Case #3: A");
}
}
}<file_sep>/CodeJamRunner/Divider.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace CodeJamRunner
{
public class Divider
{
public readonly string Path;
public Divider (string path)
{
if (!File.Exists (path))
{
throw new Exception ("File not found");
}
Path = path;
}
public List<string> Divide(Func<string, int> func)
{
int numberOfTestCases;
var list = new List<string> ();
using (StreamReader reader = new StreamReader(Path))
{
string firstLineOfFile = reader.ReadLine();
if (string.IsNullOrEmpty (firstLineOfFile) ||
firstLineOfFile.Equals (Environment.NewLine)) {
throw new Exception ("Test file empty");
}
numberOfTestCases = int.Parse(firstLineOfFile);
while (!reader.EndOfStream)
{
string first = reader.ReadLine ();
var subList = new List<string> { first };
int nr = func (first) - 1;
for (int i=0; i < nr; i++) {
subList.Add(reader.ReadLine ());
}
list.Add (string.Join(Environment.NewLine, subList));
}
}
if (numberOfTestCases != list.Count)
{
throw new Exception ("Number of tests mismatch");
}
return list;
}
}
}
<file_sep>/README.md
# CodeJamRunner
Test runner for Google Code Jam contest
<file_sep>/CodeJamRunner/Enums/FileTypeEnum.cs
namespace CodeJamRunner.Enums
{
public enum FileTypeEnum
{
Small,
Small1,
Small2,
Large,
SmallPractice,
SmallPractice1,
SmallPractice2,
LargePractice,
Test
}
}
<file_sep>/CodeJamRunner/Enums/RoundEnum.cs
namespace CodeJamRunner.Enums
{
public enum RoundEnum
{
QualificationRound,
Round1A,
Round1B,
Round1C,
Round2,
Round3
}
}
<file_sep>/CodeJamRunner/Problem.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CodeJamRunner.Enums;
namespace CodeJamRunner
{
public class Problem
{
public static readonly Dictionary<FileTypeEnum, string> FileTypes = new Dictionary<FileTypeEnum, string> {
{ FileTypeEnum.Small, "{0}-small-attempt{1}.in" },
{ FileTypeEnum.Small1, "{0}-small-1-attempt{1}.in" },
{ FileTypeEnum.Small2, "{0}-small-2-attempt{1}.in" },
{ FileTypeEnum.Large, "{0}-large.in" },
{ FileTypeEnum.SmallPractice, "{0}-small-practice.in" },
{ FileTypeEnum.SmallPractice1, "{0}-small-practice-1.in" },
{ FileTypeEnum.SmallPractice2, "{0}-small-practice-2.in" },
{ FileTypeEnum.LargePractice, "{0}-large-practice.in" },
{ FileTypeEnum.Test, "test.in" }
};
public FileTypeEnum FileType { get; set; }
public int Attempt { get; set; }
private readonly ITestCase _testCase;
private readonly string[] _newLines = { Environment.NewLine };
public Problem(ITestCase testCase)
{
_testCase = testCase;
}
public void Run()
{
Console.WriteLine(_testCase.GetTitle());
DateTime started = DateTime.Now;
Console.WriteLine("Started: " + started.ToString("hh:mm:ss"));
Process();
DateTime ended = DateTime.Now;
Console.WriteLine("Ended: " + ended.ToString("hh:mm:ss"));
TimeSpan total = ended.Subtract(started);
Console.WriteLine("Total: {0} minutes, {1} seconds, {2} milliseconds", total.Minutes, total.Seconds, total.Milliseconds);
Console.ReadLine();
}
private void Process()
{
string codeFile = GetCodeFileName();
string testFile = GetTestFileName();
string fn = Path.Combine(GetProblemDirectory(), testFile);
var divider = new Divider(fn);
List<string> testCases = divider.Divide(_testCase.LinesPerTestCase());
var ms = new MemoryStream();
ProcessReal(fn, testCases, ms);
ProcessTest(fn, ms);
CopyToDesktop(codeFile, testFile);
}
private void CopyToDesktop(string codeFile, string testFile)
{
var desktop = GetDesktopDictionary();
var problemDir = GetProblemDirectory();
if (!Directory.Exists(desktop))
{
Directory.CreateDirectory(desktop);
}
else
{
var di = new DirectoryInfo(desktop);
foreach (FileInfo file in di.GetFiles("*.cs"))
{
file.Delete();
}
foreach (FileInfo file in di.GetFiles("*.out"))
{
file.Delete();
}
}
File.Copy(Path.Combine(problemDir, codeFile), Path.Combine(desktop, codeFile), true);
testFile = testFile.Replace(".in", ".out");
File.Copy(Path.Combine(problemDir, testFile), Path.Combine(desktop, testFile), true);
}
private void ProcessReal(string fn, List<string> testCases, MemoryStream ms)
{
using (StreamWriter writer = new StreamWriter(FileType == FileTypeEnum.Test ? (Stream)ms : (Stream)new FileStream(fn.Replace(".in", ".out"), FileMode.Create)))
{
for (int i = 0; i < testCases.Count; i++)
{
DateTime now = DateTime.Now;
List<string> lines = testCases[i].Split(_newLines, StringSplitOptions.None).ToList();
string answer = $"Case #{i + 1}: {_testCase.Run(lines)}";
writer.WriteLine(answer);
var timeSpan = DateTime.Now.Subtract(now);
Console.WriteLine("{0} ({1} min, {2} s, {3} ms)", answer, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
}
}
}
private void ProcessTest(string fn, MemoryStream ms)
{
if (FileType != FileTypeEnum.Test)
return;
if (!File.Exists(fn.Replace(".in", ".out")))
{
throw new Exception("Output test file does not exists");
}
List<string> outMemoryList = Regex.Split(Encoding.Default.GetString(ms.ToArray()), @"Case ").Skip(1).ToList();
List<string> outFileList = Regex.Split(File.ReadAllText(fn.Replace(".in", ".out")), @"Case ").Skip(1).ToList();
if (!outFileList[outFileList.Count - 1].EndsWith(Environment.NewLine))
outFileList[outFileList.Count - 1] += Environment.NewLine;
bool correct = true;
Console.WriteLine("\n-----------------------\n");
for (int i = 0; i < outFileList.Count(); i++)
{
if (outMemoryList[i].Equals(outFileList[i]) == false)
{
Console.WriteLine("#{0} -wrong-> {1} -correct-> {2}", i + 1, outMemoryList[i].Substring(outMemoryList[i].IndexOf(':') + 1), outFileList[i].Substring(outFileList[i].IndexOf(':') + 1));
correct = false;
}
}
Console.WriteLine(correct ? "Test succeded!" : "Test failed!");
}
private string GetDesktopDictionary()
{
var dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var name = _testCase.GetType().Name;
return Path.Combine(dir, name[name.Length - 1].ToString());
}
private string GetProblemDirectory()
{
var fn = _testCase.GetType().Name.Replace("CodeJam_", "").Replace("_", "/");
var dir = AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", "/").Replace(@"/bin/Debug", "");
fn = string.Format(dir + fn);
return fn;
}
private string GetCodeFileName()
{
var name = _testCase.GetType().Name;
return name + ".cs";
}
private string GetTestFileName()
{
var name = _testCase.GetType().Name;
return string.Format(FileTypes[FileType], name[name.Length - 1], Attempt);
}
}
}
<file_sep>/CodeJamRunner/ITestCase.cs
using System;
using System.Collections.Generic;
namespace CodeJamRunner
{
public interface ITestCase
{
string GetTitle();
string Run(List<string> lines);
Func<string, int> LinesPerTestCase ();
}
}
|
45a951cd529aae7728a9d9e2f16603dbb2a6d27d
|
[
"Markdown",
"C#"
] | 8
|
C#
|
maleowy/CodeJamRunner
|
acfcd485202c2c5510aa3e79dd59319ae732dd77
|
66d393d1ef3d60e498f8d1badd62ae533ed04509
|
refs/heads/master
|
<file_sep>using NUnit.Framework;
using System.Dynamic;
using Lib.Extensions;
namespace LibTests.Extensions
{
[TestFixture]
public class ExpandoExtensionsTests
{
[Test]
public void HasProperty_should_return_true_if_object_has_property()
{
dynamic foo = new ExpandoObject();
foo.bar = "hello";
var result = ((ExpandoObject)foo).HasProperty("bar");
Assert.True(result);
}
[Test]
public void HasProperty_should_return_false_if_object_doesnt_have_property()
{
dynamic foo = new ExpandoObject();
foo.bar = "hello";
var result = ((ExpandoObject)foo).HasProperty("baz");
Assert.False(result);
}
[Test]
public void HasProperty_should_return_false_if_object_is_null()
{
var result = ((ExpandoObject)null).HasProperty("baz");
Assert.False(result);
}
[Test]
public void GetPropertyValue_should_return_property_value()
{
dynamic foo = new ExpandoObject();
foo.bar = "hello";
var result = ((ExpandoObject)foo).GetPropertyValue("bar");
Assert.That(result, Is.EqualTo("hello"));
}
[Test]
public void GetPropertyValue_should_return_null_if_property_doesnt_exist()
{
dynamic foo = new ExpandoObject();
foo.bar = "hello";
var result = ((ExpandoObject)foo).GetPropertyValue("baz");
Assert.That(result, Is.Null);
}
[Test]
public void GetPropertyValue_should_return_null_if_object_null()
{
var result = ((ExpandoObject)null).GetPropertyValue("bar");
Assert.That(result, Is.Null);
}
[Test]
public void Query_should_return_property_value()
{
dynamic foo = new ExpandoObject();
foo.bar = new ExpandoObject();
foo.bar.baz = "hello";
var result = ((ExpandoObject)foo).Query<string>("bar.baz");
Assert.That(result, Is.EqualTo("hello"));
}
[Test]
public void Query_should_return_null_if_property_doesnt_exist()
{
dynamic foo = new ExpandoObject();
foo.bar = new ExpandoObject();
foo.bar.baz = "hello";
var result = ((ExpandoObject)foo).Query<string>("bar.quux");
Assert.That(result, Is.Null);
}
[Test]
public void Query_should_return_null_if_it_cannot_traverse_expandos()
{
dynamic foo = new ExpandoObject();
foo.bar = new
{
baz = "hello"
};
var result = ((ExpandoObject)foo).Query<string>("bar.baz");
Assert.That(result, Is.Null);
}
[Test]
public void Query_should_return_null_if_object_null()
{
var result = ((ExpandoObject)null).Query<string>("bar.quux");
Assert.That(result, Is.Null);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace Lib.Extensions
{
public static class ModelStateExtensions
{
public static List<string> ToErrorList(this ModelStateDictionary modelState)
{
return modelState.Values.SelectMany(x => x.Errors).Select(y => y.ErrorMessage).ToList();
}
}
}<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using Lib.DataTypes;
namespace Lib.Extensions
{
public static class EnumerableExtensions
{
public static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, params IEnumerable<T>[] others)
{
var queues = new[] { first }.Concat(others).Select(x => new Queue<T>(x)).ToList();
while (queues.Any(x => x.Any()))
{
foreach (var queue in queues.Where(x => x.Any()))
{
yield return queue.Dequeue();
}
}
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static IEnumerable<TSource> MaxBy<TSource, TKey, TKey2>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TKey2> valueSelector)
{
return source.GroupBy(keySelector).Select(g => g.OrderByDescending(valueSelector).First());
}
public static Option<T> FirstOrNone<T>(this IEnumerable<T> list, Func<T,bool> predicate)
{
foreach (var item in list.Where(predicate))
{
return Option<T>.Some(item);
}
return Option<T>.None;
}
public static ListChangeSet<T> Diff<T>(this IEnumerable<T> list, IEnumerable<T> other, Func<T, object> identifierFunc = null)
{
var changeSet = new ListChangeSet<T>();
var otherList = other.ToList();
if (identifierFunc == null)
{
identifierFunc = x => x;
}
foreach (var item in list)
{
var identifier = identifierFunc(item);
var foundItem = otherList.FirstOrNone(x => identifierFunc(x).Equals(identifier));
if (foundItem.HasValue)
{
changeSet.Same.Add(item);
}
else
{
changeSet.Removed.Add(item);
}
}
changeSet.Added.AddRange(otherList.Where(x => !changeSet.Same.Contains(x)));
return changeSet;
}
}
}<file_sep>using System;
namespace Lib.Wrappers
{
public interface ITimeProvider
{
DateTime Now { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lib.Sql;
using NUnit.Framework;
namespace LibTests.Sql
{
[TestFixture]
public class SqlToolsTests
{
[Test]
public void GetSql_should_return_sql_text_for_command()
{
var command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spDoThing";
command.Parameters.Add(new SqlParameter { ParameterName = "@Foo", SqlDbType = SqlDbType.NVarChar, Value = "Hello" });
command.Parameters.Add(new SqlParameter { ParameterName = "@Bar", SqlDbType = SqlDbType.Int, Value = 123 });
command.Parameters.Add(new SqlParameter { ParameterName = "@Baz", SqlDbType = SqlDbType.Bit, Value = true });
command.Parameters.Add(new SqlParameter { ParameterName = "@Qux", SqlDbType = SqlDbType.DateTime, Value = "1/3/2016" });
var result = SqlTools.GetSql(command);
Assert.That(result, Is.EqualTo("exec spDoThing\n@Foo='Hello'\n@Bar=123\n@Baz=1\n@Qux='1/3/2016'"));
}
[Test]
public void GetSql_should_return_sql_text_for_command_with_output_params()
{
var command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spDoThing";
command.Parameters.Add(new SqlParameter { ParameterName = "@Foo", SqlDbType = SqlDbType.NVarChar, Direction = ParameterDirection.Output });
var result = SqlTools.GetSql(command);
Assert.That(result, Is.EqualTo("exec spDoThing\n@Foo=@Foo output"));
}
[Test]
public void GetSql_should_return_sql_text_for_command_with_inner_quotes()
{
var command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spDoThing";
command.Parameters.Add(new SqlParameter { ParameterName = "@Foo", SqlDbType = SqlDbType.NVarChar, Value = "Let's do this" });
var result = SqlTools.GetSql(command);
Assert.That(result, Is.EqualTo("exec spDoThing\n@Foo='Let''s do this'"));
}
[Test]
public void GetSql_should_return_sql_text_for_command_verbosely()
{
var command = new SqlCommand();
command.Connection = new SqlConnection("Initial Catalog=testdb;Data Source=localhost");
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spDoThing";
command.Parameters.Add(new SqlParameter { ParameterName = "@Foo", SqlDbType = SqlDbType.NVarChar, Value="Hello" });
var result = SqlTools.GetSql(command, true);
Assert.That(result, Is.EqualTo("--server: localhost\nuse testdb;\nexec spDoThing\n@Foo='Hello'"));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Web;
using Lib.Mvc;
using System.Web.Http.Controllers;
using System.Web.Http.ValueProviders;
namespace Lib.Mvc
{
public class FormValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(HttpActionContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var contentType = httpContext.Request.Content.Headers?.ContentType?.MediaType;
if (contentType != null && contentType == "application/x-www-form-urlencoded")
{
return new DictionaryValueProvider(AssembleDictionary(httpContext.Request.Content.ReadAsStringAsync().Result)) as IValueProvider;
}
return new DictionaryValueProvider(new Dictionary<string, object>()) as IValueProvider;
}
private Dictionary<string, object> AssembleDictionary(string form)
{
var keyvals = form.Split('&');
var dictionary = new Dictionary<string, object>();
foreach (var keyval in keyvals)
{
var keyvalSplit = keyval.Split('=');
var key = HttpUtility.UrlDecode(keyvalSplit[0]);
var value = HttpUtility.UrlDecode(keyvalSplit[1]);
if (dictionary.ContainsKey(key))
{
dictionary[key] += $",{value}";
}
else
{
dictionary.Add(key, value);
}
}
return dictionary;
}
}
}<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
namespace Lib.Helpers
{
public static class TypeHelper
{
public static bool IsDefault(object value)
{
if (value == null)
{
return true;
}
var type = value.GetType();
return type.IsValueType && Activator.CreateInstance(type).Equals(value);
}
public static List<Type> GetAllTypesInheritedFromType<T>()
{
var type = typeof(T);
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p)).ToList();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lib.Extensions;
using NUnit.Framework;
namespace LibTests.Extensions
{
[TestFixture]
public class TypeExtensions
{
[Test]
public void IsNullableType_should_return_true_if_nullable()
{
var result = typeof(int?).IsNullableType();
Assert.That(result, Is.True);
}
[Test]
public void IsNullableType_should_return_false_if_not_nullable()
{
var result = typeof(int).IsNullableType();
Assert.That(result, Is.False);
}
}
}
<file_sep>using System.Collections.Generic;
using Lib.Extensions;
using NUnit.Framework;
namespace LibTests.Extensions
{
[TestFixture]
public class DictionaryExtensions
{
[Test]
public void Pick_should_create_a_subdictionary()
{
var dict = new Dictionary<string, string>
{
{ "foo", "foo_value" },
{ "bar", "bar_value" },
{ "baz", "baz_value" }
};
var subDict = dict.Pick("foo", "baz");
Assert.That(subDict.Count, Is.EqualTo(2));
Assert.That(subDict["foo"], Is.EqualTo("foo_value"));
Assert.That(subDict["baz"], Is.EqualTo("baz_value"));
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using Lib.DataTypes;
namespace Lib.Extensions
{
public static class DictionaryExtensions
{
public static Option<T> GetByKeyCaseInvariant<T>(this IDictionary<string, T> dictionary, string key)
{
var invariantKey = dictionary.Keys.FirstOrDefault(k => k.ToLowerInvariant() == key.ToLowerInvariant());
if (invariantKey == null)
{
return Option<T>.None;
}
return Option<T>.Some(dictionary[invariantKey]);
}
public static Option<T> GetByKey<T>(this IDictionary<string, T> dictionary, string key)
{
if (dictionary.ContainsKey(key))
{
return Option<T>.Some(dictionary[key]);
}
return Option<T>.None;
}
public static Dictionary<string, T> Pick<T>(this IDictionary<string, T> dictionary, params string[] keys)
{
var subDictionary = new Dictionary<string, T>();
foreach (var key in keys)
{
dictionary.GetByKey(key).AndThen(x => subDictionary.Add(key, x));
}
return subDictionary;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lib.DataTypes;
namespace Lib.Extensions
{
public static class ResultExtensions
{
public static Option<T> ToOption<T>(this Result<T> result)
{
return result.HasException ? Option<T>.None : Option<T>.Some(result.ValueOrThrow);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Dynamic;
namespace Lib.Extensions
{
public static class ExpandoExtensions
{
public static bool HasProperty(this ExpandoObject source, string name)
{
return source != null && (source as IDictionary<string,object>).ContainsKey(name);
}
public static object GetPropertyValue(this ExpandoObject source, string name)
{
return source.HasProperty(name) ? (source as IDictionary<string, object>)[name] : null;
}
public static T Query<T>(this ExpandoObject source, string accessor)
{
var parts = accessor.Split('.');
object value = source;
foreach (var part in parts)
{
if (value is ExpandoObject)
{
var expandoValue = value as ExpandoObject;
if (!expandoValue.HasProperty(part))
{
return default(T);
}
value = expandoValue.GetPropertyValue(part);
}
else
{
return default(T);
}
}
return (T)value;
}
public static T ToClass<T>(this ExpandoObject expando)
{
var props = typeof(T).GetProperties();
var entity = Activator.CreateInstance<T>();
var dictionary = expando as IDictionary<string, object>;
foreach (var prop in props)
{
if (dictionary.ContainsKey(prop.Name) && dictionary[prop.Name].GetType() == prop.PropertyType)
{
prop.SetValue(entity, dictionary[prop.Name]);
}
}
return entity;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
namespace Lib.Mvc
{
public class DictionaryValueProvider : IValueProvider
{
private readonly IDictionary<string,object> _dictionary;
public DictionaryValueProvider(IDictionary<string, object> dictionary)
{
_dictionary = dictionary;
}
public object GetValue(object target)
{
return _dictionary[target.ToString()];
}
public void SetValue(object target, object value)
{
_dictionary[target.ToString()] = value;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib.Wrappers
{
public class DateTimeProvider
{
public DateTime Now => DateTime.Now;
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Lib.Helpers
{
public static class SqlHelper
{
public static string MakeVarList(object query)
{
var list = string.Empty;
foreach (var prop in query.GetType().GetProperties())
{
var value = prop.GetValue(query);
list += $"declare @{prop.Name} as {GetSqlType(prop.PropertyType)} = {GetSqlValue(value)};\n";
}
return list;
}
public static string MakeDebugQuery(string sqlQuery, object query)
{
var runnableQuery = string.Empty;
runnableQuery += MakeVarList(query);
runnableQuery += "\n\n";
runnableQuery += sqlQuery;
return runnableQuery;
}
private static string GetSqlType(Type t)
{
var typeMap = new Dictionary<Type, string> {
{ typeof(int), "int" },
{ typeof(string), "nvarchar(max)" },
{ typeof(bool), "bit" }
};
if (!t.IsPrimitive && t != typeof(string))
{
t = Nullable.GetUnderlyingType(t);
}
return typeMap[t];
}
public static string GetSqlValue(object value)
{
if (value == null)
{
return "null";
}
if (value is string || value is char)
{
return $"'{value}'";
}
if (value is DateTime)
{
var date = ((DateTime)value);
return $"'{date.ToString("yyyy-dd-MM HH:mm:ss")}'";
}
if (value is Enum)
{
return ((int)value).ToString();
}
return value.ToString();
}
}
}
<file_sep>using System;
namespace Lib.DataTypes
{
//Idea stolen from function languages to represent existence, can have value or none but not both, similar to F# Option.
//This helps us in instances like getting default(T) of a primative where the result is ambiguous without having to change type to
//nullable or accessing a dictionary where null and does not exist are different things.
public class Option<T>
{
private readonly T _value;
private Option() { }
private Option(T value)
{
HasValue = true;
_value = value;
}
public bool HasValue { get; } = false;
public bool IsNone => !HasValue;
public T ValueOrThrow
{
get
{
if (IsNone)
{
throw new Exception("You attempted to get an option value of None which is not allowed, please check the value before accessing.");
}
return _value;
}
}
public T ValueOrDefault(T defaultValue)
{
return IsNone ? defaultValue : ValueOrThrow;
}
public T ValueOrDefault()
{
return IsNone ? default(T) : ValueOrThrow;
}
public Option<TU> Map<TU>(Func<T, TU> func)
{
return IsNone ? Option<TU>.None : new Option<TU>(func(ValueOrThrow));
}
public Option<T> Filter(Func<T,bool> func)
{
if (IsNone)
{
return None;
}
return func(ValueOrThrow) ? Some(ValueOrThrow) : None;
}
public Option<T> AndThen(Action<T> func)
{
if (IsNone)
{
return None;
}
func(ValueOrThrow);
return new Option<T>(ValueOrThrow);
}
public Option<T> OrElse(Func<T> func)
{
return IsNone ? new Option<T>(func()) : new Option<T>(ValueOrThrow);
}
public static Option<T> None => new Option<T>();
public static Option<T> Some(T value) => new Option<T>(value);
public static Option<T> FromNullable(T value) => value == null ? None : Some(value);
}
}
<file_sep>using System;
using Lib.DataTypes;
using NUnit.Framework;
namespace LibTests.DataTypes
{
[TestFixture]
public class OptionTests
{
[Test]
public void Option_should_have_value_if_value()
{
var option = Option<int>.Some(1);
Assert.True(option.HasValue);
Assert.False(option.IsNone);
Assert.That(option.ValueOrThrow, Is.EqualTo(1));
}
[Test]
public void Option_should_have_none_if_none()
{
var option = Option<int>.None;
Assert.False(option.HasValue);
Assert.True(option.IsNone);
}
[Test]
public void Option_should_throw_if_none_and_accessed_value()
{
var option = Option<int>.None;
Assert.Throws<Exception>(() => { var x = option.ValueOrThrow; });
}
[Test]
public void Option_GetValueOrDefault_should_get_value_if_value()
{
var option = Option<int>.Some(1);
Assert.That(option.ValueOrDefault(0), Is.EqualTo(1));
}
[Test]
public void Option_GetValueOrDefault_should_get_default_if_none()
{
var option = Option<int>.None;
Assert.That(option.ValueOrDefault(0), Is.EqualTo(0));
}
[Test]
public void Option_Map_should_map_to_new_option_type()
{
var option = Option<int>.Some(5);
Assert.That(option.Map(x => x.ToString()).ValueOrThrow, Is.EqualTo("5"));
}
[Test]
public void Option_Filter_should_set_rejected_value_to_none()
{
var option = Option<int>.Some(7);
Assert.That(option.Filter(x => x > 10).HasValue, Is.False);
}
[Test]
public void Option_Filter_should_set_accepted_value_to_value()
{
var option = Option<int>.Some(11);
Assert.That(option.Filter(x => x > 10).HasValue, Is.True);
Assert.That(option.Filter(x => x > 10).ValueOrThrow, Is.EqualTo(11));
}
[Test]
public void Option_AndThen_should_run_delegate_if_value()
{
var option = Option<int>.Some(5);
var value = 0;
option.AndThen(x => value = x);
Assert.That(value, Is.EqualTo(5));
}
[Test]
public void Option_AndThen_should_not_run_delegate_if_none()
{
var option = Option<int>.None;
var value = 0;
option.AndThen(x => value = x);
Assert.That(value, Is.EqualTo(0));
}
[Test]
public void Option_OrElse_should_run_delegate_if_none()
{
var option = Option<int>.None;
var value = 0;
option.OrElse(() => value = 5);
Assert.That(value, Is.EqualTo(5));
}
[Test]
public void Option_OrElse_should_not_run_delegate_if_value()
{
var option = Option<int>.Some(7);
var value = 0;
option.OrElse(() => value = 5);
Assert.That(value, Is.EqualTo(0));
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
namespace Lib.DataTypes
{
//Represents a calculation, if successful has value, if unsuccessful has exception, never both
public class Result<T>
{
private Result(T valueOrThrow)
{
HasValue = true;
ValueOrThrow = valueOrThrow;
}
private Result(Exception exception)
{
HasValue = false;
Exception = exception;
}
public Exception Exception { get; }
public T ValueOrThrow { get; }
public bool HasValue { get; } = false;
public bool HasException => !HasValue;
public T ValueOrDefault(T defaultValue)
{
return HasValue ? ValueOrThrow : defaultValue;
}
public void TryThrow()
{
if (HasException)
{
throw Exception;
}
}
public Result<TU> Map<TU>(Func<T,TU> func)
{
return HasValue ? new Result<TU>(func(ValueOrThrow)) : new Result<TU>(Exception);
}
public Result<T> Filter(Func<T, bool> func, Func<T,Exception> exceptionMapFunc)
{
if (HasException)
{
return Error(Exception);
}
return func(ValueOrThrow) ? Ok(ValueOrThrow) : Error(exceptionMapFunc(ValueOrThrow));
}
public Result<T> AndThen(Action<T> func)
{
if (HasException)
{
return new Result<T>(Exception);
}
func(ValueOrThrow);
return new Result<T>(ValueOrThrow);
}
public Result<T> OrElse(Func<T> func)
{
return HasException ? new Result<T>(func()) : new Result<T>(ValueOrThrow);
}
public static Result<T> Try(Func<T> func)
{
Result<T> result;
try
{
result = new Result<T>(func());
}
catch (Exception ex)
{
result = new Result<T>(ex);
}
return result;
}
public static async Task<Result<T>> TryAsync(Func<Task<T>> func)
{
Result<T> result;
try
{
result = new Result<T>(await func());
}
catch (Exception ex)
{
result = new Result<T>(ex);
}
return result;
}
public static Result<T> Ok(T value){
return new Result<T>(value);
}
public static Result<T> Error(Exception exception)
{
return new Result<T>(exception);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Lib.Extensions
{
public static class ObjectExtensions
{
public static dynamic ToExpando(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
return expando as ExpandoObject;
}
public static T MapTo<T>(this object fromObject, string prefix, string[] requiredProps) where T : class, new()
{
var toObject = Activator.CreateInstance<T>();
var addressPropertyInfos = toObject.GetType().GetProperties();
var objectPropertyInfos = fromObject.GetType().GetProperties();
if (!objectPropertyInfos.Any(x => requiredProps.Contains(x.Name)))
{
return null;
}
foreach (var addressPropertyInfo in addressPropertyInfos)
{
var objectPropertyInfo = objectPropertyInfos.FirstOrDefault(x => x.Name == prefix + addressPropertyInfo.Name);
if (objectPropertyInfo != null)
{
addressPropertyInfo.SetValue(toObject, objectPropertyInfo.GetValue(fromObject));
}
}
return toObject;
}
public static List<T> ToList<T>(this object value)
{
return new List<T> { (T)value };
}
public static object GetPrefixedProperty<T>(this T entity, string propertyName, string prefix)
{
var property = typeof(T).GetProperties().FirstOrDefault(x => x.Name == prefix + propertyName);
return property?.GetValue(entity, null);
}
public static string ToJson(this object self)
{
return JsonConvert.SerializeObject(self);
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
namespace Lib.Helpers
{
public class MimeHelper
{
private static readonly Dictionary<string, string> MimeTypeMappings = new Dictionary<string, string>
{
{ "gif", "image/gif" },
{ "jpeg", "image/jpeg" },
{ "jpg", "image/jpeg" },
{ "png", "image/png" }
};
public string GetMimeType(string filename)
{
if (string.IsNullOrEmpty(filename))
{
return string.Empty;
}
string value;
var extension = filename.Split('.').Last();
return MimeTypeMappings.TryGetValue(extension, out value) ? value : string.Empty;
}
public string GetMimeType(byte[] contents)
{
if (IsGif(contents))
{
return "image/gif";
}
if (IsJpg(contents))
{
return "image/jpeg";
}
if (IsPng(contents))
{
return "image/png";
}
return string.Empty;
}
private static bool IsGif(byte[] contents)
{
return contents[0] == 0x47 && contents[1] == 0x49 && contents[2] == 0x46;
}
private static bool IsJpg(byte[] contents)
{
return contents[0] == 0xFF && contents[1] == 0xD8;
}
private static bool IsPng(byte[] contents)
{
return contents[0] == 0x89 && contents[1] == 0x50 && contents[2] == 0x4E && contents[3] == 0x47;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Web;
namespace Lib.Extensions
{
public static class IntExtensions
{
public static T ToEnum<T>(this int self) where T : struct
{
return ParseEnum(self, default(T));
}
public static T ParseEnum<T>(int input, T defaultValue, bool throwException = false) where T : struct
{
T returnEnum = defaultValue;
if (!typeof(T).IsEnum)
{
throw new InvalidOperationException("Invalid Enum Type. " + typeof(T).ToString() + " must be an Enum");
}
if (Enum.IsDefined(typeof(T), input))
{
returnEnum = (T)Enum.ToObject(typeof(T), input);
}
else
{
if (throwException)
{
throw new InvalidOperationException("Invalid Cast");
}
}
return returnEnum;
}
public static bool ToBool(this int value)
{
return value == 0;
}
public static int Bucket(int value, params int[] buckets)
{
for (var i = 0; i < buckets.Length; i++)
{
if ((i == 0 && value < buckets[i]) || (i > 0 && value >= buckets[i - 1] && value < buckets[i]))
{
return i;
}
}
return buckets.Length;
}
}
}<file_sep>using System;
using Lib.DataTypes;
using NUnit.Framework;
namespace LibTests.DataTypes
{
[TestFixture]
public class ResultTests
{
[Test]
public void Result_has_value_should_be_true_if_has_value()
{
var result = Result<int>.Ok(1);
Assert.That(result.HasValue, Is.True);
}
[Test]
public void Result_has_value_should_be_false_if_no_value()
{
var result = Result<int>.Error(new Exception());
Assert.That(result.HasValue, Is.False);
}
[Test]
public void Result_has_exception_should_be_true_if_has_exception()
{
var result = Result<int>.Error(new Exception());
Assert.That(result.HasException, Is.True);
}
[Test]
public void Result_has_exception_should_be_false_if_no_exception()
{
var result = Result<int>.Ok(1);
Assert.That(result.HasException, Is.False);
}
[Test]
public void ResultTry_should_return_valued_result_when_success()
{
var result = Result<int>.Try(() => 2);
Assert.That(result.HasValue, Is.True);
Assert.That(result.HasException, Is.False);
Assert.That(result.ValueOrThrow, Is.EqualTo(2));
}
[Test]
public void ResultTry_should_return_exception_result_when_failed()
{
var x = 1;
var result = Result<int>.Try(() => 100 / (1 - x));
Assert.That(result.HasValue, Is.False);
Assert.That(result.HasException, Is.True);
Assert.That(result.Exception, Is.TypeOf<DivideByZeroException>());
}
[Test]
public void ResultTryThrow_should_throw_if_exception()
{
var result = Result<int>.Error(new Exception("the error"));
Assert.Throws<Exception>(() => result.TryThrow());
}
[Test]
public void ResultTryThrow_should_not_throw_if_not_exception()
{
var result = Result<int>.Ok(5);
Assert.DoesNotThrow(() => result.TryThrow());
}
}
}
<file_sep>using System.Collections.Generic;
using Lib.Extensions;
using NUnit.Framework;
namespace LibTests.Extensions
{
[TestFixture]
class EnumerableExtensions
{
[Test]
public void FirstOrNone_should_get_match()
{
var listA = new List<int> { 1, 2, 3, 4 };
var result = listA.FirstOrNone(x => x == 2);
Assert.That(result.ValueOrThrow, Is.EqualTo(2));
}
[Test]
public void FirstOrNone_should_get_none_if_no_match()
{
var listA = new List<int> { 1, 2, 3, 4 };
var result = listA.FirstOrNone(x => x == 5);
Assert.That(result.IsNone, Is.True);
}
[Test]
public void Diff_should_get_same_elements()
{
var listA = new List<int> { 1, 2, 3, 4 };
var listB = new List<int> { 1, 2, 3, 4 };
var result = listA.Diff(listB);
Assert.AreEqual(result.Same.Count, 4);
Assert.AreEqual(result.Same[0], listA[0]);
Assert.AreEqual(result.Same[1], listA[1]);
Assert.AreEqual(result.Same[2], listA[2]);
Assert.AreEqual(result.Same[3], listA[3]);
Assert.AreEqual(result.Removed.Count, 0);
Assert.AreEqual(result.Added.Count, 0);
}
[Test]
public void Diff_should_get_removed_elements()
{
var listA = new List<int> { 1, 2, 3, 4, 5, 6 };
var listB = new List<int> { 1, 2, 3, 4 };
var result = listA.Diff(listB);
Assert.AreEqual(result.Same.Count, 4);
Assert.AreEqual(result.Same[0], listA[0]);
Assert.AreEqual(result.Same[1], listA[1]);
Assert.AreEqual(result.Same[2], listA[2]);
Assert.AreEqual(result.Same[3], listA[3]);
Assert.AreEqual(result.Removed.Count, 2);
Assert.AreEqual(result.Removed[0], listA[4]);
Assert.AreEqual(result.Removed[1], listA[5]);
Assert.AreEqual(result.Added.Count, 0);
}
[Test]
public void Diff_should_get_added_elements()
{
var listA = new List<int> { 1, 2, 3, 4, 5, 6 };
var listB = new List<int> { 1, 2, 3, 4, 7, 8 };
var result = listA.Diff(listB);
Assert.AreEqual(result.Same.Count, 4);
Assert.AreEqual(result.Same[0], listA[0]);
Assert.AreEqual(result.Same[1], listA[1]);
Assert.AreEqual(result.Same[2], listA[2]);
Assert.AreEqual(result.Same[3], listA[3]);
Assert.AreEqual(result.Removed.Count, 2);
Assert.AreEqual(result.Removed[0], listA[4]);
Assert.AreEqual(result.Removed[1], listA[5]);
Assert.AreEqual(result.Added.Count, 2);
Assert.AreEqual(result.Added[0], listB[4]);
Assert.AreEqual(result.Added[1], listB[5]);
}
}
}
<file_sep>using System;
using Lib.DataTypes;
namespace Lib.Extensions
{
public static class OptionExtensions
{
public static Result<T> ToResult<T>(this Option<T> option, Func<Exception> mapNone)
{
return option.IsNone ? Result<T>.Error(mapNone()) : Result<T>.Ok(option.ValueOrThrow);
}
}
}
<file_sep>using System.Collections.Generic;
namespace Lib.DataTypes
{
public class ListChangeSet<T>
{
public ListChangeSet()
{
Added = new List<T>();
Removed = new List<T>();
Same = new List<T>();
}
public List<T> Added { get; set; }
public List<T> Removed { get; set; }
public List<T> Same { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib.DataTypes
{
public class Either<TL, TR>
{
private TL _left;
private TR _right;
public bool IsRight = true;
private Either() { }
public static Either<TL,TR> Left(TL value)
{
var either = new Either<TL, TR>
{
_left = value,
IsRight = false
};
return either;
}
public static Either<TL,TR> Right(TR value)
{
var either = new Either<TL, TR>
{
_right = value,
IsRight = true
};
return either;
}
public TL LeftOrThrow {
get
{
if (IsRight)
{
throw new Exception("Cannot access Left of Either with a Right. Please check before accessing");
}
return _left;
} }
public TR RightOrThrow
{
get
{
if (IsRight)
{
throw new Exception("Cannot access Right of Either with a Left. Please check before accessing");
}
return _right;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.WebPages.Html;
namespace Lib.Extensions
{
public static class HtmlHelperExtensions
{
public static HtmlString OptionList(this HtmlHelper helper, Dictionary<string, string> keyValues)
{
var stringBuilder = new StringBuilder();
foreach (var keyValue in keyValues)
{
stringBuilder.AppendFormat("<option key={0}>{1}</option>", keyValue.Key, keyValue.Value);
}
return new HtmlString(stringBuilder.ToString());
}
public static HtmlString OptionList(this HtmlHelper helper, List<string> values)
{
var stringBuilder = new StringBuilder();
foreach (var value in values)
{
stringBuilder.AppendFormat("<option key={0}>{0}</option>", value);
}
return new HtmlString(stringBuilder.ToString());
}
public static HtmlString List(this HtmlHelper helper, List<string> values)
{
if (values == null)
{
return new HtmlString(string.Empty);
}
var stringBuilder = new StringBuilder();
foreach (var value in values)
{
stringBuilder.AppendFormat("<li>{0}</li>", value);
}
return new HtmlString(stringBuilder.ToString());
}
public static HtmlString ReturnUrl(this HtmlHelper helper, string url){
if (string.IsNullOrEmpty(url))
{
return new HtmlString(string.Empty);
}
var keyValString = string.Format("{0}={1}", "return-url", HttpUtility.UrlEncode(url));
return new HtmlString(keyValString);
}
public static HtmlString ToggleDisplay(this HtmlHelper helper, bool shouldShow)
{
return shouldShow ? new HtmlString("style=\"display: block;\"") : new HtmlString(string.Empty);
}
public static HtmlString ToggleDisabled(this HtmlHelper helper, bool disabled)
{
return disabled ? new HtmlString("disabled") : new HtmlString(string.Empty);
}
public static HtmlString ConditionalHtml(this HtmlHelper helper, object conditionValue, string html){
if (conditionValue == null)
{
return new HtmlString(string.Empty);
}
if (conditionValue is bool && (bool)conditionValue == false)
{
return new HtmlString(string.Empty);
}
return new HtmlString(html);
}
}
}<file_sep>using System.Globalization;
using System.Text.RegularExpressions;
namespace Lib.Extensions
{
public static class StringExtensions
{
public static int? AsIntOrDefault(this string str)
{
int result;
if (!int.TryParse(str, out result))
{
return null;
}
return result;
}
public static string[] SplitCamelCase(string source)
{
return Regex.Split(source, @"(?<!^)(?=[A-Z])");
}
public static string CondenseSpaces(this string text)
{
return Regex.Replace(text, "\\s{2,}", " ");
}
public static string ToKebabFormat(this string text)
{
return text.CondenseSpaces().Replace(" ", "-").ToLower();
}
public static string ToTitleCaseFormat(this string text)
{
var textInfo = new CultureInfo("en-US", false).TextInfo;
text = textInfo.ToTitleCase(text);
return text.CondenseSpaces().Replace(" ", string.Empty);
}
public static string NormalizeBreaks(this string text)
{
return text.Replace("\r\n", "\n");
}
public static string ToSingleLine(this string text)
{
return NormalizeBreaks(text).Replace("\n", " ").CondenseSpaces();
}
}
}<file_sep>using System;
namespace Lib.Extensions
{
public static class TypeExtensions
{
public static bool IsNullableType(this Type type)
{
if (type.IsGenericType)
{
return type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
return false;
}
}
}
<file_sep>using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace Lib.Sql
{
public static class SqlWriter
{
public static string GetSql(SqlCommand command, bool isVerbose = false)
{
var sql = string.Empty;
if (isVerbose)
{
sql += $"--server: {command.Connection.DataSource}\n";
sql += $"use {command.Connection.Database};\n";
}
if (command.CommandType == CommandType.StoredProcedure)
{
sql += $"exec {command.CommandText}\n";
sql = command.Parameters.Cast<SqlParameter>().Aggregate(sql, (current, param) => current + FormatSqlParamExpression(param) + ",\n");
}
return sql.Trim('\n');
}
public static string FormatSqlParamExpression(SqlParameter sqlParameter)
{
var paramBuilder = new StringBuilder();
if (sqlParameter.Direction == ParameterDirection.Output)
{
paramBuilder.Append($"{sqlParameter.ParameterName}={sqlParameter.ParameterName} output");
}
else
{
paramBuilder.Append($"{sqlParameter.ParameterName}={FormatSqlParamValue(sqlParameter)}");
}
return paramBuilder.ToString();
}
public static string FormatSqlParamValue(SqlParameter sqlParameter)
{
if (sqlParameter.Value == null)
{
return "NULL";
}
switch (sqlParameter.SqlDbType)
{
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
case SqlDbType.DateTime:
return $"'{sqlParameter.Value.ToString().Replace("'", "''")}'";
case SqlDbType.Bit:
return ((bool)sqlParameter.Value) ? "1" : "0";
default:
return sqlParameter.Value.ToString().Replace("'", "''");
}
}
}
}
|
7267df3974fbf79e7f6bbcab5cc6c985903be630
|
[
"C#"
] | 30
|
C#
|
Somnid/cs-lib
|
17a36bd6f20f50c8d156cb20c744348459f4f915
|
e697559b4b326ac32b2a785d9602d9bd58d3a331
|
refs/heads/master
|
<file_sep>#!/bin/bash
# mp's todo checklist
# Run ./todo.sh to find your unfinished business!
# It basically just greps all the .c, .h, and makefile files in the current
# the directory it's in for the phrase "todo" and formats the output nicely.
# (as per the frankly disturbing amount of regex used)
echo -e "\e[1;33m=========== Assignment 3 : TODO ================\e[0m"
grep -in --color=always todo *.c *.h makefile |
sed -E 's/\x1b\[K:\x1b\[m\x1b\[K +/:\x1b\[m\x1b\[K/g' |
sed 's/\x1b\[m\x1b\[K\x1b\[36m\x1b\[K:\x1b\[m\x1b\[K/\x1b\[m\x1b\[K\x1b\[36m:\x1b\[m\x1b\[K/g' |
sed 's/\x1b\[m\x1b\[K\x1b\[36m:\x1b\[m\x1b\[K\([^\x1b\[m\x1b\[K\x1b\[32m\x1b\[K]\)/\x1b\[m\x1b\[K\x1b\[36m:\x1b\[m\x1b\[K\t\1/g'
echo -e "\e[1;33m================================================"
echo -e "\e[0m"
|
d1db15c159b92571b229d162bec38f89ecce129b
|
[
"Shell"
] | 1
|
Shell
|
mpowelltech/CSSE2310
|
6521c9a6885d808f2552c7784eb3b688c2b98425
|
7ead8511604c6e18ba9cc80448aaa6a54cd2b45f
|
refs/heads/master
|
<file_sep><?php
session_start();
$email=$_POST["email"];
$password=$_POST["pass"];
$mysqli=new mysqli("localhost","shashank","shasha2777","web");
$sql="SELECT * FROM signup WHERE email='$email' AND password='$password'";
$result=mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if(!strcmp($row['password'],$password))
{
$new=$row['password'];
$_SESSION["username"] = $_POST["email"];
echo "<script type='text/javascript'>alert('Succesfully LoggedIn');</script>";
}
else {
echo "<script type='text/javascript'>alert('Invalid Credentials');</script>";
}
}
} else {
echo "<script type='text/javascript'>alert('Invalid Credentials');</script>";
}
/*
if ($mysqli->query($sql) === TRUE) {
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}*/
$mysqli->close();
?>
<html>
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css">
<link href="css/bootstrap.css" rel="stylesheet" />
<link href="css/bootstrap-theme.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Boogaloo" rel="stylesheet" type="text/css">
<link rel="icon" href="logo.png" type="image/x-icon"/>
<head>
<title>Home Page</title>
<style>
body
{
}
.block
{
background-color:#00264d;
opacity:0.8;
font-family:Boogaloo;
font-size:18px;
padding-top:5px;
padding-bottom:10px;
padding-left:40px;
margin-top: 10px;
margin-bottom: 10px;
}
.mb
{
background-color:#ffffff;
opacity:0.65;
font-family:Book Antiqua;
font-size:18px;
top:75px;
bottom:100px;
position: absolute;
width: 60%;
border-radius: 10px;
margin-left: 260px;
padding-top: 60px;
padding-bottom: 20px;
padding-left: 50px;
padding-right: 50px;
height: 80%;
}
.head
{
color: #00e6e6;
font-size:45px;
margin-left:25px;
font-family:Boogaloo;
float:left;
padding-top:10px;
}
ul {
position: relative;
list-style-type: none;
margin:0;
padding:0;
overflow: hidden;
background-color:#00264d;
opacity: 1;
}
li {
float: right;
}
li a {
display: block;
color: #00e6e6;
font-family: Boogaloo;
text-align: center;
padding: 5px 10px;
text-decoration: none;
font-size:30px;
}
li a:hover {
background-color:#55ACEE;
padding-left:25px;
padding-right:25px;
transition: 0.5s;
box-shadow:3px 2px lightblue;
}
.c1
{
background-color:#00264d;
padding-top: 3px;
padding-bottom:15px;
margin-bottom: 0px;
font-family:Boogaloo;
opacity: 0.9;
}
.footer {
right: 0;
bottom: 0;
left: 0;
padding: 0.5rem;
position: fixed;
}
.bgimg-1, .bgimg-2, .bgimg-3, .bgimg-4, .bgimg5 {
position: relative;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
.bgimg-1 {
background-image: url("giphy (1).gif");
opacity:1;
height: 100%;
}
.bgimg-2 {
background-image: url("Shooting.png");
height: 100%;
}
.bgimg-3 {
background-image: url("clashofclans.jpg");
height: 100%;
}
.bgimg-4 {
background-image: url("plvszom.jpeg");
height: 100%;
}
.bgimg-5 {
background-image: url("letsplay.jpeg");
height: 100%;
}
.caption {
position: absolute;
left: 0;
top: 35%;
width: 100%;
text-align: center;
color: #000;
}
</style>
</head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<ul>
<li class="head"><a href="home.html" id="anchor"><span id="game">BUZZGAMES!</span></a></li>
<!--
<li style="float:left;padding-left:5px"><img src="logo.png" alt="weblogo" height="75px" width="75px"></li>
-->
<li style="padding-top:15px"><a href="login_final.html" id="sign"><span id="signup">Login/SignUp</span></a></li>
<li style="padding-top:15px"><a href="about_page.html">About</a></li>
<li style="padding-top:15px"><a href="contact.html">Contact</a></li>
<li style="padding-top:15px"><a href="categories_page.html">Categories</a></li>
<li style="padding-top:15px;padding-left:50px"><a href="home.html">Home</a></li>
</ul>
<div class="bgimg-1">
<div class="caption">
<span style="font-family:Courier New;color:#ffff33;font-size:90px;"><b>WELCOME TO BUZZGAMES!</b></span>
<br>
<span style="font-family:Courier New;color:#ff3300;font-size:60px;padding-top: 20px;"><b>Go Game Or Go Home</b> </span>
<br>
</div>
</div>
<div class="bgimg-2">
<div class="mb" style="font-family:Lucida Console;color:#77773c;font-size: 40px; opacity: 0.79;margin-top:20px;height: 70%;">
Shooty-bang-bang games are fun and all, but what other genres are out there?
<br>
<br>
<b>Check out our all-time favourite games.</b>
</div>
</div>
<div class="bgimg-3">
<div class="mb" style="color:#ff9933;font-size: 45px; opacity: 0.86;padding-top:30px;height: 50%;margin-top: 70px;font-family:Lucida Console;">
Inspired by ancient Gods, Played By Modern Heroes! <br>
Check out our newest <span style="font-family: Palatino Linotype;color: #ff6600;">Strategy Games! </span>
</div>
</div>
<div class="bgimg-4">
<div class="mb" style="font-family:Lucida Console;color: #ff8000;font-size: 40px; opacity: 0.79;margin-top:20px;height: 35%; padding-top: 85px;text-align: center;">
<a href="categories_page.html">Click here to FIND MORE!</a>
</div>
<div class="mb" style="font-family:Lucida Console;color:black;font-size: 20px;opacity:0.87;margin-top:400px;height: 25%; padding-top: 30px;padding-bottom:10px;padding-left:20px;width: 40%;left: 40%;background-color: #ffcc00;text-align: center;">
Scroll down to see what the creators have to say!
<br>
To know more view our <a href="about_page.html"><span style="color:red;">About Page</span></a>
<br>
Need help? You can contact us <a href="contact.html"><span style="color:red;">here</span></a>
</div>
</div>
<div class="bgimg-1">
<div class="mb" style="padding-top: 20px;padding-bottom: 20px;">
Greetings Fellow Gamer!<br>
Welcome to Buzz Games!<br><br>
Buzz Games is an online website for games and game reviews.
It showcases the best games in the hottest categories,making this a gamer's paradise.<br><br>
Categories range from Action,Adventure,Sport and Multiplayer to Role Playing and Educational games.<br>
These categories provide a wide range of games,each providing a different experience,to give the user a satisfying gaming session.<br><br>
Apart from serving as a portal for these games,users have the option of reviewing the games they have played,to display their personal feedback and advice.
This can be very helpful for newbie gamers who are looking to get the best gaming experience they can,without the hassles of google searches and unnecessary browsing.<br><br>
Buzz Games is a one stop destination for the gaming enthusiast,and the gaming newbie alike.<br>
We hope you like the website and what it has to offer.<br>
Happy Gaming!<br>
-Team Buzz Games
</div>
</div>
<?php
echo "string<br>";
if(isset($_SESSION["username"]))
{
echo "<script>var g=document.querySelector(\"#game\");";
echo "var sign=document.querySelector(\"#sign\");";
echo "sign.setAttribute(\"href\",\"logout.html\");";
echo "var g1=document.querySelector(\"#anchor\");";
echo "g1.innerHTML = \"Signout\";";
echo "g1.setAttribute(\"href\",\"logout.html\");</script>";
echo "<script>var k=document.querySelector(\"#signup\");";
echo "k.innerHTML = \"$_SESSION[username]\";</script>";
}
echo "not if ";
?>
<div class="c1 footer" style="margin-top:9%">
<b style="margin-bottom:25px;color:#00e6e6;font-size: 10px;font-family:Boogaloo;">2017 © BUZZGAMES, All Rights Reserved.</b>
</div>
</body>
</html>
<file_sep># web
3rd sem webtech project
<file_sep><html>
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Boogaloo" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css">
<head>
<title>signup</title>
<style>
body
{
background-image:url('background_nebula.jpg');
}
.c1
{
background-color:#00264d;
margin:5px;
}
.head
{
color: #00e6e6;
font-size:45px;
margin-left:25px;
font-family:Boogaloo;
float:left;
padding-top:10px;
}
ul {
position: relative;
list-style-type: none;
margin:0;
padding:0;
overflow: hidden;
background-color:#00264d;
opacity: 0.8;
}
li {
float: right;
}
li a {
display: block;
color: #00e6e6;
font-family: Boogaloo;
text-align: center;
padding: 5px 10px;
text-decoration: none;
font-size:30px;
}
li a:hover {
background-color:#55ACEE;
padding-left:25px;
padding-right:25px;
transition: 0.5s;
box-shadow:3px 2px lightblue;
}
.c1
{
background-color:#00264d;
padding-top: 3px;
padding-bottom: 15px;
margin-bottom: 5px;
font-family:Boogaloo;
opacity: 0.9;
}
.footer {
right: 0;
bottom: 0;
left: 0;
padding: 0.5rem;
}
</style>
<?php
$username=$_POST["username"];
$pass=$_POST["password"];
$re=$_POST["repass"];
$email=$_POST["email"];
$dob=$_POST["dob"];
//print $username
//echo $pass;
$mysqli=new mysqli("localhost","shashank","shasha2777","web");
$sql="INSERT INTO signup VALUES('$username','$pass','$email','$dob')";
if ($mysqli->query($sql) === TRUE) {
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
</head>
<body>
<ul>
<li class="head"><a href="home.html">BUZZGAMES!</a></li>
<li style="padding-top:15px"><a href="login_final.html">Login/SignUp</a></li>
<li style="padding-top:15px"><a href="about_page.html">About</a></li>
<li style="padding-top:15px"><a href="contact.html">Contact</a></li>
<li style="padding-top:15px"><a href="categories_page.html">Categories</a></li>
<li style="padding-top:15px;padding-left:50px"><a href="home.html">Home</a></li>
</ul>
<h1 align="center" style="font-family:Boogaloo;color:#66ff66;font-size:40px;padding-top:80px;">Successfully Registered</h1>
<p style="font-family:Boogaloo;color:#ff7733;font-size:30px;padding-left:70px;padding-right:70px;" align="center" >Loogin to access the account
</p>
<div class="c1 footer" style="margin-top:31%">
<b style="margin-bottom:25px;color:#00e6e6;font-size:10px;font-family:Boogaloo;">2017 © BUZZGAMES, All Rights Reserved.</b>
</div>
</body>
</html>
<file_sep># Buzzgames
A gaming website
<file_sep><?php
$mysqli=new mysqli("localhost","shashank","shasha2777","web");
$email=$_POST["email"];
$dob=$_POST["dob"];
$sql="SELECT * FROM signup WHERE email='$email' AND dob='$dob'";
$result=mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if(!strcmp($row['dob'],$dob))
{
$new=$row['password'];
echo "<script type='text/javascript'>alert('Your Password is:$new');</script>";
}
else {
echo "<script type='text/javascript'>alert('Invalid Credentials');</script>";
}
}
} else {
echo "<script type='text/javascript'>alert('Invalid Credentials');</script>";
}
/*
if ($mysqli->query($sql) === TRUE) {
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}*/
$mysqli->close();
?><html>
<head>
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Boogaloo" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css">
<title>Login Page</title>
<style>
body
{
background-image: url('background_nebula.jpg');
}
.c1
{
background-color:#00264d;
padding-top: 3px;
padding-bottom: 15px;
margin-bottom: 5px;
font-family:Boogaloo;
opacity: 0.9;
}
.head
{
color: #00e6e6;
font-size:45px;
margin-left:25px;
font-family:Boogaloo;
float:left;
padding-top:10px;
}
ul {
position: relative;
list-style-type: none;
margin:0;
padding:0;
overflow: hidden;
background-color:#00264d;
opacity: 0.8;
}
li {
float: right;
}
li a {
display: block;
color: #00e6e6;
font-family: Boogaloo;
text-align: center;
padding: 5px 10px;
text-decoration: none;
font-size:30px;
}
li a:hover {
background-color:#55ACEE;
padding-left:25px;
padding-right:25px;
transition: 0.5s;
box-shadow:3px 2px lightblue;
}
.login_block
{
color:#00e6e6;
background-color:#00274d;
margin-right: 65px;
padding-left: 35px;
padding-bottom: 30px;
padding-top: 2px;
opacity: 0.6;
margin-bottom: : 0px;
border-radius: 45px;
margin-top: -10px;
}
.c3
{
margin-left:40px;
}
.footer {
right: 0;
bottom: 0;
left: 0;
padding: 0.5rem;
}
.vl {
border-left: 1px solid green;
height: 500px;
}
</style>
</head>
<body>
<ul>
<li class="head"><a href="home.html">BUZZGAMES!</a></li>
<!--
<li style="float:left;padding-left:5px"><img src="logo.png" alt="weblogo" height="75px" width="75px"></li>
-->
<li style="padding-top:15px"><a href="login_final.html">Login/SignUp</a></li>
<li style="padding-top:15px"><a href="about_page.html">About</a></li>
<li style="padding-top:15px"><a href="contact.html">Contact</a></li>
<li style="padding-top:15px"><a href="categories_page.html">Categories</a></li>
<li style="padding-top:15px;padding-left:50px"><a href="home.html">Home</a></li>
</ul>
<br>
<br>
<div class="row">
<div class="col-md-8">
<div class="c3">
<img src="logo.png" alt="buzzgames-logo" height="435px" width="635px">
</div>
</div>
<div class="col-md-4">
<div class="login_block" style="margin-top:10%">
<h2 style="font-family:Boogaloo;margin-left:15%;padding-top:10px"><b>Password Recovery</b></h2>
<br>
<form action="forgot.php" method="post">
<label style="font-family:Boogaloo;font-size:20px">Email:<br>
<div class="col-xs-18">
<input type="text" name="email" placeholder="Email" name="email" color="black" class="form-control col-xs-6" required></label><br><br>
</div>
<label style="font-family:Boogaloo;font-size:20px">DOB:<br>
<div class="col-xs-18">
<input type="date" placeholder="DOB" name="dob" class="form-control" required></label>
</div>
<br>
<input type="submit" class="btn btn-info btn-block" style="border-radius:10px;font-family:Boogaloo;padding:10px;margin-left:55px"><br>
</form>
</div>
</div>
</div>
<br><br>
<div class="c1 footer" style="margin-top:9%">
<b style="margin-bottom:25px;color:#00e6e6;font-size: 10px;font-family:Boogaloo;">2017 © BUZZGAMES, All Rights Reserved.</b>
</div>
</body>
</html>
|
4d797fca486e7a1dd5364f79a4251b976b6a364d
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
ShashankBongale/Buzzgames
|
6302561f1351a98ffb9fa0af1e47ebf21252ab4f
|
e10e4be428e105a22661e237a96e95b97e1b28e8
|
refs/heads/master
|
<file_sep>package com.james.jettydemo;
import org.eclipse.jetty.server.Server;
public class SimplestServer {
private static void startServer(){
Server server = new Server(8080);
server.setHandler(new HelloHandler());
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
startServer();
}
}
|
4625cc437971acabde6a86efe630e85efd0ba23d
|
[
"Java"
] | 1
|
Java
|
jameszkw/loadbalancer
|
f9912de2adf550abcb76da1950dbc175d2dfdc78
|
5934a525aba5e49b33eef214f808f6544d3186de
|
refs/heads/master
|
<repo_name>matuszed/Atlas<file_sep>/Atlas.py
import json
import time
import time,hmac,base64,hashlib,urllib,urllib2,json
from hashlib import sha256
from decimal import Decimal
import datetime
import sys
import os
import httplib
import requests
#Adapted from Gox Class
class AtlasClient:
timeout = 15
tryout = 0
def __init__(self, key=''):
self.key = key
self.time = {'init': time.time(), 'req': time.time()}
self.reqs = {'max': 10, 'window': 10, 'curr': 0}
self.base = 'https://atlasats.hk/'
def throttle(self):
# check that in a given time window (10 seconds),
# no more than a maximum number of requests (10)
# have been sent, otherwise sleep for a bit
diff = time.time() - self.time['req']
if diff > self.reqs['window']:
self.reqs['curr'] = 0
self.time['req'] = time.time()
self.reqs['curr'] += 1
if self.reqs['curr'] > self.reqs['max']:
print 'Request limit reached...'
time.sleep(self.reqs['window'] - diff)
def req(self, path, inp=None):
t0 = time.time()
tries = 0
funds_error=False
while True:
# check if have been making too many requests
self.throttle()
try:
# send request to mtgox
opener = urllib2.build_opener()
opener.addheaders = [("Authorization" , "Token token="+self.key )]
if inp==None:
response = opener.open(self.base+path)
else:
inpstr = urllib.urlencode(inp.items())
response = opener.open(self.base+path+"?"+inpstr)
# interpret json response
output = json.load(response)
if 'error' in output:
if output['error']!=[]:
print output
raise ValueError(output['error'])
return output
except Exception as e:
print str(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print "Error: %s" % e
# don't wait too long
tries += 1
if time.time() - t0 > self.timeout or tries > self.tryout:
if funds_error:
raise Exception('Funds')
else:
raise Exception('Timeout')
def req_post(self, path, inp=None):
t0 = time.time()
tries = 0
funds_error=False
while True:
# check if have been making too many requests
self.throttle()
try:
# send request to mtgox
opener = urllib2.build_opener()
opener.addheaders = [("Authorization" , "Token token="+self.key )]
if inp==None:
response = opener.open(self.base+path)
else:
inpstr = urllib.urlencode(inp.items())
response = opener.open(self.base+path,inpstr)
# interpret json response
output = json.load(response)
if 'error' in output:
if output['error']!=[]:
print output
raise ValueError(output['error'])
return output
except Exception as e:
print str(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print "Error: %s" % e
# don't wait too long
tries += 1
if time.time() - t0 > self.timeout or tries > self.tryout:
if funds_error:
raise Exception('Funds')
else:
raise Exception('Timeout')
def req_delete(self, path):
t0 = time.time()
tries = 0
funds_error=False
while True:
# check if have been making too many requests
self.throttle()
try:
# send request to mtgox
headers = {'Authorization': "Token token="+self.key}
req = requests.request('DELETE',self.base+path,headers=headers )
output = req.json()
if 'error' in output:
if output['error']!=[]:
print output
raise ValueError(output['error'])
return output
except Exception as e:
print str(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print "Error: %s" % e
# don't wait too long
tries += 1
if time.time() - t0 > self.timeout or tries > self.tryout:
if funds_error:
raise Exception('Funds')
else:
raise Exception('Timeout')
def get_best_bid(book):
best_price=0.0
for item in book['bids']:
price = float(item[0])
volume = float(item[1])
if volume> .25:
if price>best_price:
best_price=price
return best_price
def get_best_ask(book):
best_price=100000000
for item in book['asks']:
price = float(item[0])
volume = float(item[1])
if volume>.25:
if price<best_price:
best_price=price
return best_price
def cancel_all_orders():
x=0
results=client.req_post(api_version+'orders')
for item in results:
if item['status']=='OPEN':
cancel_order(item['oid'])
x+=1
return x
def cancel_order(oid):
#Placing An Order
return client.req_delete(api_version+'orders/'+oid)
def place_limit_order(side,pair,price,volume):
#Placing An Order
item=pair.split('_')[0]
currency=pair.split('_')[1]
price=round(price,2)
volume=round(volume,4)
return client.req_post(api_version+'orders',{'item':item,'currency':currency,'side':side,'price':price,'quantity':volume,'type':"limit"})['oid']
def get_balances():
account_info=client.req(api_version+'account')
btc_size=0.0
for item in account_info['positions']:
if item['item']=='BTC':
btc_size=item['size']
return account_info['buyingpower'],btc_size
def is_order_live(oid):
if oid==None:
return False
order_info=client.req(api_version+'orders/'+oid)
if order_info['status']!='OPEN':
return False
else:
return True
def get_nbbo_krak(pair,thresh=.1):
item=pair.split('_')[0]
currency=pair.split('_')[1]
best_bid_krak=0
best_ask_krak=1000000
book=client.req(api_version+'market/book',{'item':item,'currency':currency})
for item in book['quotes']:
if float(item['price'])>best_bid_krak and float(item['size'])>thresh and item['side']=="BUY":
best_bid_krak=float(item['price'])
if float(item['price'])<best_ask_krak and float(item['size'])>thresh and item['side']=="SELL":
best_ask_krak=float(item['price'])
#for item in account_info['positions']:
# if item['item']=='BTC':
# btc_size=item['size']
#return account_info['buyingpower'],btc_size
return best_bid_krak,best_ask_krak
#Put Your Api Key Here
key=""
client = AtlasClient(key)
api_version='api/v1/'
print str(cancel_all_orders())+" Orders Cancelled"
#Get Balances
usd_balance,btc_balance=get_balances()
print get_nbbo_krak("BTC_USD")
#Place Bid
#id_bid_1=place_limit_order("BUY","BTC_USD","100.0","0.1")
#Cancel an Order
#cancel_order(id_bid_1)
#Check If Order Is Live
#is_order_live(id_bid_1)
|
6e617410e477a15a165ac46c603685c07146574d
|
[
"Python"
] | 1
|
Python
|
matuszed/Atlas
|
6494e58abe0d4a8c6ed8628582be86d855c3f53f
|
68860a42179e02cf42c25267cef44392a95b00b1
|
refs/heads/main
|
<file_sep>:plugin: kv
:type: filter
///////////////////////////////////////////
START - GENERATED VARIABLES, DO NOT EDIT!
///////////////////////////////////////////
:version: %VERSION%
:release_date: %RELEASE_DATE%
:changelog_url: %CHANGELOG_URL%
:include_path: ../../../../logstash/docs/include
///////////////////////////////////////////
END - GENERATED VARIABLES, DO NOT EDIT!
///////////////////////////////////////////
[id="plugins-{type}s-{plugin}"]
=== Kv filter plugin
include::{include_path}/plugin_header.asciidoc[]
==== Description
This filter helps automatically parse messages (or specific event fields)
which are of the `foo=bar` variety.
For example, if you have a log message which contains `ip=1.2.3.4
error=REFUSED`, you can parse those automatically by configuring:
[source,ruby]
filter {
kv { }
}
The above will result in a message of `ip=1.2.3.4 error=REFUSED` having
the fields:
* `ip: 1.2.3.4`
* `error: REFUSED`
This is great for postfix, iptables, and other types of logs that
tend towards `key=value` syntax.
You can configure any arbitrary strings to split your data on,
in case your data is not structured using `=` signs and whitespace.
For example, this filter can also be used to parse query parameters like
`foo=bar&baz=fizz` by setting the `field_split` parameter to `&`.
[id="plugins-{type}s-{plugin}-ecs_metadata"]
==== Event Metadata and the Elastic Common Schema (ECS)
The plugin behaves the same regardless of ECS compatibility, except giving a warning when ECS is enabled and `target` isn't set.
TIP: Set the `target` option to avoid potential schema conflicts.
[id="plugins-{type}s-{plugin}-options"]
==== Kv Filter Configuration Options
This plugin supports the following configuration options plus the <<plugins-{type}s-{plugin}-common-options>> described later.
[cols="<,<,<",options="header",]
|=======================================================================
|Setting |Input type|Required
| <<plugins-{type}s-{plugin}-allow_duplicate_values>> |<<boolean,boolean>>|No
| <<plugins-{type}s-{plugin}-allow_empty_values>> |<<boolean,boolean>>|No
| <<plugins-{type}s-{plugin}-default_keys>> |<<hash,hash>>|No
| <<plugins-{type}s-{plugin}-ecs_compatibility>> | <<string,string>>|No
| <<plugins-{type}s-{plugin}-exclude_keys>> |<<array,array>>|No
| <<plugins-{type}s-{plugin}-field_split>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-field_split_pattern>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-include_brackets>> |<<boolean,boolean>>|No
| <<plugins-{type}s-{plugin}-include_keys>> |<<array,array>>|No
| <<plugins-{type}s-{plugin}-prefix>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-recursive>> |<<boolean,boolean>>|No
| <<plugins-{type}s-{plugin}-remove_char_key>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-remove_char_value>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-source>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-target>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-tag_on_failure>> |<<array,array>>|No
| <<plugins-{type}s-{plugin}-tag_on_timeout>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-timeout_millis>> |<<number,number>>|No
| <<plugins-{type}s-{plugin}-transform_key>> |<<string,string>>, one of `["lowercase", "uppercase", "capitalize"]`|No
| <<plugins-{type}s-{plugin}-transform_value>> |<<string,string>>, one of `["lowercase", "uppercase", "capitalize"]`|No
| <<plugins-{type}s-{plugin}-trim_key>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-trim_value>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-value_split>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-value_split_pattern>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-whitespace>> |<<string,string>>, one of `["strict", "lenient"]`|No
|=======================================================================
Also see <<plugins-{type}s-{plugin}-common-options>> for a list of options supported by all
filter plugins.
[id="plugins-{type}s-{plugin}-allow_duplicate_values"]
===== `allow_duplicate_values`
* Value type is <<boolean,boolean>>
* Default value is `true`
A bool option for removing duplicate key/value pairs. When set to false, only
one unique key/value pair will be preserved.
For example, consider a source like `from=me from=me`. `[from]` will map to
an Array with two elements: `["me", "me"]`. To only keep unique key/value pairs,
you could use this configuration:
[source,ruby]
filter {
kv {
allow_duplicate_values => false
}
}
[id="plugins-{type}s-{plugin}-allow_empty_values"]
===== `allow_empty_values`
* Value type is <<boolean,boolean>>
* Default value is `false`
A bool option for explicitly including empty values.
When set to true, empty values will be added to the event.
NOTE: Parsing empty values typically requires <<plugins-{type}s-{plugin}-whitespace,`whitespace => strict`>>.
[id="plugins-{type}s-{plugin}-default_keys"]
===== `default_keys`
* Value type is <<hash,hash>>
* Default value is `{}`
A hash specifying the default keys and their values which should be added to the event
in case these keys do not exist in the source field being parsed.
[source,ruby]
filter {
kv {
default_keys => [ "from", "<EMAIL>",
"to", "default@dev.null" ]
}
}
[id="plugins-{type}s-{plugin}-ecs_compatibility"]
===== `ecs_compatibility`
* Value type is <<string,string>>
* Supported values are:
** `disabled`: does not use ECS-compatible field names
** `v1`: Elastic Common Schema compliant behavior (warns when `target` isn't set)
Controls this plugin's compatibility with the {ecs-ref}[Elastic Common Schema (ECS)].
See <<plugins-{type}s-{plugin}-ecs_metadata>> for detailed information.
[id="plugins-{type}s-{plugin}-exclude_keys"]
===== `exclude_keys`
* Value type is <<array,array>>
* Default value is `[]`
An array specifying the parsed keys which should not be added to the event.
By default no keys will be excluded.
For example, consider a source like `Hey, from=<abc>, to=def foo=bar`.
To exclude `from` and `to`, but retain the `foo` key, you could use this configuration:
[source,ruby]
filter {
kv {
exclude_keys => [ "from", "to" ]
}
}
[id="plugins-{type}s-{plugin}-field_split"]
===== `field_split`
* Value type is <<string,string>>
* Default value is `" "`
A string of characters to use as single-character field delimiters for parsing out key-value pairs.
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
*Example with URL Query Strings*
For example, to split out the args from a url query string such as
`?pin=12345~0&d=123&e=<EMAIL>&oq=bobo&ss=12345`:
[source,ruby]
filter {
kv {
field_split => "&?"
}
}
The above splits on both `&` and `?` characters, giving you the following
fields:
* `pin: 12345~0`
* `d: 123`
* `e: <EMAIL>`
* `oq: bobo`
* `ss: 12345`
[id="plugins-{type}s-{plugin}-field_split_pattern"]
===== `field_split_pattern`
* Value type is <<string,string>>
* There is no default value for this setting.
A regex expression to use as field delimiter for parsing out key-value pairs.
Useful to define multi-character field delimiters.
Setting the `field_split_pattern` options will take precedence over the `field_split` option.
Note that you should avoid using captured groups in your regex and you should be
cautious with lookaheads or lookbehinds and positional anchors.
For example, to split fields on a repetition of one or more colons
`k1=v1:k2=v2::k3=v3:::k4=v4`:
[source,ruby]
filter { kv { field_split_pattern => ":+" } }
To split fields on a regex character that need escaping like the plus sign
`k1=v1++k2=v2++k3=v3++k4=v4`:
[source,ruby]
filter { kv { field_split_pattern => "\\+\\+" } }
[id="plugins-{type}s-{plugin}-include_brackets"]
===== `include_brackets`
* Value type is <<boolean,boolean>>
* Default value is `true`
A boolean specifying whether to treat square brackets, angle brackets,
and parentheses as value "wrappers" that should be removed from the value.
[source,ruby]
filter {
kv {
include_brackets => true
}
}
For example, the result of this line:
`bracketsone=(hello world) bracketstwo=[hello world] bracketsthree=<hello world>`
will be:
* bracketsone: hello world
* bracketstwo: hello world
* bracketsthree: hello world
instead of:
* bracketsone: (hello
* bracketstwo: [hello
* bracketsthree: <hello
[id="plugins-{type}s-{plugin}-include_keys"]
===== `include_keys`
* Value type is <<array,array>>
* Default value is `[]`
An array specifying the parsed keys which should be added to the event.
By default all keys will be added.
For example, consider a source like `Hey, from=<abc>, to=def foo=bar`.
To include `from` and `to`, but exclude the `foo` key, you could use this configuration:
[source,ruby]
filter {
kv {
include_keys => [ "from", "to" ]
}
}
[id="plugins-{type}s-{plugin}-prefix"]
===== `prefix`
* Value type is <<string,string>>
* Default value is `""`
A string to prepend to all of the extracted keys.
For example, to prepend arg_ to all keys:
[source,ruby]
filter { kv { prefix => "arg_" } }
[id="plugins-{type}s-{plugin}-recursive"]
===== `recursive`
* Value type is <<boolean,boolean>>
* Default value is `false`
A boolean specifying whether to drill down into values
and recursively get more key-value pairs from it.
The extra key-value pairs will be stored as subkeys of the root key.
Default is not to recursive values.
[source,ruby]
filter {
kv {
recursive => "true"
}
}
[id="plugins-{type}s-{plugin}-remove_char_key"]
===== `remove_char_key`
* Value type is <<string,string>>
* There is no default value for this setting.
A string of characters to remove from the key.
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
Contrary to trim option, all characters are removed from the key, whatever their position.
For example, to remove `<` `>` `[` `]` and `,` characters from keys:
[source,ruby]
filter {
kv {
remove_char_key => "<>\[\],"
}
}
[id="plugins-{type}s-{plugin}-remove_char_value"]
===== `remove_char_value`
* Value type is <<string,string>>
* There is no default value for this setting.
A string of characters to remove from the value.
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
Contrary to trim option, all characters are removed from the value, whatever their position.
For example, to remove `<`, `>`, `[`, `]` and `,` characters from values:
[source,ruby]
filter {
kv {
remove_char_value => "<>\[\],"
}
}
[id="plugins-{type}s-{plugin}-source"]
===== `source`
* Value type is <<string,string>>
* Default value is `"message"`
The field to perform `key=value` searching on
For example, to process the `not_the_message` field:
[source,ruby]
filter { kv { source => "not_the_message" } }
[id="plugins-{type}s-{plugin}-target"]
===== `target`
* Value type is <<string,string>>
* There is no default value for this setting.
The name of the container to put all of the key-value pairs into.
If this setting is omitted, fields will be written to the root of the
event, as individual fields.
For example, to place all keys into the event field kv:
[source,ruby]
filter { kv { target => "kv" } }
[id="plugins-{type}s-{plugin}-tag_on_failure"]
===== `tag_on_failure`
* Value type is <<array,array>>
* The default value for this setting is [`_kv_filter_error`].
When a kv operation causes a runtime exception to be thrown within the plugin,
the operation is safely aborted without crashing the plugin, and the event is
tagged with the provided values.
[id="plugins-{type}s-{plugin}-tag_on_timeout"]
===== `tag_on_timeout`
* Value type is <<string,string>>
* The default value for this setting is `_kv_filter_timeout`.
When timeouts are enabled and a kv operation is aborted, the event is tagged
with the provided value (see: <<plugins-{type}s-{plugin}-timeout_millis>>).
[id="plugins-{type}s-{plugin}-timeout_millis"]
===== `timeout_millis`
* Value type is <<number,number>>
* The default value for this setting is 30000 (30 seconds).
* Set to zero (`0`) to disable timeouts
Timeouts provide a safeguard against inputs that are pathological against the
regular expressions that are used to extract key/value pairs. When parsing an
event exceeds this threshold the operation is aborted and the event is tagged
in order to prevent the operation from blocking the pipeline
(see: <<plugins-{type}s-{plugin}-tag_on_timeout>>).
[id="plugins-{type}s-{plugin}-transform_key"]
===== `transform_key`
* Value can be any of: `lowercase`, `uppercase`, `capitalize`
* There is no default value for this setting.
Transform keys to lower case, upper case or capitals.
For example, to lowercase all keys:
[source,ruby]
filter {
kv {
transform_key => "lowercase"
}
}
[id="plugins-{type}s-{plugin}-transform_value"]
===== `transform_value`
* Value can be any of: `lowercase`, `uppercase`, `capitalize`
* There is no default value for this setting.
Transform values to lower case, upper case or capitals.
For example, to capitalize all values:
[source,ruby]
filter {
kv {
transform_value => "capitalize"
}
}
[id="plugins-{type}s-{plugin}-trim_key"]
===== `trim_key`
* Value type is <<string,string>>
* There is no default value for this setting.
A string of characters to trim from the key. This is useful if your
keys are wrapped in brackets or start with space.
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
Only leading and trailing characters are trimed from the key.
For example, to trim `<` `>` `[` `]` and `,` characters from keys:
[source,ruby]
filter {
kv {
trim_key => "<>\[\],"
}
}
[id="plugins-{type}s-{plugin}-trim_value"]
===== `trim_value`
* Value type is <<string,string>>
* There is no default value for this setting.
Constants used for transform check
A string of characters to trim from the value. This is useful if your
values are wrapped in brackets or are terminated with commas (like postfix
logs).
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
Only leading and trailing characters are trimed from the value.
For example, to trim `<`, `>`, `[`, `]` and `,` characters from values:
[source,ruby]
filter {
kv {
trim_value => "<>\[\],"
}
}
[id="plugins-{type}s-{plugin}-value_split"]
===== `value_split`
* Value type is <<string,string>>
* Default value is `"="`
A non-empty string of characters to use as single-character value delimiters for parsing out key-value pairs.
These characters form a regex character class and thus you must escape special regex
characters like `[` or `]` using `\`.
For example, to identify key-values such as
`key1:value1 key2:value2`:
[source,ruby]
filter { kv { value_split => ":" } }
[id="plugins-{type}s-{plugin}-value_split_pattern"]
===== `value_split_pattern`
* Value type is <<string,string>>
* There is no default value for this setting.
A regex expression to use as value delimiter for parsing out key-value pairs.
Useful to define multi-character value delimiters.
Setting the `value_split_pattern` options will take precedence over the `value_split option`.
Note that you should avoid using captured groups in your regex and you should be
cautious with lookaheads or lookbehinds and positional anchors.
See `field_split_pattern` for examples.
[id="plugins-{type}s-{plugin}-whitespace"]
===== `whitespace`
* Value can be any of: `lenient`, `strict`
* Default value is `lenient`
An option specifying whether to be _lenient_ or _strict_ with the acceptance of unnecessary
whitespace surrounding the configured value-split sequence.
By default the plugin is run in `lenient` mode, which ignores spaces that occur before or
after the value-splitter. While this allows the plugin to make reasonable guesses with most
input, in some situations it may be too lenient.
You may want to enable `whitespace => strict` mode if you have control of the input data and
can guarantee that no extra spaces are added surrounding the pattern you have defined for
splitting values. Doing so will ensure that a _field-splitter_ sequence immediately following
a _value-splitter_ will be interpreted as an empty field.
[id="plugins-{type}s-{plugin}-common-options"]
include::{include_path}/{type}.asciidoc[]
<file_sep># encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require 'logstash/plugin_mixins/ecs_compatibility_support'
require 'logstash/plugin_mixins/ecs_compatibility_support/target_check'
require 'logstash/plugin_mixins/validator_support/field_reference_validation_adapter'
require "timeout"
# This filter helps automatically parse messages (or specific event fields)
# which are of the `foo=bar` variety.
#
# For example, if you have a log message which contains `ip=1.2.3.4
# error=REFUSED`, you can parse those automatically by configuring:
# [source,ruby]
# filter {
# kv { }
# }
#
# The above will result in a message of `ip=1.2.3.4 error=REFUSED` having
# the fields:
#
# * `ip: 1.2.3.4`
# * `error: REFUSED`
#
# This is great for postfix, iptables, and other types of logs that
# tend towards `key=value` syntax.
#
# You can configure any arbitrary strings to split your data on,
# in case your data is not structured using `=` signs and whitespace.
# For example, this filter can also be used to parse query parameters like
# `foo=bar&baz=fizz` by setting the `field_split` parameter to `&`.
class LogStash::Filters::KV < LogStash::Filters::Base
config_name "kv"
include LogStash::PluginMixins::ECSCompatibilitySupport
include LogStash::PluginMixins::ECSCompatibilitySupport::TargetCheck
extend LogStash::PluginMixins::ValidatorSupport::FieldReferenceValidationAdapter
# Constants used for transform check
TRANSFORM_LOWERCASE_KEY = "lowercase"
TRANSFORM_UPPERCASE_KEY = "uppercase"
TRANSFORM_CAPITALIZE_KEY = "capitalize"
# A string of characters to trim from the value. This is useful if your
# values are wrapped in brackets or are terminated with commas (like postfix
# logs).
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# Only leading and trailing characters are trimed from the value.
#
# For example, to trim `<`, `>`, `[`, `]` and `,` characters from values:
# [source,ruby]
# filter {
# kv {
# trim_value => "<>\[\],"
# }
# }
config :trim_value, :validate => :string
# A string of characters to trim from the key. This is useful if your
# keys are wrapped in brackets or start with space.
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# Only leading and trailing characters are trimmed from the key.
#
# For example, to trim `<` `>` `[` `]` and `,` characters from keys:
# [source,ruby]
# filter {
# kv {
# trim_key => "<>\[\],"
# }
# }
config :trim_key, :validate => :string
# A string of characters to remove from the value.
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# Contrary to trim option, all characters are removed from the value, whatever their position.
#
# For example, to remove `<`, `>`, `[`, `]` and `,` characters from values:
# [source,ruby]
# filter {
# kv {
# remove_char_value => "<>\[\],"
# }
# }
config :remove_char_value, :validate => :string
# A string of characters to remove from the key.
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# Contrary to trim option, all characters are removed from the key, whatever their position.
#
# For example, to remove `<` `>` `[` `]` and `,` characters from keys:
# [source,ruby]
# filter {
# kv {
# remove_char_key => "<>\[\],"
# }
# }
config :remove_char_key, :validate => :string
# Transform values to lower case, upper case or capitals.
#
# For example, to capitalize all values:
# [source,ruby]
# filter {
# kv {
# transform_value => "capitalize"
# }
# }
config :transform_value, :validate => [TRANSFORM_LOWERCASE_KEY, TRANSFORM_UPPERCASE_KEY, TRANSFORM_CAPITALIZE_KEY]
# Transform keys to lower case, upper case or capitals.
#
# For example, to lowercase all keys:
# [source,ruby]
# filter {
# kv {
# transform_key => "lowercase"
# }
# }
config :transform_key, :validate => [TRANSFORM_LOWERCASE_KEY, TRANSFORM_UPPERCASE_KEY, TRANSFORM_CAPITALIZE_KEY]
# A string of characters to use as single-character field delimiters for parsing out key-value pairs.
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# #### Example with URL Query Strings
#
# For example, to split out the args from a url query string such as
# `?pin=12345~0&d=123&e=<EMAIL>&oq=bobo&ss=12345`:
# [source,ruby]
# filter {
# kv {
# field_split => "&?"
# }
# }
#
# The above splits on both `&` and `?` characters, giving you the following
# fields:
#
# * `pin: 12345~0`
# * `d: 123`
# * `e: <EMAIL>`
# * `oq: bobo`
# * `ss: 12345`
config :field_split, :validate => :string, :default => ' '
# A regex expression to use as field delimiter for parsing out key-value pairs.
# Useful to define multi-character field delimiters.
# Setting the field_split_pattern options will take precedence over the field_split option.
#
# Note that you should avoid using captured groups in your regex and you should be
# cautious with lookaheads or lookbehinds and positional anchors.
#
# For example, to split fields on a repetition of one or more colons
# `k1=v1:k2=v2::k3=v3:::k4=v4`:
# [source,ruby]
# filter { kv { field_split_pattern => ":+" } }
#
# To split fields on a regex character that need escaping like the plus sign
# `k1=v1++k2=v2++k3=v3++k4=v4`:
# [source,ruby]
# filter { kv { field_split_pattern => "\\+\\+" } }
config :field_split_pattern, :validate => :string
# A non-empty string of characters to use as single-character value delimiters for parsing out key-value pairs.
#
# These characters form a regex character class and thus you must escape special regex
# characters like `[` or `]` using `\`.
#
# For example, to identify key-values such as
# `key1:value1 key2:value2`:
# [source,ruby]
# filter { kv { value_split => ":" } }
config :value_split, :validate => :string, :default => '='
# A regex expression to use as value delimiter for parsing out key-value pairs.
# Useful to define multi-character value delimiters.
# Setting the value_split_pattern options will take precedence over the value_split option.
#
# Note that you should avoid using captured groups in your regex and you should be
# cautious with lookaheads or lookbehinds and positional anchors.
#
# See field_split_pattern for examples.
config :value_split_pattern, :validate => :string
# A string to prepend to all of the extracted keys.
#
# For example, to prepend arg_ to all keys:
# [source,ruby]
# filter { kv { prefix => "arg_" } }
config :prefix, :validate => :string, :default => ''
# The field to perform `key=value` searching on
#
# For example, to process the `not_the_message` field:
# [source,ruby]
# filter { kv { source => "not_the_message" } }
config :source, :validate => :field_reference, :default => "message"
# The name of the container to put all of the key-value pairs into.
#
# If this setting is omitted, fields will be written to the root of the
# event, as individual fields.
#
# For example, to place all keys into the event field kv:
# [source,ruby]
# filter { kv { target => "kv" } }
config :target, :validate => :field_reference
# An array specifying the parsed keys which should be added to the event.
# By default all keys will be added.
#
# For example, consider a source like `Hey, from=<abc>, to=def foo=bar`.
# To include `from` and `to`, but exclude the `foo` key, you could use this configuration:
# [source,ruby]
# filter {
# kv {
# include_keys => [ "from", "to" ]
# }
# }
config :include_keys, :validate => :array, :default => []
# An array specifying the parsed keys which should not be added to the event.
# By default no keys will be excluded.
#
# For example, consider a source like `Hey, from=<abc>, to=def foo=bar`.
# To exclude `from` and `to`, but retain the `foo` key, you could use this configuration:
# [source,ruby]
# filter {
# kv {
# exclude_keys => [ "from", "to" ]
# }
# }
config :exclude_keys, :validate => :array, :default => []
# A hash specifying the default keys and their values which should be added to the event
# in case these keys do not exist in the source field being parsed.
# [source,ruby]
# filter {
# kv {
# default_keys => [ "from", "<EMAIL>",
# "to", "<EMAIL>" ]
# }
# }
config :default_keys, :validate => :hash, :default => {}
# A bool option for removing duplicate key/value pairs. When set to false, only
# one unique key/value pair will be preserved.
#
# For example, consider a source like `from=me from=me`. `[from]` will map to
# an Array with two elements: `["me", "me"]`. To only keep unique key/value pairs,
# you could use this configuration:
# [source,ruby]
# filter {
# kv {
# allow_duplicate_values => false
# }
# }
config :allow_duplicate_values, :validate => :boolean, :default => true
# A bool option for keeping empty or nil values.
config :allow_empty_values, :validate => :boolean, :default => false
# A boolean specifying whether to treat square brackets, angle brackets,
# and parentheses as value "wrappers" that should be removed from the value.
# [source,ruby]
# filter {
# kv {
# include_brackets => true
# }
# }
#
# For example, the result of this line:
# `bracketsone=(hello world) bracketstwo=[hello world] bracketsthree=<hello world>`
#
# will be:
#
# * bracketsone: hello world
# * bracketstwo: hello world
# * bracketsthree: hello world
#
# instead of:
#
# * bracketsone: (hello
# * bracketstwo: [hello
# * bracketsthree: <hello
#
config :include_brackets, :validate => :boolean, :default => true
# A boolean specifying whether to drill down into values
# and recursively get more key-value pairs from it.
# The extra key-value pairs will be stored as subkeys of the root key.
#
# Default is not to recursive values.
# [source,ruby]
# filter {
# kv {
# recursive => "true"
# }
# }
#
config :recursive, :validate => :boolean, :default => false
# An option specifying whether to be _lenient_ or _strict_ with the acceptance of unnecessary
# whitespace surrounding the configured value-split sequence.
#
# By default the plugin is run in `lenient` mode, which ignores spaces that occur before or
# after the value-splitter. While this allows the plugin to make reasonable guesses with most
# input, in some situations it may be too lenient.
#
# You may want to enable `whitespace => strict` mode if you have control of the input data and
# can guarantee that no extra spaces are added surrounding the pattern you have defined for
# splitting values. Doing so will ensure that a _field-splitter_ sequence immediately following
# a _value-splitter_ will be interpreted as an empty field.
#
config :whitespace, :validate => %w(strict lenient), :default => "lenient"
# Attempt to terminate regexps after this amount of time.
# This applies per source field value if event has multiple values in the source field.
# Set to 0 to disable timeouts
config :timeout_millis, :validate => :number, :default => 30_000
# Tag to apply if a kv regexp times out.
config :tag_on_timeout, :validate => :string, :default => '_kv_filter_timeout'
# Tag to apply if kv errors
config :tag_on_failure, :validate => :array, :default => ['_kv_filter_error']
EMPTY_STRING = ''.freeze
def register
# Too late to set the regexp interruptible flag, at least warn if it is not set.
require 'java'
if java.lang.System.getProperty("jruby.regexp.interruptible") != "true" && @timeout_millis > 0
logger.warn("KV Filter registered with `timeout_millis` safeguard enabled, but a required flag is missing so timeouts cannot be reliably enforced. " +
"Without this safeguard, runaway matchers in the KV filter may lead to high CPU usage and stalled pipelines. " +
"To resolve, add `-Djruby.regexp.interruptible=true` to your `config/jvm.options` and restart the Logstash process.")
end
if @value_split.empty?
raise LogStash::ConfigurationError, I18n.t(
"logstash.runner.configuration.invalid_plugin_register",
:plugin => "filter",
:type => "kv",
:error => "Configuration option 'value_split' must be a non-empty string"
)
end
if @field_split_pattern && @field_split_pattern.empty?
raise LogStash::ConfigurationError, I18n.t(
"logstash.runner.configuration.invalid_plugin_register",
:plugin => "filter",
:type => "kv",
:error => "Configuration option 'field_split_pattern' must be a non-empty string"
)
end
if @value_split_pattern && @value_split_pattern.empty?
raise LogStash::ConfigurationError, I18n.t(
"logstash.runner.configuration.invalid_plugin_register",
:plugin => "filter",
:type => "kv",
:error => "Configuration option 'value_split_pattern' must be a non-empty string"
)
end
@trim_value_re = Regexp.new("^[#{@trim_value}]+|[#{@trim_value}]+$") if @trim_value
@trim_key_re = Regexp.new("^[#{@trim_key}]+|[#{@trim_key}]+$") if @trim_key
@remove_char_value_re = Regexp.new("[#{@remove_char_value}]") if @remove_char_value
@remove_char_key_re = Regexp.new("[#{@remove_char_key}]") if @remove_char_key
optional_whitespace = / */
eof = /$/
field_split_pattern = Regexp::compile(@field_split_pattern || "[#{@field_split}]")
value_split_pattern = Regexp::compile(@value_split_pattern || "[#{@value_split}]")
# in legacy-compatible lenient mode, the value splitter can be wrapped in optional whitespace
if @whitespace == 'lenient'
value_split_pattern = /#{optional_whitespace}#{value_split_pattern}#{optional_whitespace}/
end
# a key is a _captured_ sequence of characters or escaped spaces before optional whitespace
# and followed by either a `value_split`, a `field_split`, or EOF.
key_pattern = (original_params.include?('value_split_pattern') || original_params.include?('field_split_pattern')) ?
unquoted_capture_until_pattern(value_split_pattern, field_split_pattern) :
unquoted_capture_until_charclass(@value_split + @field_split)
value_pattern = begin
# each component expression within value_pattern _must_ capture exactly once.
value_patterns = []
value_patterns << quoted_capture(%q(")) # quoted double
value_patterns << quoted_capture(%q(')) # quoted single
if @include_brackets
value_patterns << quoted_capture('(', ')') # bracketed paren
value_patterns << quoted_capture('[', ']') # bracketed square
value_patterns << quoted_capture('<', '>') # bracketed angle
end
# an unquoted value is a _captured_ sequence of characters or escaped spaces before a `field_split` or EOF.
value_patterns << (original_params.include?('field_split_pattern') ?
unquoted_capture_until_pattern(field_split_pattern) :
unquoted_capture_until_charclass(@field_split))
Regexp.union(value_patterns)
end
@scan_re = /#{key_pattern}#{value_split_pattern}#{value_pattern}?#{Regexp::union(field_split_pattern, eof)}/
@value_split_re = value_split_pattern
@logger.debug? && @logger.debug("KV scan regex", :regex => @scan_re.inspect)
# divide by float to allow fractional seconds, the Timeout class timeout value is in seconds but the underlying
# executor resolution is in microseconds so fractional second parameter down to microseconds is possible.
# see https://github.com/jruby/jruby/blob/9.2.7.0/core/src/main/java/org/jruby/ext/timeout/Timeout.java#L125
@timeout_seconds = @timeout_millis / 1000.0
end
def filter(event)
value = event.get(@source)
# if timeout is 0 avoid creating a closure although Timeout.timeout has a bypass for 0s timeouts.
kv = @timeout_seconds > 0.0 ? Timeout.timeout(@timeout_seconds, TimeoutException) { parse_value(value, event) } : parse_value(value, event)
# Add default key-values for missing keys
kv = @default_keys.merge(kv)
return if kv.empty?
if @target
if event.include?(@target)
@logger.debug? && @logger.debug("Overwriting existing target field", field: @target, existing_value: event.get(@target))
end
event.set(@target, kv)
else
kv.each{|k, v| event.set(k, v)}
end
filter_matched(event)
rescue TimeoutException => e
logger.warn("Timeout reached in KV filter with value #{summarize(value)}")
event.tag(@tag_on_timeout)
rescue => ex
meta = { :exception => ex.message }
meta[:backtrace] = ex.backtrace if logger.debug?
logger.warn('Exception while parsing KV', meta)
@tag_on_failure.each { |tag| event.tag(tag) }
end
def close
end
private
def parse_value(value, event)
kv = Hash.new
case value
when nil
# Nothing to do
when String
parse(value, event, kv)
when Array
value.each { |v| parse(v, event, kv) }
else
@logger.warn("kv filter has no support for this type of data", :type => value.class, :value => value)
end
kv
end
# @overload summarize(value)
# @param value [Array]
# @return [String]
# @overload summarize(value)
# @param value [String]
# @return [String]
def summarize(value)
if value.kind_of?(Array)
value.map(&:to_s).map do |entry|
summarize(entry)
end.to_s
end
value = value.to_s
value.bytesize < 255 ? "`#{value.dump}`" : "(entry too large to show; showing first 255 characters) `#{value[0..255].dump}`[...]"
end
def has_value_splitter?(s)
s =~ @value_split_re
end
# Helper function for generating single-capture `Regexp` that, when matching a string bound by the given quotes
# or brackets, will capture the content that is between the quotes or brackets.
#
# @api private
# @param quote_sequence [String] a character sequence that begins a quoted expression
# @param close_quote_sequence [String] a character sequence that ends a quoted expression; (default: quote_sequence)
# @return [Regexp] with a single capture group representing content that is between the given quotes
def quoted_capture(quote_sequence, close_quote_sequence=quote_sequence)
fail('quote_sequence must be non-empty!') if quote_sequence.nil? || quote_sequence.empty?
fail('close_quote_sequence must be non-empty!') if close_quote_sequence.nil? || close_quote_sequence.empty?
open_pattern = /#{Regexp.quote(quote_sequence)}/
close_pattern = /#{Regexp.quote(close_quote_sequence)}/
# matches a sequence of zero or more characters are _not_ the `close_quote_sequence`
quoted_value_pattern = unquoted_capture_until_charclass(Regexp.quote(close_quote_sequence))
/#{open_pattern}#{quoted_value_pattern}?#{close_pattern}/
end
# Helper function for generating *capturing* `Regexp` that will match any sequence of characters that are either
# backslash-escaped OR *NOT* matching any of the given pattern(s)
#
# @api private
# @param *until_lookahead_patterns [Regexp]
# @return [Regexp]
def unquoted_capture_until_pattern(*patterns)
pattern = patterns.size > 1 ? Regexp.union(patterns) : patterns.first
/((?:(?!#{pattern})(?:\\.|.))+)/
end
# Helper function for generating *capturing* `Regexp` that will _efficiently_ match any sequence of characters
# that are either backslash-escaped or do _not_ belong to the given charclass.
#
# @api private
# @param charclass [String] characters to be injected directly into a regexp charclass; special characters must be pre-escaped.
# @return [Regexp]
def unquoted_capture_until_charclass(charclass)
/((?:\\.|[^#{charclass}])+)/
end
def transform(text, method)
case method
when TRANSFORM_LOWERCASE_KEY
return text.downcase
when TRANSFORM_UPPERCASE_KEY
return text.upcase
when TRANSFORM_CAPITALIZE_KEY
return text.capitalize
end
end
# Parses the given `text`, using the `event` for context, into the provided `kv_keys` hash
#
# @param text [String]: the text to parse
# @param event [LogStash::Event]: the event from which to extract context (e.g., sprintf vs (in|ex)clude keys)
# @param kv_keys [Hash{String=>Object}]: the hash in which to inject found key/value pairs
#
# @return [void]
def parse(text, event, kv_keys)
# short circuit parsing if the text does not contain the @value_split
return unless has_value_splitter?(text)
# Interpret dynamic keys for @include_keys and @exclude_keys
include_keys = @include_keys.map{|key| event.sprintf(key)}
exclude_keys = @exclude_keys.map{|key| event.sprintf(key)}
text.scan(@scan_re) do |key, *value_candidates|
value = value_candidates.compact.first || EMPTY_STRING
next if value.empty? && !@allow_empty_values
key = key.gsub(@trim_key_re, EMPTY_STRING) if @trim_key
key = key.gsub(@remove_char_key_re, EMPTY_STRING) if @remove_char_key
key = transform(key, @transform_key) if @transform_key
# Bail out as per the values of include_keys and exclude_keys
next if not include_keys.empty? and not include_keys.include?(key)
# next unless include_keys.include?(key)
next if exclude_keys.include?(key)
key = event.sprintf(@prefix) + key
value = value.gsub(@trim_value_re, EMPTY_STRING) if @trim_value
value = value.gsub(@remove_char_value_re, EMPTY_STRING) if @remove_char_value
value = transform(value, @transform_value) if @transform_value
# Bail out if inserting duplicate value in key mapping when unique_values
# option is set to true.
next if not @allow_duplicate_values and kv_keys.has_key?(key) and kv_keys[key].include?(value)
# recursively get more kv pairs from the value
if @recursive
innerKv = {}
parse(value, event, innerKv)
value = innerKv unless innerKv.empty?
end
if kv_keys.has_key?(key)
if kv_keys[key].is_a?(Array)
kv_keys[key].push(value)
else
kv_keys[key] = [kv_keys[key], value]
end
else
kv_keys[key] = value
end
end
end
class TimeoutException < RuntimeError
end
end
<file_sep># encoding: utf-8
require "logstash/devutils/rspec/spec_helper"
require "insist"
require "logstash/filters/kv"
# Logstash starts JRuby with a special flag to ensure that regexp's are
# executed in an interruptible fashion.
require 'java'
if java.lang.System.getProperty("jruby.regexp.interruptible") != "true"
fail("Java must be started with `-Djruby.regexp.interruptible=true`")
end
describe LogStash::Filters::KV do
describe "defaults" do
# The logstash config goes here.
# At this time, only filters are supported.
config <<-CONFIG
filter {
kv { }
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world' bracketsone=(hello world) bracketstwo=[hello world] bracketsthree=<hello world>" do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
insist { subject.get("bracketsone") } == "hello world"
insist { subject.get("bracketstwo") } == "hello world"
insist { subject.get("bracketsthree") } == "hello world"
end
end
describe "test transforming keys to uppercase and values to lowercase" do
config <<-CONFIG
filter {
kv {
transform_key => "uppercase"
transform_value => "lowercase"
}
}
CONFIG
sample "hello = world Foo =Bar BAZ= FIZZ doublequoteD = \"hellO worlD\" Singlequoted= 'Hello World' brAckets =(hello World)" do
insist { subject.get("HELLO") } == "world"
insist { subject.get("FOO") } == "bar"
insist { subject.get("BAZ") } == "fizz"
insist { subject.get("DOUBLEQUOTED") } == "hello world"
insist { subject.get("SINGLEQUOTED") } == "hello world"
insist { subject.get("BRACKETS") } == "hello world"
end
end
describe 'whitespace => strict' do
config <<-CONFIG
filter {
kv {
whitespace => strict
}
}
CONFIG
context 'unquoted values' do
sample "IN=eth0 OUT= MAC=0f:5f:5e:aa:d3:a2:21:ff:09:00:0f:e1:c8:17 SRC=192.168.0.1" do
insist { subject.get('IN') } == 'eth0'
insist { subject.get('OUT') } == nil # when whitespace is strict, OUT is empty and thus uncaptured.
insist { subject.get('MAC') } == '0f:5f:5e:aa:d3:a2:21:ff:09:00:0f:e1:c8:17'
insist { subject.get('SRC') } == '192.168.0.1'
end
end
context 'mixed quotations' do
sample 'hello=world goodbye=cruel\\ world empty_quoted="" quoted="value1" empty_unquoted= unquoted=value2 empty_bracketed=[] bracketed=[value3] cake=delicious' do
insist { subject.get('hello') } == 'world'
insist { subject.get('goodbye') } == 'cruel\\ world'
insist { subject.get('empty_quoted') } == nil
insist { subject.get('quoted') } == 'value1'
insist { subject.get('empty_unquoted') } == nil
insist { subject.get('unquoted') } == 'value2'
insist { subject.get('empty_bracketed') } == nil
insist { subject.get('bracketed') } == 'value3'
insist { subject.get('cake') } == 'delicious'
end
end
context 'when given sloppy input, it extracts only the unambiguous bits' do
sample "hello = world foo =bar baz= fizz whitespace=none doublequoted = \"hello world\" singlequoted= 'hello world' brackets =(hello world) strict=true" do
insist { subject.get('whitespace') } == 'none'
insist { subject.get('strict') } == 'true'
insist { subject.to_hash.keys.sort } == %w(@timestamp @version message strict whitespace)
end
end
end
describe "test transforming keys to lowercase and values to uppercase" do
config <<-CONFIG
filter {
kv {
transform_key => "lowercase"
transform_value => "uppercase"
}
}
CONFIG
sample "Hello = World fOo =bar baz= FIZZ DOUBLEQUOTED = \"hellO worlD\" singlequoted= 'hEllo wOrld' brackets =(HELLO world)" do
insist { subject.get("hello") } == "WORLD"
insist { subject.get("foo") } == "BAR"
insist { subject.get("baz") } == "FIZZ"
insist { subject.get("doublequoted") } == "HELLO WORLD"
insist { subject.get("singlequoted") } == "HELLO WORLD"
insist { subject.get("brackets") } == "HELLO WORLD"
end
end
describe "test transforming keys and values to capitals" do
config <<-CONFIG
filter {
kv {
transform_key => "capitalize"
transform_value => "capitalize"
}
}
CONFIG
sample "Hello = World fOo =bar baz= FIZZ DOUBLEQUOTED = \"hellO worlD\" singlequoted= 'hEllo wOrld' brackets =(HELLO world)" do
insist { subject.get("Hello") } == "World"
insist { subject.get("Foo") } == "Bar"
insist { subject.get("Baz") } == "Fizz"
insist { subject.get("Doublequoted") } == "Hello world"
insist { subject.get("Singlequoted") } == "Hello world"
insist { subject.get("Brackets") } == "Hello world"
end
end
describe "test spaces attached to the field_split" do
config <<-CONFIG
filter {
kv { }
}
CONFIG
sample "hello = world foo =bar baz= fizz doublequoted = \"hello world\" singlequoted= 'hello world' brackets =(hello world)" do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
insist { subject.get("brackets") } == "hello world"
end
end
describe "LOGSTASH-624: allow escaped space in key or value " do
config <<-CONFIG
filter {
kv { value_split => ':' }
}
CONFIG
sample 'IKE:=Quick\ Mode\ completion IKE\ IDs:=subnet:\ x.x.x.x\ (mask=\ 255.255.255.254)\ and\ host:\ y.y.y.y' do
insist { subject.get("IKE") } == '=Quick\ Mode\ completion'
insist { subject.get('IKE\ IDs') } == '=subnet:\ x.x.x.x\ (mask=\ 255.255.255.254)\ and\ host:\ y.y.y.y'
end
end
describe "test value_split" do
context "using an alternate splitter" do
config <<-CONFIG
filter {
kv { value_split => ':' }
}
CONFIG
sample "hello:=world foo:bar baz=:fizz doublequoted:\"hello world\" singlequoted:'hello world' brackets:(hello world)" do
insist { subject.get("hello") } == "=world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz=") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
insist { subject.get("brackets") } == "hello world"
end
end
end
# these specs are quite implementation specific by testing on the private method
# has_value_splitter? - this is what I figured would help fixing the short circuit
# broken code that was previously in place
describe "short circuit" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
context "plain message" do
let(:options) { {} }
context "without splitter" do
let(:message) { "foo:bar" }
it "should short circuit" do
expect(subject.send(:has_value_splitter?, message)).to be_falsey
expect(subject).to receive(:has_value_splitter?).with(message).once.and_return(false)
subject.filter(event)
end
end
context "with splitter" do
let(:message) { "foo=bar" }
it "should not short circuit" do
expect(subject.send(:has_value_splitter?, message)).to be_truthy
expect(subject).to receive(:has_value_splitter?).with(message).once.and_return(true)
subject.filter(event)
end
end
end
context "recursive message" do
context "without inner splitter" do
let(:inner) { "bar" }
let(:message) { "foo=#{inner}" }
let(:options) { {"recursive" => "true"} }
it "should extract kv" do
subject.filter(event)
expect(event.get("foo")).to eq(inner)
end
it "should short circuit" do
expect(subject.send(:has_value_splitter?, message)).to be_truthy
expect(subject.send(:has_value_splitter?, inner)).to be_falsey
expect(subject).to receive(:has_value_splitter?).with(message).once.and_return(true)
expect(subject).to receive(:has_value_splitter?).with(inner).once.and_return(false)
subject.filter(event)
end
end
context "with inner splitter" do
let(:foo_val) { "1" }
let(:baz_val) { "2" }
let(:inner) { "baz=#{baz_val}" }
let(:message) { "foo=#{foo_val} bar=(#{inner})" } # foo=1 bar=(baz=2)
let(:options) { {"recursive" => "true"} }
it "should extract kv" do
subject.filter(event)
expect(event.get("foo")).to eq(foo_val)
expect(event.get("[bar][baz]")).to eq(baz_val)
end
it "should short circuit" do
expect(subject.send(:has_value_splitter?, message)).to be_truthy
expect(subject.send(:has_value_splitter?, foo_val)).to be_falsey
expect(subject.send(:has_value_splitter?, inner)).to be_truthy
expect(subject.send(:has_value_splitter?, baz_val)).to be_falsey
expect(subject).to receive(:has_value_splitter?).with(message).once.and_return(true)
expect(subject).to receive(:has_value_splitter?).with(foo_val).once.and_return(false)
expect(subject).to receive(:has_value_splitter?).with(inner).once.and_return(true)
expect(subject).to receive(:has_value_splitter?).with(baz_val).once.and_return(false)
subject.filter(event)
end
end
end
end
describe "test field_split" do
config <<-CONFIG
filter {
kv { field_split => '?&' }
}
CONFIG
sample "?hello=world&foo=bar&baz=fizz&doublequoted=\"hello world\"&singlequoted='hello world'&ignoreme&foo12=bar12" do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
insist { subject.get("foo12") } == "bar12"
end
end
describe "test include_brackets is false" do
config <<-CONFIG
filter {
kv { include_brackets => "false" }
}
CONFIG
sample "bracketsone=(hello world) bracketstwo=[hello world]" do
insist { subject.get("bracketsone") } == "(hello"
insist { subject.get("bracketstwo") } == "[hello"
end
end
describe "test recursive" do
config <<-CONFIG
filter {
kv {
recursive => 'true'
}
}
CONFIG
sample 'IKE="Quick Mode completion" IKE\ IDs = (subnet= x.x.x.x mask= 255.255.255.254 and host=y.y.y.y)' do
insist { subject.get("IKE") } == 'Quick Mode completion'
insist { subject.get('IKE\ IDs')['subnet'] } == 'x.x.x.x'
insist { subject.get('IKE\ IDs')['mask'] } == '255.255.255.254'
insist { subject.get('IKE\ IDs')['host'] } == 'y.y.y.y'
end
end
describe "delimited fields should override space default (reported by LOGSTASH-733)" do
config <<-CONFIG
filter {
kv { field_split => "|" }
}
CONFIG
sample "field1=test|field2=another test|field3=test3" do
insist { subject.get("field1") } == "test"
insist { subject.get("field2") } == "another test"
insist { subject.get("field3") } == "test3"
end
end
describe "test prefix" do
config <<-CONFIG
filter {
kv { prefix => '__' }
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("__hello") } == "world"
insist { subject.get("__foo") } == "bar"
insist { subject.get("__baz") } == "fizz"
insist { subject.get("__doublequoted") } == "hello world"
insist { subject.get("__singlequoted") } == "hello world"
end
end
describe "speed test", :performance => true do
count = 10000 + rand(3000)
config <<-CONFIG
input {
generator {
count => #{count}
type => foo
message => "hello=world bar='baz fizzle'"
}
}
filter {
kv { }
}
output {
null { }
}
CONFIG
start = Time.now
agent do
duration = (Time.now - start)
puts "filters/kv rate: #{"%02.0f/sec" % (count / duration)}, elapsed: #{duration}s"
end
end
describe "add_tag" do
context "should activate when successful" do
config <<-CONFIG
filter {
kv { add_tag => "hello" }
}
CONFIG
sample "hello=world" do
insist { subject.get("hello") } == "world"
insist { subject.get("tags") }.include?("hello")
end
end
context "should not activate when failing" do
config <<-CONFIG
filter {
kv { add_tag => "hello" }
}
CONFIG
sample "this is not key value" do
insist { subject.get("tags") }.nil?
end
end
end
describe "add_field" do
context "should activate when successful" do
config <<-CONFIG
filter {
kv { add_field => [ "whoa", "fancypants" ] }
}
CONFIG
sample "hello=world" do
insist { subject.get("hello") } == "world"
insist { subject.get("whoa") } == "fancypants"
end
end
context "should not activate when failing" do
config <<-CONFIG
filter {
kv { add_tag => "hello" }
}
CONFIG
sample "this is not key value" do
reject { subject.get("whoa") } == "fancypants"
end
end
end
#New tests
describe "test target" do
config <<-CONFIG
filter {
kv { target => 'kv' }
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("kv")["hello"] } == "world"
insist { subject.get("kv")["foo"] } == "bar"
insist { subject.get("kv")["baz"] } == "fizz"
insist { subject.get("kv")["doublequoted"] } == "hello world"
insist { subject.get("kv")["singlequoted"] } == "hello world"
insist {subject.get("kv").count } == 5
end
end
describe "test empty target" do
config <<-CONFIG
filter {
kv { target => 'kv' }
}
CONFIG
sample "hello:world:foo:bar:baz:fizz" do
insist { subject.get("kv") } == nil
end
end
describe "test data from specific sub source" do
config <<-CONFIG
filter {
kv {
source => "data"
}
}
CONFIG
sample({"data" => "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'"}) do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
end
end
describe "test data from specific top source" do
config <<-CONFIG
filter {
kv {
source => "@data"
}
}
CONFIG
sample({"@data" => "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'"}) do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
end
end
describe 'field_split_pattern with literal backslashes' do
config <<-CONFIG
filter {
kv {
source => headers
field_split_pattern => "\\\\r\\\\n"
value_split_pattern => ": "
whitespace => strict
target => headerskv
}
}
CONFIG
sample({"headers"=>"Host: foo.com\\r\\nUser-Agent: Qwerty/1.2.3 (www.qwerty.org)\\r\\nContent-Type: text/xml; charset=utf-8\\r\\nAccept: */*\\r\\nAccept-Encoding: gzip, deflate\\r\\nContent-Length: 123\\r\\nX-UUID: 0:15713435944943992\\r\\n\\r\\n"}) do
insist { subject.get("[headerskv][Host]") } == "foo.com"
insist { subject.get("[headerskv][User-Agent]") } == "Qwerty/1.2.3 (www.qwerty.org)"
insist { subject.get("[headerskv][Content-Type]") } == "text/xml; charset=utf-8"
insist { subject.get("[headerskv][Accept]") } == "*/*"
insist { subject.get("[headerskv][Accept-Encoding]") } == "gzip, deflate"
insist { subject.get("[headerskv][Content-Length]") } == "123"
insist { subject.get("[headerskv][X-UUID]") } == "0:15713435944943992"
end
end
describe "test data from specific sub source and target" do
config <<-CONFIG
filter {
kv {
source => "data"
target => "kv"
}
}
CONFIG
sample({"data" => "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'"}) do
insist { subject.get("kv")["hello"] } == "world"
insist { subject.get("kv")["foo"] } == "bar"
insist { subject.get("kv")["baz"] } == "fizz"
insist { subject.get("kv")["doublequoted"] } == "hello world"
insist { subject.get("kv")["singlequoted"] } == "hello world"
insist { subject.get("kv").count } == 5
end
end
describe "test data from nil sub source, should not issue a warning" do
config <<-CONFIG
filter {
kv {
source => "non-exisiting-field"
target => "kv"
}
}
CONFIG
sample "" do
insist { subject.get("non-exisiting-field") } == nil
insist { subject.get("kv") } == nil
end
end
describe "test include_keys" do
config <<-CONFIG
filter {
kv {
include_keys => [ "foo", "singlequoted" ]
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("foo") } == "bar"
insist { subject.get("singlequoted") } == "hello world"
end
end
describe "test exclude_keys" do
config <<-CONFIG
filter {
kv {
exclude_keys => [ "foo", "singlequoted" ]
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("hello") } == "world"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
end
end
describe "test include_keys with prefix" do
config <<-CONFIG
filter {
kv {
include_keys => [ "foo", "singlequoted" ]
prefix => "__"
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("__foo") } == "bar"
insist { subject.get("__singlequoted") } == "hello world"
end
end
describe "test exclude_keys with prefix" do
config <<-CONFIG
filter {
kv {
exclude_keys => [ "foo", "singlequoted" ]
prefix => "__"
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("__hello") } == "world"
insist { subject.get("__baz") } == "fizz"
insist { subject.get("__doublequoted") } == "hello world"
end
end
describe "test include_keys with dynamic key" do
config <<-CONFIG
filter {
kv {
source => "data"
include_keys => [ "%{key}"]
}
}
CONFIG
sample({"data" => "foo=bar baz=fizz", "key" => "foo"}) do
insist { subject.get("foo") } == "bar"
insist { subject.get("baz") } == nil
end
end
describe "test exclude_keys with dynamic key" do
config <<-CONFIG
filter {
kv {
source => "data"
exclude_keys => [ "%{key}"]
}
}
CONFIG
sample({"data" => "foo=bar baz=fizz", "key" => "foo"}) do
insist { subject.get("foo") } == nil
insist { subject.get("baz") } == "fizz"
end
end
describe "test include_keys and exclude_keys" do
config <<-CONFIG
filter {
kv {
# This should exclude everything as a result of both settings.
include_keys => [ "foo", "singlequoted" ]
exclude_keys => [ "foo", "singlequoted" ]
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
%w(hello foo baz doublequoted singlequoted).each do |field|
reject { subject }.include?(field)
end
end
end
describe "test default_keys" do
config <<-CONFIG
filter {
kv {
default_keys => [ "foo", "xxx",
"goo", "yyy" ]
}
}
CONFIG
sample "hello=world foo=bar baz=fizz doublequoted=\"hello world\" singlequoted='hello world'" do
insist { subject.get("hello") } == "world"
insist { subject.get("foo") } == "bar"
insist { subject.get("goo") } == "yyy"
insist { subject.get("baz") } == "fizz"
insist { subject.get("doublequoted") } == "hello world"
insist { subject.get("singlequoted") } == "hello world"
end
end
describe "overwriting a string field (often the source)" do
config <<-CONFIG
filter {
kv {
source => "happy"
target => "happy"
}
}
CONFIG
sample({"happy" => "foo=bar baz=fizz"}) do
insist { subject.get("[happy][foo]") } == "bar"
insist { subject.get("[happy][baz]") } == "fizz"
end
end
describe "Removing duplicate key/value pairs" do
config <<-CONFIG
filter {
kv {
field_split => "&"
source => "source"
allow_duplicate_values => false
}
}
CONFIG
sample({"source" => "foo=bar&foo=yeah&foo=yeah"}) do
insist { subject.get("[foo]") } == ["bar", "yeah"]
end
end
describe "Allowing empty values" do
config <<-CONFIG
filter {
kv {
field_split => " "
source => "source"
allow_empty_values => true
whitespace => strict
}
}
CONFIG
sample({"source" => "present=one empty= emptyquoted='' present=two emptybracketed=[] endofinput="}) do
insist { subject.get('[present]') } == ['one','two']
insist { subject.get('[empty]') } == ''
insist { subject.get('[emptyquoted]') } == ''
insist { subject.get('[emptybracketed]') } == ''
insist { subject.get('[endofinput]') } == ''
end
end
describe "Allow duplicate key/value pairs by default" do
config <<-CONFIG
filter {
kv {
field_split => "&"
source => "source"
}
}
CONFIG
sample({"source" => "foo=bar&foo=yeah&foo=yeah"}) do
insist { subject.get("[foo]") } == ["bar", "yeah", "yeah"]
end
end
describe "keys without values (reported in #22)" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:f1) { "AccountStatus" }
let(:v1) { "4" }
let(:f2) { "AdditionalInformation" }
let(:f3) { "Code" }
let(:f4) { "HttpStatusCode" }
let(:f5) { "IsSuccess" }
let(:v5) { "True" }
let(:f6) { "Message" }
let(:message) { "#{f1}: #{v1}\r\n#{f2}\r\n\r\n#{f3}: \r\n#{f4}: \r\n#{f5}: #{v5}\r\n#{f6}: \r\n" }
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
let(:options) {
{
"field_split" => "\r\n",
"value_split" => " ",
"trim_key" => ":"
}
}
context "key and splitters with no value" do
it "should ignore the incomplete key/value pairs" do
subject.filter(event)
expect(event.get(f1)).to eq(v1)
expect(event.get(f5)).to eq(v5)
expect(event.include?(f2)).to be false
expect(event.include?(f3)).to be false
expect(event.include?(f4)).to be false
expect(event.include?(f6)).to be false
end
end
end
describe "trim_key/trim_value options : trim only leading and trailing spaces in keys/values (reported in #10)" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:message) { "key1= value1 with spaces | key2 with spaces =value2" }
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
let(:options) {
{
"field_split" => "\|",
"value_split" => "=",
"trim_value" => " ",
"trim_key" => " "
}
}
context "key and value with leading, trailing and middle spaces" do
it "should trim only leading and trailing spaces" do
subject.filter(event)
expect(event.get("key1")).to eq("value1 with spaces")
expect(event.get("key2 with spaces")).to eq("value2")
end
end
end
describe "trim_key/trim_value options : trim multiple matching characters from either end" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
context 'repeated same-character sequence' do
let(:message) { "key1= value1 with spaces | key2 with spaces =value2" }
let(:options) {
{
"field_split" => "|",
"value_split" => "=",
"trim_value" => " ",
"trim_key" => " "
}
}
it 'trims all the right bits' do
subject.filter(event)
expect(event.get('key1')).to eq('value1 with spaces')
expect(event.get('key2 with spaces')).to eq('value2')
end
end
context 'multi-character sequence' do
let(:message) { "to=<<EMAIL>>, orig_to=<<EMAIL>>, %+relay=mail.example.com[private/dovecot-lmtp], delay=2.2, delays=1.9/0.01/0.01/0.21, dsn=2.0.0, status=sent (250 2.0.0 <<EMAIL>> YERDHejiRSXFDSdfUXTV Saved) " }
let(:options) {
{
"field_split" => " ",
"value_split" => "=",
"trim_value" => "<>,",
"trim_key" => "%+"
}
}
it 'trims all the right bits' do
subject.filter(event)
expect(event.get('to')).to eq('<EMAIL>')
expect(event.get('orig_to')).to eq('<EMAIL>')
expect(event.get('relay')).to eq('mail.example.com[private/dovecot-lmtp]')
expect(event.get('delay')).to eq('2.2')
expect(event.get('delays')).to eq('1.9/0.01/0.01/0.21')
expect(event.get('dsn')).to eq('2.0.0')
expect(event.get('status')).to eq('sent')
end
end
end
describe "remove_char_key/remove_char_value options : remove all characters in keys/values whatever their position" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:message) { "key1= value1 with spaces | key2 with spaces =value2" }
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
let(:options) {
{
"field_split" => "\|",
"value_split" => "=",
"remove_char_value" => " ",
"remove_char_key" => " "
}
}
context "key and value with leading, trailing and middle spaces" do
it "should remove all spaces" do
subject.filter(event)
expect(event.get("key1")).to eq("value1withspaces")
expect(event.get("key2withspaces")).to eq("value2")
end
end
end
describe "an empty value_split option should be reported" do
config <<-CONFIG
filter {
kv {
value_split => ""
}
}
CONFIG
sample({"message" => "random message"}) do
insist { subject }.raises(LogStash::ConfigurationError)
end
end
end
describe "multi character splitting" do
subject do
plugin = LogStash::Filters::KV.new(options)
plugin.register
plugin
end
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
shared_examples "parsing all fields and values" do
it "parses all fields and values" do
subject.filter(event)
expect(event.get("hello")).to eq("world")
expect(event.get("foo")).to eq("bar")
expect(event.get("baz")).to eq("fizz")
expect(event.get("doublequoted")).to eq("hello world")
expect(event.get("singlequoted")).to eq("hello world")
expect(event.get("bracketsone")).to eq("hello world")
expect(event.get("bracketstwo")).to eq("hello world")
expect(event.get("bracketsthree")).to eq("hello world")
end
end
context "empty value_split_pattern" do
let(:options) { { "value_split_pattern" => "" } }
it "should raise ConfigurationError" do
expect{subject}.to raise_error(LogStash::ConfigurationError)
end
end
context "empty field_split_pattern" do
let(:options) { { "field_split_pattern" => "" } }
it "should raise ConfigurationError" do
expect{subject}.to raise_error(LogStash::ConfigurationError)
end
end
context "single split" do
let(:message) { "hello:world foo:bar baz:fizz doublequoted:\"hello world\" singlequoted:'hello world' bracketsone:(hello world) bracketstwo:[hello world] bracketsthree:<hello world>" }
let(:options) {
{
"field_split" => " ",
"value_split" => ":",
}
}
it_behaves_like "parsing all fields and values"
end
context "value split multi" do
let(:message) { "hello::world foo::bar baz::fizz doublequoted::\"hello world\" singlequoted::'hello world' bracketsone::(hello world) bracketstwo::[hello world] bracketsthree::<hello world>" }
let(:options) {
{
"field_split" => " ",
"value_split_pattern" => "::",
}
}
it_behaves_like "parsing all fields and values"
end
context 'multi-char field split pattern with value that begins quoted and contains more unquoted' do
let(:message) { 'foo=bar!!!!!baz="quoted stuff" and more unquoted!!!!!msg="fully-quoted with a part! of the separator"!!!!!blip="this!!!!!is it"!!!!!empty=""!!!!!non-empty="foo"' }
let(:options) {
{
"field_split_pattern" => "!!!!!"
}
}
it 'gets the right bits' do
subject.filter(event)
expect(event.get("foo")).to eq('bar')
expect(event.get("baz")).to eq('"quoted stuff" and more unquoted')
expect(event.get("msg")).to eq('fully-quoted with a part! of the separator')
expect(event.get("blip")).to eq('this!!!!!is it')
expect(event.get("empty")).to be_nil
expect(event.get("non-empty")).to eq('foo')
end
end
context 'standard field split pattern with value that begins quoted and contains more unquoted' do
let(:message) { 'foo=bar baz="quoted stuff" and more unquoted msg="some fully-quoted message " empty="" non-empty="foo"' }
let(:options) {
{
}
}
it 'gets the right bits' do
subject.filter(event)
expect(event.get("foo")).to eq('bar')
expect(event.get("baz")).to eq('quoted stuff') # NOTE: outside the quotes is truncated because field split pattern wins.
expect(event.get("msg")).to eq('some fully-quoted message ')
expect(event.get("empty")).to be_nil
expect(event.get("non-empty")).to eq('foo')
end
end
context "field and value split multi" do
let(:message) { "hello::world__foo::bar__baz::fizz__doublequoted::\"hello world\"__singlequoted::'hello world'__bracketsone::(hello world)__bracketstwo::[hello world]__bracketsthree::<hello world>" }
let(:options) {
{
"field_split_pattern" => "__",
"value_split_pattern" => "::",
}
}
it_behaves_like "parsing all fields and values"
end
context "field and value split multi with regex" do
let(:message) { "hello:world_foo::bar__baz:::fizz___doublequoted:::\"hello world\"____singlequoted:::::'hello world'____bracketsone:::(hello world)__bracketstwo:[hello world]_bracketsthree::::::<hello world>" }
let(:options) {
{
"field_split_pattern" => "_+",
"value_split_pattern" => ":+",
}
}
it_behaves_like "parsing all fields and values"
end
context "field and value split multi using singe char" do
let(:message) { "hello:world foo:bar baz:fizz doublequoted:\"hello world\" singlequoted:'hello world' bracketsone:(hello world) bracketstwo:[hello world] bracketsthree:<hello world>" }
let(:options) {
{
"field_split_pattern" => " ",
"value_split_pattern" => ":",
}
}
it_behaves_like "parsing all fields and values"
end
context "field and value split multi using escaping" do
let(:message) { "hello++world??foo++bar??baz++fizz??doublequoted++\"hello world\"??singlequoted++'hello world'??bracketsone++(hello world)??bracketstwo++[hello world]??bracketsthree++<hello world>" }
let(:options) {
{
"field_split_pattern" => "\\?\\?",
"value_split_pattern" => "\\+\\+",
}
}
it_behaves_like "parsing all fields and values"
end
context "example from @guyboertje in #15" do
let(:message) { 'key1: val1; key2: val2; key3: https://site/?g={......"...; CLR rv:11.0)"..}; key4: val4;' }
let(:options) {
{
"field_split_pattern" => ";\s*(?=key.+?:)|;$",
"value_split_pattern" => ":\s+",
}
}
it "parses all fields and values" do
subject.filter(event)
expect(event.get("key1")).to eq("val1")
expect(event.get("key2")).to eq("val2")
expect(event.get("key3")).to eq("https://site/?g={......\"...; CLR rv:11.0)\"..}")
expect(event.get("key4")).to eq("val4")
end
end
describe "handles empty values" do
let(:message) { 'a=1|b=|c=3' }
shared_examples "parse empty values" do
it "splits correctly upon empty value" do
subject.filter(event)
expect(event.get("a")).to eq("1")
expect(event.get("b")).to be_nil
expect(event.get("c")).to eq("3")
end
end
context "using char class splitters" do
let(:options) {
{
"field_split" => "|",
"value_split" => "=",
}
}
it_behaves_like "parse empty values"
end
context "using pattern splitters" do
let(:options) {
{
"field_split_pattern" => '\|',
"value_split_pattern" => "=",
}
}
it_behaves_like "parse empty values"
end
end
end
context 'runtime errors' do
let(:options) { {} }
let(:plugin) do
LogStash::Filters::KV.new(options).instance_exec { register; self }
end
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
let(:message) { "foo=bar hello=world" }
before(:each) do
expect(plugin).to receive(:parse) { fail('intentional') }
end
context 'when a runtime error is raised' do
it 'does not cascade the exception to crash the plugin' do
plugin.filter(event)
end
it 'tags the event with "_kv_filter_error"' do
plugin.filter(event)
expect(event.get('tags')).to_not be_nil
expect(event.get('tags')).to include('_kv_filter_error')
end
it 'logs an informative message' do
logger_double = double('Logger').as_null_object
expect(plugin).to receive(:logger).and_return(logger_double).at_least(:once)
expect(logger_double).to receive(:warn).with('Exception while parsing KV', anything)
plugin.filter(event)
end
context 'when a custom tag is defined' do
let(:options) { super().merge("tag_on_failure" => "KV-ERROR")}
it 'tags the event with the custom tag' do
plugin.filter(event)
expect(event.get('tags')).to_not be_nil
expect(event.get('tags')).to include('KV-ERROR')
expect(event.get('tags')).to_not include('_kv_filter_error')
end
end
context 'when multiple custom tags are defined' do
let(:options) { super().merge("tag_on_failure" => ["kv_FAIL_one", "_kv_fail_TWO"])}
it 'tags the event with the custom tag' do
plugin.filter(event)
expect(event.get('tags')).to_not be_nil
expect(event.get('tags')).to include('kv_FAIL_one')
expect(event.get('tags')).to include('_kv_fail_TWO')
expect(event.get('tags')).to_not include('_kv_filter_error')
end
end
end
end
# This group intentionally uses patterns that are vulnerable to pathological inputs to test timeouts.
#
# patterns of the form `/(?:x+x+)+y/` are vulnerable to inputs that have long sequences matching `/x/`
# that are _not_ followed by a sequence matching `/y/`.
context 'timeouts' do
let(:options) do
{
"value_split_pattern" => "(?:=+=+)+:"
}
end
subject(:plugin) do
LogStash::Filters::KV.new(options).instance_exec { register; self }
end
let(:data) { {"message" => message} }
let(:event) { LogStash::Event.new(data) }
let(:message) { "foo=bar hello=world" }
after(:each) { plugin.close }
# since we are dealing with potentially-pathological specs, ensure specs fail in a timely
# manner if they block for longer than `spec_blocking_threshold_seconds`.
let(:spec_blocking_threshold_seconds) { 10 }
around(:each) do |example|
begin
blocking_exception_class = Class.new(::Exception) # avoid RuntimeError, which is handled in KV#filter
Timeout.timeout(spec_blocking_threshold_seconds, blocking_exception_class, &example)
rescue blocking_exception_class
fail('execution blocked')
end
end
context 'when timeouts are enabled' do
let(:options) { super().merge("timeout_millis" => 250) }
let(:spec_blocking_threshold_seconds) { 3 }
context 'when given a pathological input' do
let(:message) { "foo========:bar baz================================================bingo" }
it 'tags the event' do
plugin.filter(event)
expect(event.get('tags')).to be_a_kind_of(Enumerable)
expect(event.get('tags')).to include('_kv_filter_timeout')
end
context 'when given a custom `tag_on_timeout`' do
let(:options) { super().merge('tag_on_timeout' => 'BADKV') }
it 'tags the event with the custom tag' do
plugin.filter(event)
expect(event.get('tags')).to be_a_kind_of(Enumerable)
expect(event.get('tags')).to include('BADKV')
end
end
context 'when default_keys are provided' do
let(:options) { super().merge("default_keys" => {"default" => "key"})}
it 'does not populate default keys' do
plugin.filter(event)
expect(event).to_not include('default')
end
end
context 'when filter_matched hooks are provided' do
let(:options) { super().merge("add_field" => {"kv" => "success"})}
it 'does not call filter_matched hooks' do
plugin.filter(event)
expect(event).to_not include('kv')
end
end
end
context 'when given a non-pathological input' do
let(:message) { "foo==:bar baz==:bingo" }
it 'extracts the k/v' do
plugin.filter(event)
expect(event.get('foo')).to eq('bar')
expect(event.get('baz')).to eq('bingo')
end
end
end
context 'when timeouts are explicitly disabled' do
let(:options) { super().merge("timeout_millis" => 0) }
context 'when given a pathological input' do
let(:message) { "foo========:bar baz================================================================bingo"}
it 'blocks for at least 3 seconds' do
blocking_exception_class = Class.new(::Exception) # avoid RuntimeError, which is handled in KV#filter
expect do
Timeout.timeout(3, blocking_exception_class) do
plugin.filter(event)
end
end.to raise_exception(blocking_exception_class)
end
end
context 'when given a non-pathological input' do
let(:message) { "foo==:bar baz==:bingo" }
it 'extracts the k/v' do
plugin.filter(event)
expect(event.get('foo')).to eq('bar')
expect(event.get('baz')).to eq('bingo')
end
end
end
end
<file_sep>## 4.7.1
- Improved action call-out of log warning when this plugin cannot enforce timeouts [#93](https://github.com/logstash-plugins/logstash-filter-kv/pull/93)
## 4.7.0
- Allow attaching multiple tags on failure. The `tag_on_failure` option now also supports an array of strings [#100](https://github.com/logstash-plugins/logstash-filter-kv/issues/100). Fixes [#92](https://github.com/logstash-plugins/logstash-filter-kv/issues/92)
## 4.6.0
- Added `allow_empty_values` option [#72](https://github.com/logstash-plugins/logstash-filter-kv/pull/72)
## 4.5.0
- Feat: check that target is set in ECS mode [#96](https://github.com/logstash-plugins/logstash-filter-kv/pull/96)
## 4.4.1
- Fixed issue where a `field_split_pattern` containing a literal backslash failed to match correctly [#87](https://github.com/logstash-plugins/logstash-filter-kv/issues/87)
## 4.4.0
- Changed timeout handling using the Timeout class [#84](https://github.com/logstash-plugins/logstash-filter-kv/pull/84)
## 4.3.3
- Fixed asciidoc formatting in docs
## 4.3.2
- Resolved potential race condition in pipeline shutdown where the timeout enforcer could be shut down while work was still in-flight, potentially leading to stuck pipelines.
- Resolved potential race condition in pipeline shutdown where work could be submitted to the timeout enforcer after it had been shutdown, potentially leading to stuck pipelines.
## 4.3.1
- Fixed asciidoc formatting in documentation [#81](https://github.com/logstash-plugins/logstash-filter-kv/pull/81)
## 4.3.0
- Added a timeout enforcer which prevents inputs that are pathological against the generated parser from blocking
the pipeline. By default, timeout is a generous 30s, but can be configured or disabled entirely with the new
`timeout_millis` and `tag_on_timeout` directives ([#79](https://github.com/logstash-plugins/logstash-filter-kv/pull/79))
- Made error-handling configurable with `tag_on_failure` directive.
## 4.2.1
- Fixes performance regression introduced in 4.1.0 ([#70](https://github.com/logstash-plugins/logstash-filter-kv/issues/70))
## 4.2.0
- Added `whitespace => strict` mode, which allows the parser to behave more predictably when input is known to avoid unnecessary whitespace.
- Added error handling, which tags the event with `_kv_filter_error` if an exception is raised while handling an event instead of allowing the plugin to crash.
## 4.1.2
- bugfix: improves trim_key and trim_value to trim any _sequence_ of matching characters from the beginning and ends of the corresponding keys and values; a previous implementation limitited trim to a single character from each end, which was surprising.
- bugfix: fixes issue where we can fail to correctly break up a sequence that includes a partially-quoted value followed by another fully-quoted value by slightly reducing greediness of quoted-value captures.
## 4.1.1
- bugfix: correctly handle empty values between value separator and field separator (#58)
## 4.1.0
- feature: add option to split fields and values using a regex pattern (#55)
## 4.0.3
- Update gemspec summary
## 4.0.2
- Fix some documentation issues
## 4.0.0
- breaking: trim and trimkey options are renamed to trim_value and trim_key
- bugfix: trim_value and trim_key options now remove only leading and trailing characters (#10)
- feature: new options remove_char_value and remove_char_key to remove all characters from keys/values whatever their position
## 3.1.1
- internal,deps: Relax constraint on logstash-core-plugin-api to >= 1.60 <= 2.99
## 3.1.0
- Adds :transform_value and :transform_key options to lowercase/upcase or capitalize all keys/values
## 3.0.1
- internal: Republish all the gems under jruby.
## 3.0.0
- internal,deps: Update the plugin to the version 2.0 of the plugin api, this change is required for Logstash 5.0 compatibility. See https://github.com/elastic/logstash/issues/5141
## 2.0.7
- feature: With include_brackets enabled, angle brackets (\< and \>) are treated the same as square brackets and parentheses, making it easy to parse strings like "a=\<b\> c=\<d\>".
- feature: An empty value_split option value now gives a useful error message.
## 2.0.6
- internal,deps: Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash
## 2.0.5
- internal,deps: New dependency requirements for logstash-core for the 5.0 release
## 2.0.4
- bugfix: Fields without values could claim the next field + value under certain circumstances. Reported in #22
## 2.0.3
- bugfix: fixed short circuit expressions, some optimizations, added specs, PR #20
- bugfix: fixed event field assignment, PR #21
## 2.0.0
- internal: Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully,
instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895
- internal,deps: Dependency on logstash-core update to 2.0
## 1.1.0
- feature: support spaces between key and value_split,
support brackets and recursive option.
|
0c8dd5c3ec06b7043c12670bfa0b2316526002fa
|
[
"Markdown",
"Ruby",
"AsciiDoc"
] | 4
|
AsciiDoc
|
logstash-plugins/logstash-filter-kv
|
cdabd65486c0b9a3fc16207bfb385d48a0d1a9a7
|
945ebc4978c16286df9ce15b1cf02b3863eb14b8
|
refs/heads/master
|
<repo_name>Jaycar-Electronics/Wall-Dodging-Robot<file_sep>/robotCode/robotCode.ino
// Wall Doding robot code
// <NAME> 2020
#include <AFMotor.h>
const int ldr_pin = A5;
const int trigger_pin = A2;
const int echo_pin = A3;
const int light_threshold = 700;
const int sonar_threshold = 200;
AF_DCMotor left_motor(4);
AF_DCMotor right_motor(3);
//define the functions so we can use them later.
void setup()
{
Serial.begin(9600);
Serial.println("Robot Starting!");
pinMode(ldr_pin, INPUT);
pinMode(trigger_pin, OUTPUT);
pinMode(echo_pin, INPUT);
Serial.println("Robot OK!");
}
void loop()
{
delay(100);
int ldrReading = analogRead(ldr_pin);
long sonarDistance = sonarPing();
Serial.print("LDR Reading: ");
Serial.println(ldrReading, DEC);
Serial.print("Distance Reading: ");
Serial.println(sonarDistance, DEC);
//check if the lights are on
if (ldrReading < light_threshold)
{
stop();
blinkErrorMessage();
//return as we don't want to do more in the loop function
return;
}
// check distance of what's in front of us
// (closer objects are lower values)
if (sonarDistance < sonar_threshold)
{
//turn around;
stop();
driveBackward(800);
reverseTurn(800);
stop();
}
//drive forward
driveForward();
}
// ===============================================================
// ----------------------------------------------------
// blinkErrorMessage function
// This is to just blink the onboard LED when needed.
void blinkErrorMessage()
{
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(1000);
pinMode(13, INPUT);
}
// --------------------------------------------------------
// motion functions
// These just set the correct motor values to drive the bot
void driveForward()
{
left_motor.run(FORWARD);
right_motor.run(FORWARD);
left_motor.setSpeed(255);
right_motor.setSpeed(255);
}
void driveBackward(long time)
{
left_motor.run(BACKWARD);
right_motor.run(BACKWARD);
left_motor.setSpeed(255);
right_motor.setSpeed(255);
delay(time); //drive backwards for half a second
}
void stop()
{
left_motor.setSpeed(0);
right_motor.setSpeed(0);
delay(500); //stop for half a second, allow motors to wind down
}
void reverseTurn(long time)
{
left_motor.run(FORWARD);
right_motor.run(BACKWARD);
left_motor.setSpeed(0);
right_motor.setSpeed(255);
delay(time);
}
// -------------------------------------------------------------
// sonarPing function
// This measures the distance (in milimeters) to the object infront of it
unsigned long sonarPing()
{
//send a pulse and time how long it takes to come back.
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
unsigned long duration = pulseIn(echo_pin, HIGH);
return duration * 0.17; //convert microseconds to millimeters; (speed of sound);
}
<file_sep>/robotCode/Workshop_Wall_Dodging_Robot.ino
#include <Ultrasonic.h>
//Ultrasonic sensor pins
#define TRIG 9
#define ECHO 10
//motor module pins
const int channel_a_enable = 6;
const int channel_a_input_1 = 4;
const int channel_a_input_2 = 7;
const int channel_b_enable = 5;
const int channel_b_input_3 = 3;
const int channel_b_input_4 = 2;
int a=0; //motor a speed and direction
int b=0; //motor b speed and direction
int phase=0; //what stage are we up to
long timeout=0; //how long have we been doing it for
#define PROX 30
#define FORWARDSPEED 150
#define REVERSESPEED 150
//set TURNSPEED negative to turn the other way
#define TURNSPEED 150
#define REVERSETIME 1000
#define TURNTIME 1000
Ultrasonic ultrasonic(TRIG,ECHO);
void setup()
{
pinMode(11,OUTPUT);
digitalWrite(11,LOW); //GND for ultrasonic
pinMode(8,OUTPUT);
digitalWrite(8,HIGH); //5V for ultrasonic
usonicsetup();
pinMode( channel_a_enable, OUTPUT ); // Channel A enable
pinMode( channel_a_input_1, OUTPUT ); // Channel A input 1
pinMode( channel_a_input_2, OUTPUT ); // Channel A input 2
pinMode( channel_b_enable, OUTPUT ); // Channel B enable
pinMode( channel_b_input_3, OUTPUT ); // Channel B input 3
pinMode( channel_b_input_4, OUTPUT ); // Channel B input 4
//everything off
digitalWrite( channel_a_input_1, LOW);
digitalWrite( channel_a_input_2, LOW);
digitalWrite( channel_a_enable, LOW);
digitalWrite( channel_b_input_3, LOW);
digitalWrite( channel_b_input_4, LOW);
digitalWrite( channel_b_enable, LOW);
delay(1000); //wait a bit
Serial.begin( 9600 ); //serial debug
Serial.println("Starting up");
}
void loop()
{
//read ultrasonic sensor
int d;
d= ultrasonic.read(); // usonic(11600)/58; // distance in cm
if(d==0){d=200;}
Serial.println(d); //print d on serial monitor
//react based on d
switch(phase){
case 0:
if(d<PROX){phase=1;timeout=millis();} //if too close, reverse
break;
case 1:
if(millis()>timeout+REVERSETIME){phase=2;timeout=millis();} //reversed for REVERSETIME, now turn
break;
case 2:
if(millis()>timeout+TURNTIME){phase=0;} //turned for TURNTIME, now back to forward
break;
}
//print phase for debugging
Serial.print("PHASE:");
Serial.println(phase);
//set motors based on stage
switch(phase){
case 0: //normal going forward
a=FORWARDSPEED;
b=FORWARDSPEED;
break;
case 1: //backing up
a=-(REVERSESPEED);
b=-(REVERSESPEED);
break;
case 2: //turn a little
a=TURNSPEED;
b=-(TURNSPEED);
break;
default: //something wrong happened
a=0;
b=0;
break;
}
setmotor();
delay(200); //wait a bit
}
void setmotor(){
int s;
if(a>0){
digitalWrite( channel_a_input_1, HIGH);
digitalWrite( channel_a_input_2, LOW);
}
if(a<0){
digitalWrite( channel_a_input_1, LOW);
digitalWrite( channel_a_input_2, HIGH);
}
if(b>0){
digitalWrite( channel_b_input_3, HIGH);
digitalWrite( channel_b_input_4, LOW);
}
if(b<0){
digitalWrite( channel_b_input_3, LOW);
digitalWrite( channel_b_input_4, HIGH);
}
s=abs(a);
if(s>255){s=255;}
if(s<0){s=0;}
analogWrite( channel_a_enable, s);
s=abs(b);
if(s>255){s=255;}
if(s<0){s=0;}
analogWrite( channel_b_enable, s);
}
void allInputsOff()
{
digitalWrite( channel_a_input_1, LOW);
digitalWrite( channel_a_input_2, LOW);
digitalWrite( channel_a_enable, LOW);
digitalWrite( channel_b_input_3, LOW);
digitalWrite( channel_b_input_4, LOW);
digitalWrite( channel_b_enable, LOW);
}
void usonicsetup(void){
pinMode(ECHO, INPUT);
pinMode(TRIG, OUTPUT);
digitalWrite(TRIG, LOW);
}
long usonic(long utimeout){ //utimeout is maximum time to wait for return in us
long b;
if(digitalRead(ECHO)==HIGH){return 0;} //if echo line is still low from last result, return 0;
digitalWrite(TRIG, HIGH); //send trigger pulse
delay(1);
digitalWrite(TRIG, LOW);
long utimer=micros();
while((digitalRead(ECHO)==LOW)&&((micros()-utimer)<1000)){} //wait for pin state to change- return starts after 460us typically
utimer=micros();
while((digitalRead(ECHO)==HIGH)&&((micros()-utimer)<utimeout)){} //wait for pin state to change
b=micros()-utimer;
return b;
}
<file_sep>/README.md
# Wall Dodging Robot
This clever robot is the perfect way to get started with robotics. The robot explores
its surroundings as it avoids obstacles and walls in its path. Starting with the
provided code, the robot can easily be expanded upon.
This is the updated version! codename `Mini-Tesla` - it now has a rechargeable Li-ion battery with an On-Off switch. It also now has a light sensor so it can turn off (or reverse) when it gets into dark places such as under beds or tables, and we use the motor shield to save space on the platform.
There's a lot more that this little robot can do, check out the [Exploration](#Exploration) section for more ideas once you have finished off the build.

## Table of Contents
- [Wall Dodging Robot](#Wall-Dodging-Robot)
- [Table of Contents](#Table-of-Contents)
- [Bill of Materials](#Bill-of-Materials)
- [You might also want](#You-might-also-want)
- [Connection Table](#Connection-Table)
- [System Overview](#System-Overview)
- [Assembly](#Assembly)
- [USB connector](#USB-connector)
- [Assembling the Chassis](#Assembling-the-Chassis)
- [Soldering the motor controller](#Soldering-the-motor-controller)
- [Positing components and placing the switch](#Positing-components-and-placing-the-switch)
- [Connecting the UNO/Motor controller](#Connecting-the-UNOMotor-controller)
- [Attaching the sensors](#Attaching-the-sensors)
- [Quick power test](#Quick-power-test)
- [Programming](#Programming)
- [Troubleshooting](#Troubleshooting)
- [Exploration](#Exploration)
## Bill of Materials
| Qty | Code | Description |
| --- | ---------------------------------------- | --------------------------- |
| 1 | [XC4410](https://jaycar.com.au/p/XC4410) | UNO board |
| 1 | [XC4442](https://jaycar.com.au/p/XC4442) | Ultrasonic Sensor |
| 1 | [KR3160](https://jaycar.com.au/p/KR3160) | 2 wheeled robotic platform |
| 1 | [MB3793](https://jaycar.com.au/p/MB3793) | Rechargeable battery pack |
| 1 | [XC4472](https://jaycar.com.au/p/XC4472) | Motor Shield for arduino |
| 1 | [PP0790](https://jaycar.com.au/p/PP0790) | USB A bare solder plug |
| 1 | [WC7756](https://jaycar.com.au/p/WC7756) | USB Micro extension cable |
| 1 | [ST0300](https://jaycar.com.au/p/ST0300) | Mini toggle switch |
| 1 | [XC4446](https://jaycar.com.au/p/XC4446) | LDR sensor module |
| 1 | [HM3211](https://jaycar.com.au/p/HM3211) | Vertical Header 28pin |
| 1 | [WC6026](https://jaycar.com.au/p/WC6026) | Socket socket leads 40 pack |
### You might also want
- Some spare wires, [WH3025](https://jaycar.com.au/p/WH3025) is a good choice as it gives you a number of colours, 2 meters in length.
- Small hot glue gun ([TH1997](https://jaycar.com.au/p/TH1997)) or some extra hot glue ([TH1991](https://jaycar.com.au/p/TH1991))
- Bootlace crimps, for terminals: [PT4433](https://jaycar.com.au/p/PT4433)
- Double-sided tape: [NM2821](https://jaycar.com.au/p/NM2821)
- Extra mounting hardware, such as M3 nuts ([HP0425](https://jaycar.com.au/p/HP0425))
## Connection Table
The motor controller ([XC4472](https://jaycar.com.au/p/XC4472)) fits directly on-top of the uno so you don't have to worry about the pinout of the motor connections. The LDR and ultrasonic sensor ([XC4446](https://jaycar.com.au/p/XC4446) and [XC4442](https://jaycar.com.au/p/XC4442)) connect into the analogue pins on the motor shield, which don't have headers, but we can just solder them in with the [HM3211](https://jaycar.com.au/p/HM3211) vertical headers.
| UNO (shield) | Device |
| ------------ | --------------- |
| A5 | LDR Sensor pin |
| A4 | Ultrasonic TRIG |
| A3 | Ultrasonic ECHO |
Be sure to connect all of the 5V to the 5V pins, and the GND to GND pins.
## System Overview

The overall robotic platform is pretty easy to understand. we are using a battery to power the entire system by jacking into the motor controller. This means we have the most amount of current (which with lithium ion - could be a lot!) goes to the motors when we want it to. The LDR and ultrasonic sensor plug into the motor shield but they actually just get passed and controlled by the UNO underneath.
## Assembly
We've broken the assembly instructions into different sections so you can jump around if you need to:
- [USB connector](#USB-connector)
- [Assembling the Chassis](#Assembling-the-Chassis)
- [Positing components and placing the switch](#Positing-components-and-placing-the-switch)
### USB connector
Firstly, we'll assemble the USB connector. Looking at what's in the pack you should have 4 pieces as shown below.

USB is a common standard so we would do best to follow the standard by looking at what the pin out for a USB connector is, we are focused on "USB A" on the cable side, you can google for this easily:

Flip over the connector, so that the solder tags are facing you, (they have a 'u' shape) and you'll find that the leftmost connector (labelled `4` in the diagram above) is the ground connection. Strip a length of wire (either from [WH3025](https://jaycar.com.au/p/WH3025) or whatever you've got) and twist the wires so they all remain together. Then fill the 'u' shaped channel on the connector with a bit of solder.

Then, you'll be able to easily place the wire on top of the solder, and heat it through so that it gets absorbed by the melted solder. You can then put some fresh solder over the top so that it's secure in place and completely covered by solder.

As long as it's secure and there's no stray wires it should be ok. Continue to do the positive side, which is the opposite end of the connector. Here we used an orange colour to signify that it is not ground. It's important not to get the polarity wrong, so some sort of colour scheming should do good.

Then you can clip the small white cover on top, then place it into the large metal connector.

You should find that it only goes one way, and it must be flush on the USB connector side, as shown below.

Then you can place the other metal casing over it; This metal part "hooks" into it, as shown on the above picture, then it can swing close and become a bit tidy, enclosing everything in the metal housing.

Once it's all together, and snug, you can gently plug it in and test polarity with a multimeter if you want. It's crucial to get the polarity right; while this battery set up has plenty of protection to keep everything safe, not every battery does.
Once it's good, use a pair of pliers to gently wrap up the cable clamps to make it strong and sturdy.

Then you've finished the USB connector, this will be used to plug into the rechargeable battery later.

### Assembling the Chassis
In the Robot Chassis kit ([KR3160](https://jaycar.com.au/p/KR3160)) you should find some metal pieces and some long screws, along with the motor gearboxes. Bolt through the motor gearboxes onto the metal mounts as shown below.

We'll do this to both sides, so that they are opposing, with the top screw-mounts on opposite sides:

You'll find that there's only one real spot where the wheels will actually attach, and you can use the smaller screws to attach the motors to that point.

The trolley wheel goes near the flat end of the robotic platform, and you can use the broad-headed screws to mount the wheel to the small brass spacers in the kit, like such:

Then use the remaining small screws to mount the wheel assembly to the chassis. If you have some spare washers or nuts, you can space them out a bit so that they fit more securely as shown below, or just mount it straight onto the chassis. It shouldn't cause a problem.

### Soldering the motor controller
The motor controller has plenty of connectors on it, however not all of them have the header pins. You should see 3 rows of 6 solder pads near the analogue connections on the motor controller, this is where we will use some of the [HM3211](https://jaycar.com.au/p/HM3211) pins to solder in.
Break off 3 lots of 4 pins. We are only using 4 as that's what we need, but you can break off longer segments if you want. Place one lot in through the top of the motor shield along the analogue connectors and flip the motor controller around so you can solder underneath as shown below.

It might be easier to start with the analogue connections first, then work your way away from the edge; here we've started on the GND row.

Tack them in and be sure not to short any of the connections. The connectors are already done on the board, so we don't need to make any new connections here.

### Positing components and placing the switch
Next up, we'll start positioning the components and building the on-off switch.
Cover the leads of the USB cable that you made previously, and connect both the USB cable and the USB extension into the [MB3793](https://jaycar.com.au/p/MB3793) battery pack. Lay out the components under the robot platform as shown below:

Here we've pushed the motor cables up and through the platform so they are on top, as well as put the USB extension under the 3rd wheel.
Use hot glue to mount the battery case and the USB extension lead in place, so that the battery pack is fairly centred and the usb lead is flush with the side of the robot, as shown below. Note where the switch will end up when we get to finally placing it.

Now you know the length of wire that you need, you can cut and strip a portion of wire so that you don't have too much wire between the battery and the switch, then solder to one of the side terminals on the [ST0300](https://jaycar.com.au/p/ST0300) switch.

Use some more black wire (signifying ground) to the middle terminal, and place the switch back in the hole near the 3d wheel. Use a spanner to tighten the top nut of the switch so that it is sitting firmly in place. You won't need the washers on the switch if they make it more difficult to attach.
Bring the new negative wire up through the same hole as the positive from the USB/battery bank. you should now have 6 wires coming to the top portion of the platform, 2 from each motor and the positive/negative from the USB cable in the battery bank.

### Connecting the UNO/Motor controller
Once the motor shield has been soldered and you're happy with it, you can place it on top of the UNO and mount the UNO to the robotic platform. We've found it nicer to mount the uno off to the side a little so that you can still program through the USB-B connector, so we use some double sided tape ([NM2821](https://jaycar.com.au/p/NM2821)) or hot-glue to keep it in place.

Connect the motors to the motor ports (M3 and M4) then connect the battery bank leads to the M+ and GND connections on the shield (remember polarity!). We've used bootlace crimps ([PT4433](https://jaycar.com.au/p/PT4433)) to make the connections extra secure as the terminals have something extra to grab on-to, but you could also bend the bare wires back a bit and double up inside of the screw terminal. Trim the wires to size as well, so that there's not too much loose wire hanging around. The polarity of the motors don't really matter, as you can just reverse them in code.
- Make sure that the "EXT_PWR" jumper is also connected so that the UNO feeds power off the motor controller power.
- If you were powering this off a battery that has more than 12v, you **need** to disconnect this jumper, but this battery is 5v so it is fine.
### Attaching the sensors
Next is just the ultrasonic and LDR sensors, which can be placed wherever you wish. Connect the `VCC` and `GND` from each sensor to the `5V` and `GND` on the motor shield, from the header connections that were soldered on previously, then connect the `S`, `TRIG`, and `ECHO` wires to the analogue pins.

You can do any pin out, but our code sample has LDR on `A5`, `TRIG` on `A4` and `ECHO` on `A3`.
We used hot-glue to fix the sensors in position.
### Quick power test
Once everything is connected, you should be able to flick the switch to turn on the battery pack and find the motor controller and UNO lights up. Turn it off again to program. If you plug in a phone charger or otherwise to the side port, the battery bank should shine red to show that it is recharging.
## Programming
The source code is in the `robotCode` folder, which you can modify and upload. Once you've uploaded you should see the robot start driving and turn around if it reaches a wall. It will also stop moving if you turn the lights off, or if it goes underneath a table or bed.
### Troubleshooting
The arduino code has information showing in the serial monitor on `9600` baud. You can prop the motor up on a mug or box so that the wheels are off the ground, and see how it responds to moving your hand in front of the sensor, or covering the LDR with your fingers.
- If the robot does not move to begin with, it might be too dark for the robot already; shine a torch on the LDR of the robot to see if it moves
- you can calibrate the `light_threshold` in the code to determine at what light level the robot stops moving.
- If the robot keeps hitting a wall, check to see if the robot will hit the wall when facing straight at it.
- If it hits the wall, then make sure that the `ECHO` and `TRIG` pins are connected the right way, and see what the serial output says.
If the robot hits walls on an angle, it might not detect the wall properly, something similar to below:

The only way to combat this is to use two ultrasonic sensors on different angles, so that one of them is going to be a little more perpendicular to the side wall. You can also look in the below [Exploration](#Exploration) section for some ideas, such as using a servo to move the sensor to face the wall.
## Exploration
This is really meant to be a starting platform for robotics, as you can now change the robot in any way that suits; some ideas are below:
- [YM2758](https://jaycar.com.au/p/YM2758) Servo module
- Attach the servo so that the ultrasonic can sweep across and look at other directions, a bit like the Ultrasonic radar project
- [XC4411](https://jaycar.com.au/p/XC4411) UNO with WiFi
- Use the Uno with WiFi so that it can accept commands from a computer or phone, similar to our WiFi Rover project.
- [XC4385](https://jaycar.com.au/p/XC4385) Circular RGB LED Lights
- Circular LEDS makes everything cooler, as it can give impressions on what it's doing or which direction it's travelling. This makes it similar to our [KR9262](https://jaycar.com.au/p/KR9262) robot as well.
- [XC4496](https://jaycar.com.au/p/XC4496) 3 Axis Magnetometer
- Get a reading of what's north so the robot can find it's way throughout a maze or similar
|
282f644c65234bccd1ec8b377f1ef044b83ccbfa
|
[
"Markdown",
"C++"
] | 3
|
C++
|
Jaycar-Electronics/Wall-Dodging-Robot
|
02604fcd1d58aae902fe3fcd0dcefca24a0a5d2a
|
2029e61029e136680a80b1a53fdf1d8c0ecfe157
|
refs/heads/master
|
<repo_name>andrewvora/horokov<file_sep>/scripts/main.js
var sentenceSize = 10;
var numSentenceOffset = Math.floor(sentenceSize/3 + Math.pow(-1, 0.5 - Math.random()));
var numSentences = Math.floor(sentenceSize/2) + Math.floor(sentenceSize*Math.random());
numSentences = numSentences < 3 ? numSentences : 3;
var SetHoroscope = function(sign){
var horoscopeText = "";
for(var i = 0; i < numSentences; i++){
horoscopeText+=generate_horoscope(sentenceSize + Math.floor(sentenceSize * Math.random()))+". ";
}
$("#horoscope").find("#horoscope-text").html(horoscopeText);
$("#horoscope").find("h1").first().html(sign);
$("#horoscope-image").attr("src", "img/"+sign+".png");
};
$(document).ready(function(){
//horoscope generation
SetHoroscope("Aries");
//bio generation
sentenceSize = 7 + Math.floor(2 + Math.pow(-1, 0.5 - Math.random()));
numSentences = Math.floor(3*Math.random());
numSentences = numSentences < 1 ? 1 : numSentences;
var bioText = "";
for(var i = 0; i < numSentences; i++){
bioText += generate_bio(sentenceSize)+". ";
}
$("#bio").html(bioText);
});<file_sep>/README.md
# Horokov - Markov Chains + Horoscopes
My little entry for the UF Bad-Appathon 2014 (hosted by UF SEC) :V
Simply `git clone` and open `index.html` in your fav browser to _run_ it.
<file_sep>/scripts/parser.js
var source;
var bioSource;
var getText = function(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
if(file.indexOf("horoscope") > -1) source = rawFile.responseText.split(/[.?!]/);
else if(file.indexOf("bio") > -1) bioSource = rawFile.responseText.split(/[.?!]/);
}
}
}
rawFile.send(null);
}
getText("words/horoscopes.txt");
getText("words/bio.txt");
|
a5de40f27479fe290b647f144b4aab626dd8e8ee
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
andrewvora/horokov
|
0f7b539bdfc88bc0f66f6d587621b7f5193e6580
|
aa2a3706da66e6974f8a2f0a46032731b251e916
|
refs/heads/master
|
<repo_name>LaoDie1/godot_vector_graphics<file_sep>/README.md
Vector Graphics for Godot.
* This is an experiment
* It's written in C++ 11, so it's editor-only
* All vector graphics can be converted into `MeshInstance2D`s
* I have very little time to work on this
Live Demo:
https://www.youtube.com/watch?v=EsTSf5dytbs&feature=youtu.be
# Install and build
* Check out this repo as `git clone --recurse-submodules https://github.com/poke1024/godot_vector_graphics`
* Rename the whole repo folder to `vector_graphics` and move it into your Godot `/modules` folder (i.e. as `/modules/vector_graphics`).
* Build godot using `scons platform=your_platform svg=patch`.
* The `svg=patch` part in the `scons` build instructs the `vector_graphics` module to apply a patch, so that you can drag and drop SVGs as vector graphics into Godot (see the SVG Import Patch section below to see what exactly is patched).
# Basic usage in Godot
Drag and drop an SVG into the 2d canvas.
Or: add a new VGPath node in your scene (under a Node2D).
In the inspector, set its Renderer to a new VGAdaptiveRenderer. Now, in
the toolbar at the top, click on the circle. Drag and drop on the canvas
to draw a vector circle.
Select a VGPath and double click onto it (while having the arrow tool
selected) to see and edit control points and curves.
You can add new control points by clicking on a curve.
Select a control point and hit the delete key to remove it.
Rendering quality can be changed by editing the VGAdaptiveRenderer's
quality setting (lower number means less triangles). You can do this
interactively in the Godot editor.
# The SVG Import Patch
In order to be able to drag and drop SVG assets into the Godot editor
as vector graphics, you need to make one patch in Godot; take a look at
the accompanying patches/0001-tovegd-svg-support.patch, which is this:
In editor/canvas_item_editor_plugin.cpp, add
Node *createVectorSprite(Ref<Resource> p_resource, Node *p_owner);
then replace
child = memnew(Sprite); // default
with:
child = createVectorSprite(texture, target_node);
After recompiling, you should now be able to drag and drop an SVG file
into your Godot FileSystem. From there you can drag it into your scene,
and all SVG paths should get converted into VGPaths.
<file_sep>/SCsub
#!/usr/bin/env python
Import('env')
Import('env_modules')
env_tove = env_modules.Clone()
env_tove.add_source_files(env.modules_sources, "*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/cpp/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/cpp/mesh/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/cpp/shader/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/cpp/gpux/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/thirdparty/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/thirdparty/polypartition/src/*.cpp")
env_tove.add_source_files(env.modules_sources, "tove2d/src/thirdparty/tinyxml2/tinyxml2.cpp")
import os
dir_path = Dir('.').abspath
env_tove.Append(CXXFLAGS=[
'-std=c++11',
'-DTOVE_GODOT',
'-I' + os.path.join(dir_path, 'tove2d/src/thirdparty/fp16/include')])
def package_sl(target, source, env):
with open(source[0].abspath, "r") as sl:
with open(target[0].abspath, "w") as out:
out.write('w << R"GLSL(\n')
out.write(sl.read())
out.write(')GLSL";\n')
env_tove.Append(BUILDERS={
'PackageSL':Builder(action=package_sl)})
env_tove.PackageSL(
'tove2d/src/glsl/fill.frag.inc',
Glob('tove2d/src/glsl/fill.frag'))
env_tove.PackageSL(
'tove2d/src/glsl/line.vert.inc',
Glob('tove2d/src/glsl/line.vert'))
# patching.
env_vars = Variables(None, ARGUMENTS)
env_vars.Add(EnumVariable(
'svg',
'patch for vector graphics svg support?',
'nopatch', allowed_values=('patch', 'nopatch')))
env_vars.Update(env)
if env['svg'] == 'patch':
declare_vector_sprite = '''
Node *createVectorSprite(Ref<Resource> p_resource);
void configureVectorSprite(Node *p_child, Ref<Resource> p_texture);
'''
replace_create = (
('child = memnew(Sprite);',
'child = createVectorSprite(texture);'),
('_create_nodes(target_node, child, path, drop_pos);',
'_create_nodes(target_node, child, path, drop_pos); configureVectorSprite(child, texture);')
)
editor_plugins_path = Dir('../../editor/plugins').abspath
file_path = os.path.join(editor_plugins_path, 'canvas_item_editor_plugin.cpp')
with open(file_path, 'r+') as f:
source_code = f.read()
if declare_vector_sprite not in source_code:
lines = source_code.split("\n")
include_index = None
for i, line in enumerate(lines):
if line.strip().startswith('#include'):
include_index = i
lines.insert(include_index + 1, declare_vector_sprite)
source_code = "\n".join(lines)
for a, b in replace_create:
source_code = source_code.replace(a, b)
f.seek(0)
f.write(source_code)
print("patched %s" % file_path)
<file_sep>/patches/icons/README.md
move to /editor/icons/
(do this before building godot)
|
a722267c983fd6ec736514c3ab6d25e81d11ecc3
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
LaoDie1/godot_vector_graphics
|
bf8c8702ea83e9746b5b23c813ca3b710bca46bc
|
d5560b52d0361756b910a5db4e9a352e5630f4e1
|
refs/heads/master
|
<repo_name>SiddharthShukla547/Login<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms'
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
hide: boolean = false;
dummypass = '<PASSWORD>';
dummymail = '<EMAIL>';
passent = '';
emailent = '';
constructor(private fb: FormBuilder, private route:Router) {
}
ngOnInit() {
}
loginForm: FormGroup = this.fb.group({
email: ['', [Validators.required, Validators.email, Validators.pattern('^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.]+[\.][a-z]{2,}$')]],
password: ['', [Validators.required, Validators.minLength(8), Validators.pattern('^(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[0-9]{1,})(?=.*[~!@#$%^&*()\-_=+{};:,<.>]{1,}).{8,}$')]]
})
onLogin() {
if(this.passent === this.dummypass && this.emailent === this.dummymail){
this.route.navigate(['HomePage']);
}
else{alert("Wrong credentials");
this.passent = '';
this.emailent = '';
}
}
loginButtonDisabled()
{
return (this.loginForm.valid);
}
}
|
6e00ef0d366069c86644fd820ca24e17304bc7d0
|
[
"TypeScript"
] | 1
|
TypeScript
|
SiddharthShukla547/Login
|
f659ee2ad4b8afbb13d5067f4c7f6547cae84c5e
|
b6c7eb774f41ab647bd22cad1138fa11305835ed
|
refs/heads/master
|
<file_sep>#!/usr/bin/env bash
pip3 install virtualenv
<file_sep># config
### Prerequisites
* Clone this repo to `~/git/config`
* Install `xcode`
### Usage
To set up everything from scratch, run the following:
```
cd ~/git/config/utils
./do_everything.sh
```
To periodically update homebrew, run this from the terminal:
```
homebrew_me_harder
```
### Notes
* **Danger:** this will remove your current `~/.bash_profile`, `~/.vimrc`, and `~/.ssh/config`
* ssh keys need to be placed in `~/.ssh`
* `~/.github_tokens.sh` will need to be updated
* `~/.virtualenvs` will be the location for Python virtualenvs
<file_sep>#!/usr/bin/env bash
sudo xcodebuild -license
<file_sep>#!/usr/bin/env bash
source ./homebrew_utils.sh
ensure_homebrew_is_installed
brew update
ensure_installed bash
new_shell='/usr/local/bin/bash'
grep $new_shell /etc/shells >/dev/null || sudo bash -c "echo $new_shell >> /etc/shells"
if [ "$new_shell" != "$(which bash)" ]; then
chsh -s $new_shell
fi
<file_sep>#!/bin/bash
echo "###########################################"
echo "# #"
echo "# ~/.github_tokens.sh needs updated!!!!!! #"
echo "# #"
echo "# https://github.com/settings/tokens #"
echo "# #"
echo "###########################################"
export HOMEBREW_GITHUB_API_TOKEN=<PASSWORD>
<file_sep>#!/usr/bin/env bash
CASKROOM="`brew --prefix`/Caskroom"
installed_packages=($(brew list))
installed_casks=($(brew cask list))
function status_update {
BLUE='\033[1;34m'
WHITE='\033[1;97m'
NC='\033[0m'
echo -e "${BLUE}==> ${WHITE}${1}${NC}"
}
function contains_element {
local element
for element in "${@:2}"
do
if [[ "$element" == "$1" ]]
then
return 0
fi
done
return 1
}
function ensure_homebrew_is_installed {
status_update "Ensuring homebrew is installed"
if ! hash brew 2>/dev/null
then
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
else
echo "Already installed"
fi
}
function ensure_installed {
if ! contains_element "$(echo "$1" | rev | cut -d'/' -f1 | rev)" "${installed_packages[@]}"
then
brew install $@
fi
}
function ensure_cask_installed {
cask_info=$(brew cask info $1)
echo "$cask_info" | grep 'Not installed' &>/dev/null
is_not_installed=$?
if [ $is_not_installed -eq 0 ]
then
brew cask install --force $1
else
manifest_version=$(echo "$cask_info" | head -n1 | cut -d' ' -f2)
echo "$cask_info" | tail -n +2 | grep $manifest_version &>/dev/null
is_manifest_version_present=$?
if [ $is_manifest_version_present -ne 0 ]
then
brew cask install --force $1
fi
fi
}
function cleanup_old_cask_versions {
status_update "Removing old cask versions"
installed_casks=($(brew cask list))
cask_count=${#installed_casks[@]}
for (( i=0; i<${cask_count}; i++ ))
do
cask=${installed_casks[$i]}
if (( $(ls -l $CASKROOM/$cask/.metadata | wc -l) > 2 ))
then
current_version=$(get_cask_manifest_version $cask)
for version in $(ls $CASKROOM/$cask/.metadata)
do
if [ "$current_version" != "$version" ]
then
echo "$CASKROOM/$cask/$version is replaced by $current_version"
rm -rf $CASKROOM/$cask/$version
rm -rf $CASKROOM/$cask/.metadata/$version
fi
done
fi
echo -en "Processed $((i + 1))/${cask_count}\r"
done
echo
}
function get_cask_installed_version {
echo $(brew cask list $1 | grep "Staged content:" -A 1 | tail -n1 | cut -d' ' -f1 | sed "s|`echo $CASKROOM/$1/`||")
}
function get_cask_manifest_version {
echo $(brew cask info $1 | head -n1 | cut -d' ' -f2)
}
<file_sep>alias ls='ls --color=auto'
alias ll='ls -la'
alias grep="`which grep` --color=always"
alias homebrew_me_harder='~/git/config/utils/homebrew.sh'
if [ -f $(brew --prefix)/etc/bash_completion ]; then
. $(brew --prefix)/etc/bash_completion
fi
complete -o default -o nospace -W"$(grep "^Host" $HOME/.ssh/config | grep -v "[?*]" | cut -d" " -f2)" scp sftp ssh
complete -o default -o nospace -W"$(find $HOME/.virtualenvs -name "activate")" source
GIT_PS1_SHOWDIRTYSTATE=1 # unstaged (*), staged (+)
GIT_PS1_SHOWSTASHSTATE=1 # stashed ($)
GIT_PS1_SHOWUNTRACKEDFILES=1 # untracked (%)
GIT_PS1_SHOWUPSTREAM="auto" # behind (<), ahead (>), diverged (<>), no difference (=)
export PS1='$(__git_ps1 "(%s) ")\w\$ '
PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"
source ~/.github_tokens.sh
<file_sep>#!/usr/bin/env bash
./set_preferences.applescript >/dev/null
# Show hidden files in Finder
defaults write com.apple.finder AppleShowAllFiles YES
# set mouse scroll acceleration
defaults write .GlobalPreferences com.apple.scrollwheel.scaling 0.3125
# Terminal defaults
/usr/libexec/PlistBuddy -c "Set :'Default Window Settings' Pro" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Startup Window Settings' Pro" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:shellExitAction 0" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:rowCount 40" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:columnCount 150" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowActiveProcessArgumentsInTitle 1" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowRepresentedURLPathInTitle 1" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowTTYNameInTitle 0" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowCommandKeyInTitle 0" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowDimensionsInTitle 0" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowActiveProcessInTitle 1" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :'Window Settings':Pro:ShowShellCommandInTitle 0" $HOME/Library/Preferences/com.apple.Terminal.plist
# Disable auto adjust screen brightness
/usr/libexec/PlistBuddy -c "Set :'Automatic Display Enabled' 0" /Library/Preferences/com.apple.iokit.AmbientLightSensor.plist
# Disable navigation with swipe gesture
defaults write 'Apple Global Domain' AppleEnableSwipeNavigateWithScrolls -integer 0
# Add login items
for item in Caffeine Flux 'Google Drive' 'Google Play Music Desktop Player' ShiftIt; do
./add_login_item.applescript "$item" "/Applications/$item.app" true
done
<file_sep>#!/usr/bin/env bash
mkdir -p ~/.ssh
mkdir -p ~/.virtualenvs
for file in .bash_profile .vimrc .ssh/config .pypirc; do
rm ~/$file
ln -s ~/git/config/$file ~/$file
done
file=".github_tokens.sh"
if [ ! -f ~/$file ]; then
cp ~/git/config/$file ~/$file
chmod 600 ~/$file
fi
<file_sep>#!/usr/bin/env bash
./accept_xcode_license.sh
./link_dot_files.sh
./update_bash.sh
./homebrew.sh
./osx_settings.sh
./set_up_python.sh
<file_sep>#!/usr/bin/env bash
source "$(dirname $0)/homebrew_utils.sh"
packages=(
# web dev
node
homebrew/php/php56
php56-pdo-pgsql
postgresql
# misc tools
coreutils
pandoc
macvim
git
git-review # used for gerrit
wget
gnupg
python
python3
enchant # needed as dependency for scikit-learn
aspell
bash-completion # _get_comp_words_by_ref needs newer version than default
redis
android-platform-tools
elixir
vitorgalvao/tiny-scripts/cask-repair # used to update casks
nmap
gnu-sed
sbt
# homebrew/fuse/ext2fuse # used for mounting ext filesystems
)
declare -A package_options=(['aspell']='--with-all-langs')
casks=(
shiftit # window snapping
caffeine # disable automatic sleep with toggle
limechat # irc client
telegram
keepassx
google-chrome
google-drive
firefox
flux # screen temperature adjuster
java
java-jdk-javadoc
intellij-idea
pycharm
webstorm
google-play-music-desktop-player
skype
filezilla
qbittorrent
vlc
kodi
steam
libreoffice
docker
kitematic
cockatrice
tunnelblick
usb-overdrive
handbrake
virtualbox
# karabiner is used to remap keys, but I'm using it to set the trackpad scroll
# direction to be opposite of the mouse with the following settings:
# - Karabiner Preferences > Change Key > Karabiner core settings >
# Exclude devices > Don't remap Apple's pointing devices
# - Karabiner Preferences > Change Key > Pointing Device >
# Reverse scrolling direction > Reverse Vertical Scrolling
# doesn't work in macOS sierra
# karabiner
# osxfuse-beta # used for mounting different filesystems
)
################################################################
ensure_homebrew_is_installed
status_update "Updating homebrew"
brew update
status_update "Installing packages"
package_count=${#packages[@]}
for (( i=0; i<${package_count}; i++ ))
do
ensure_installed "${packages[$i]}" ${package_options["${packages[$i]}"]}
echo -en "Processed $((i + 1))/${package_count}\r"
done
echo
status_update "Installing casks"
cask_count=${#casks[@]}
for (( i=0; i<${cask_count}; i++ ))
do
ensure_cask_installed "${casks[$i]}"
echo -en "Processed $((i + 1))/${cask_count}\r"
done
echo
status_update "Upgrading packages"
brew upgrade
status_update "Cleaning up packages"
brew cleanup
status_update "Cleaning up casks"
brew cask cleanup --outdated
cleanup_old_cask_versions
|
0795d81c37fcd1cb554f132ec28db940fc7ede13
|
[
"Markdown",
"Shell"
] | 11
|
Shell
|
schana/config
|
f46a872b0ceec49d735791a1ff599cb58aedb78a
|
48e357368eca9542bc34ca869b2763ab12ce3cba
|
refs/heads/master
|
<repo_name>gortazar/master-data-science-cloud-architectures<file_sep>/README.md
# master-data-science-cloud-architectures
Reources for Cloud Architectures in Master Data Science at URJC
<file_sep>/hadoop/hadoopuser-install.sh
#!/bin/bash
HADOOP_ROL=$1
HADOOP_MASTER_IP=$2
HADOOP_SLAVE_IP=$3
if [ "$HADOOP_ROL" = "master" ]; then
echo "Generating rsa key pair and injecting it into slave $HADOOP_SLAVE_IP"
ssh-keygen -t rsa -P ""
cat /home/hadoopuser/.ssh/id_rsa.pub >> /home/hadoopuser/.ssh/authorized_keys || exit 1
chmod 600 .ssh/authorized_keys
fi
if [ "$HADOOP_ROL" = "slave" ]; then
echo "Allowing PasswordAuthentication"
sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo service ssh restart
fi
echo "Downloading & extracting hadoop..."
wget http://apache.rediris.es/hadoop/common/hadoop-2.6.0/hadoop-2.6.0.tar.gz
tar xvf hadoop-2.6.0.tar.gz
mv hadoop-2.6.0 hadoop
echo "Hadoop downloaded & extracted"
echo "Setting environment variables needed by hadoop..."
echo 'export HADOOP_HOME=/home/hadoopuser/hadoop' >> .bashrc
echo 'export JAVA_HOME=/usr/lib/jvm/java-7-oracle' >> .bashrc
echo 'export PATH=$PATH:$HADOOP_HOME/bin:$HADOOP_HOME/sbin' >> .bashrc
sed -i 's|export JAVA_HOME=${JAVA_HOME}|export JAVA_HOME=/usr/lib/jvm/java-7-oracle|' /home/hadoopuser/hadoop/etc/hadoop/hadoop-env.sh
echo "Succesfully changed environment variables!"
cat > /home/hadoopuser/hadoop/etc/hadoop/core-site.xml <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>hadoop.tmp.dir</name>
<value>/home/hadoopuser/tmp</value>
<description>Temporary Directory.</description>
</property>
<property>
<name>fs.defaultFS</name>
<value>hdfs://$HADOOP_MASTER_IP:54310</value>
<description>Use HDFS as file storage engine</description>
</property>
</configuration>
EOF
if [ "$HADOOP_ROL" = "master" ]; then
cat > /home/hadoopuser/hadoop/etc/hadoop/mapred-site.xml <<-EOF
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>mapreduce.jobtracker.address</name>
<value>$HADOOP_MASTER_IP:54311</value>
<description>The host and port that the MapReduce job tracker runs
at. If "local", then jobs are run in-process as a single map
and reduce task.
</description>
</property>
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
<description>The framework for running mapreduce jobs</description>
</property>
</configuration>
EOF
fi
echo "Initializing hdfs..."
mkdir -p /home/hadoopuser/hadoop-data/hdfs/namenode || exit 1
mkdir -p /home/hadoopuser/hadoop-data/hdfs/datanode || exit 1
cat > hadoop/etc/hadoop/hdfs-site.xml <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>dfs.replication</name>
<value>2</value>
<description>Default block replication.
The actual number of replications can be specified when the file is created.
The default is used if replication is not specified in create time.
</description>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>/home/hadoopuser/hadoop-data/hdfs/namenode</value>
<description>Determines where on the local filesystem the DFS name node should store the name table(fsimage). If this is a comma-delimited list of directories then the name table is replicated in all of the directories, for redundance
</description>
</property>
<property>
<name>dfs.datanode.data.dir</name>
<value>/home/hadoopuser/hadoop-data/hdfs/datanode</value>
<description>Determines where on the local filesystem an DFS data node should store its blocks. If this is a comma-delimited list of directories, then data will be stored in all named directories, typically on different devices.
</description>
</property>
</configuration>
EOF
cat > /home/hadoopuser/hadoop/etc/hadoop/yarn-site.xml <<-EOF
<?xml version="1.0"?>
<configuration>
<!-- Site specific YARN configuration properties -->
<property>
<name>yarn.nodemanager.aux-services</name>
<value>mapreduce_shuffle</value>
</property>
<property>
<name>yarn.resourcemanager.scheduler.address</name>
<value>$HADOOP_MASTER_IP:8030</value>
</property>
<property>
<name>yarn.resourcemanager.address</name>
<value>$HADOOP_MASTER_IP:8032</value>
</property>
<property>
<name>yarn.resourcemanager.webapp.address</name>
<value>$HADOOP_MASTER_IP:8088</value>
</property>
<property>
<name>yarn.resourcemanager.resource-tracker.address</name>
<value>$HADOOP_MASTER_IP:8031</value>
</property>
<property>
<name>yarn.resourcemanager.admin.address</name>
<value>$HADOOP_MASTER_IP:8033</value>
</property>
</configuration>
EOF
if [ "$HADOOP_ROL" = "master" ]; then
cat > /home/hadoopuser/hadoop/etc/hadoop/slaves <<-EOF
$HADOOP_MASTER_IP
$HADOOP_SLAVE_IP
EOF
echo "Formating hdfs..."
./hadoop/bin/hdfs namenode -format
echo "hdfs initialized!"
fi
if [ "$HADOOP_ROL" = "master" ]; then
echo "To complete configuration run the following commands:"
echo "ssh-copy-id -i ~/.ssh/id_rsa.pub hadoopuser@$HADOOP_SLAVE_IP"
echo "Login to slave with the key. This command should not ask for a password.\nType exit when logged into the slave to return to master"
echo "ssh hadoopuser@$HADOOP_SLAVE_IP"
echo "On the Amazon AWS security group add a new rule and configure it as follows:"
echo "Select security group on instance details"
echo "Click on Edit, then on Add rule"
echo "Add the following rules, each line represents a rule, and fields are separated by commas"
echo "Custom TCP Rule, TCP, 54310, $HADOOP_SLAVE_IP/32"
echo "Custom TCP Rule, TCP, 8030-8033, $HADOOP_SLAVE_IP/32"
echo "Custom TCP Rule, TCP, 8088, Anywhere"
echo "Custom TCP Rule, TCP, 50010, Anywhere"
fi
<file_sep>/hadoop/install.sh
#!/bin/bash
# Check mandatory parameters
[ -z $HADOOP_ROL ] && { echo "Please set HADOOP_ROL environment variable to 'master' or 'slave' like this: export HADOOP_ROL=master"; exit 1; }
[ -z $HADOOP_MASTER_IP ] && { echo "Please set HADOOP_MASTER_IP environment variable with the private IP of the slave like this: export HADOOP_MASTER_IP=<ip>"; exit 1; }
[ -z $HADOOP_SLAVE_IP ] && { echo "Please set HADOOP_SLAVE_IP environment variable with the private IP of the slave like this: export HADOOP_SLAVE_IP=<ip>"; exit 1; }
# Install java from Oracle
echo "Installing Java..."
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install -y oracle-java7-installer || { echo "Could not install Java"; exit 1; }
sudo update-java-alternatives -s java-7-oracle
echo "Java installed!"
if [ "$HADOOP_ROL" = "slave" ]; then
echo "Enabling password authentication..."
sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config || exit 1
sudo service ssh restart || exit 1
echo "Password authentication enabled!"
fi
# Add hadoopgroup & hadoopuser.
echo "Adding group hadoopgroup and user hadoopuser..."
sudo addgroup hadoopgroup || exit 1
echo "I'm going to add the hadoopuser user."
echo "The command to add the user will ask for a password. Please choose a password, enter it twice, and leave the rest of the fields blank"
sudo adduser --ingroup hadoopgroup hadoopuser || exit 1
echo "I'm going to run some commands as user 'hadoopuser'. Please enter the password when prompted"
su -c "$PWD/hadoopuser-install.sh $HADOOP_ROL $HADOOP_MASTER_IP $HADOOP_SLAVE_IP" - hadoopuser
|
2e8228a46cab32327420bccfac58c3d82d97f576
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
gortazar/master-data-science-cloud-architectures
|
174f8c7d805547532bca9bc8f947514eb2905653
|
6da70dc9c5d4d6d5546acbd33d066b8bb4ad70d2
|
refs/heads/master
|
<repo_name>hwangJi-dev/project2<file_sep>/diaryProject/diaryProject/Sources/FriendsData.swift
//
// FriendsData.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class FriendsData: NSObject {
var userid: String = ""
var passwd: String = ""
var name: String = ""
var profileImg: String = ""
var statusMsg: String = ""
}
<file_sep>/diaryProject/diaryProject/Cell/myDiaryTableViewCell.swift
//
// myDiaryTableViewCell.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class myDiaryTableViewCell: UITableViewCell {
@IBOutlet var myTitle: UILabel!
@IBOutlet var writeDate: UILabel!
@IBOutlet var todaysStatus: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/diaryProject/diaryProject/Cell/FriendsInformation.swift
//
// FriendsInformation.swift
// diaryProject
//
// Created by 황지은 on 2020/06/22.
// Copyright © 2020 황지은. All rights reserved.
//
import Foundation
struct FreindsInformation{
var profileImg: String?
var profileName:String
var statusLabel:String
init(profileImg: String, profileName:String, statusLabel:String){
self.profileImg = profileImg
self.profileName = profileName
self.statusLabel = statusLabel
}
}
<file_sep>/diaryProject/diaryProject/VCs/mainViewController.swift
//
// mainViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class mainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private var diaryList:[diaryData] = Array()
@IBOutlet var mainTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mainTableView.delegate = self
mainTableView.dataSource = self
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
diaryList = []
self.downloadDataFromServer()
}
func downloadDataFromServer() ->Void {
let urlString: String = "http://condi.swu.ac.kr/student/M12/project2/friendsDiaryTable.php"
guard let requestURL = URL(string: urlString) else { return }
let request = URLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseError == nil else { print("Error: calling POST"); return; }
guard let receivedData = responseData else {
print("Error: not receiving Data"); return;
}
let response = response as! HTTPURLResponse
if !(200...299 ~= response.statusCode) { print("HTTP response Error!"); return }
do {
if let jsonData = try JSONSerialization.jsonObject (with: receivedData,
options:.allowFragments) as? [[String: Any]] {
for i in 0...jsonData.count-1 {
var newData: diaryData = diaryData()
var jsonElement = jsonData[i]
newData.userid = jsonElement["userid"] as! String
newData.title = jsonElement["title"] as! String //제목
newData.diaryDetail = jsonElement["diaryDetail"] as! String
newData.statusMsg = jsonElement["statusMsg"] as! String
newData.userName = jsonElement["userName"] as! String
newData.date = jsonElement["date"] as! String
//newData.openStatus = jsonElement["openStatus"] as! Bool
self.diaryList.append(newData)
}
DispatchQueue.main.async { self.mainTableView.reloadData() }
}
} catch { print("Error: Catch") }
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diaryList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! mainTableViewCell
let item = diaryList[indexPath.row]
cell.mainID.text = item.userid
cell.mainDate.text = "\(item.date)"
// cell.mainImg.image = UIImage(named: item.profileImg)
cell.mainStatus.text = item.statusMsg
cell.mainTitle.text = item.title
return cell
}
}
<file_sep>/diaryProject/diaryProject/VCs/myDiaryViewController.swift
//
// myDiaryViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
import CoreData
class myDiaryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var myTableView: UITableView!
var myDiary: [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myTableView.delegate = self
myTableView.dataSource = self
}
func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
//View가 보여질 때 자료를 DB에서 가져오도록 한다
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = self.getContext()
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MyDiary")
//로그인 아이디 별 내가 쓴 글 필터링
let filter = appDelegate.userId
let predicate = NSPredicate(format: "userid = %@", filter as! CVarArg)
fetchRequest.predicate = predicate
do{
myDiary = try context.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
self.myTableView.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return myDiary.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myDiary", for: indexPath) as! myDiaryTableViewCell
// Configure the cell...
let myDiaries = myDiary[indexPath.row]
cell.myTitle.text = myDiaries.value(forKey: "title")as? String
cell.todaysStatus.text = myDiaries.value(forKey: "status")as? String
return cell
}
}
<file_sep>/diaryProject/diaryProject/Cell/profileTableViewCell.swift
//
// profileTableViewCell.swift
// diaryProject
//
// Created by 황지은 on 2020/06/22.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class profileTableViewCell: UITableViewCell {
@IBOutlet var profileImage: UIImageView!
@IBOutlet var profileNameLabel: UILabel!
@IBOutlet var profileStatusMsg: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setProfileInformation(profileImg:String,profileName:String,profileStatus:String){
// friendsImg.image = UIImage(named: profileImg)
profileNameLabel.text = profileName
profileStatusMsg.text = profileStatus
profileImage.image = UIImage(named: profileImg)
}
}
<file_sep>/diaryProject/diaryProject/VCs/SignUpViewController.swift
//
// SignUpViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/06/22.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController,UITextFieldDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var textID: UITextField!
@IBOutlet var textPassword: UITextField!
@IBOutlet var textName: UITextField!
@IBOutlet var textStatus: UITextField!
@IBOutlet var labelStatus: UILabel!
@IBOutlet var textImgUrl: UILabel!
@IBOutlet var buttonCamera: UIButton!
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if !(UIImagePickerController.isSourceTypeAvailable(.camera)){
let alert = UIAlertController(title: "Error!", message: "카메라가 없습니다.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
buttonCamera.isEnabled = false //카메라 버튼 사용 금지시킴
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imageView.image = image
print(imageView.image!)
}
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.textID {
textField.resignFirstResponder()
self.textPassword.becomeFirstResponder()
}
else if textField == self.textPassword {
textField.resignFirstResponder()
self.textName.becomeFirstResponder()
}
else if textField == self.textName {
textName.resignFirstResponder()
self.textStatus.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
@IBAction func takePicture() {
let myPicker = UIImagePickerController()
myPicker.delegate = self
myPicker.allowsEditing = true
myPicker.sourceType = .camera
self.present(myPicker, animated: true, completion: nil)
}
@IBAction func selectFromAlbum() {
let mypicker = UIImagePickerController()
mypicker.delegate = self
mypicker.sourceType = .photoLibrary
self.present(mypicker, animated: true, completion: nil)
}
@IBAction func doSignUpBtn() {
if textID.text == "" {
labelStatus.text = "ID를 입력하세요."
}
else if textPassword.text == "" {
labelStatus.text = "Password를 입력하세요."
}
else if textName.text == "" {
labelStatus.text = "사용자 이름을 입력하세요."
}
else if textStatus.text == "" {
labelStatus.text = "상태메시지를 입력하세요."
}
guard let myImage = imageView.image else {
let alert = UIAlertController(title: "이미지를 선택하세요", message: "Save Failed!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true)
return
}
let myUrl = URL (string: "http://condi.swu.ac.kr/student/M12/project2/upload.php")
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField: "Content-Type")
guard let imageData = myImage.jpegData(compressionQuality:1) else {
return }
var body = Data()
var dataString = "--\(boundary)\r\n"
dataString += "Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"
dataString += "Content-Type: application/octet-stream\r\n\r\n"
if let data = dataString.data(using: .utf8) { body.append(data) }
// imageData 위 아래로 boundary 정보 추가
body.append(imageData)
dataString = "\r\n"
dataString += "--\(boundary)--\r\n"
if let data = dataString.data(using: .utf8) { body.append(data) }
request.httpBody = body
var imageFileName: String = ""
let semaphore = DispatchSemaphore(value: 0)
let session = URLSession.shared
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseError == nil else { print("Error: calling POST"); return; }
guard let receivedData = responseData else {
print("Error: not receiving Data")
return;
}
if let utf8Data = String(data: receivedData, encoding: .utf8) {
// 서버에 저장한 이미지 파일 이름
imageFileName = utf8Data
print(imageFileName)
semaphore.signal()
}
}
task.resume()
// 이미지 파일 이름을 서버로 부터 받은 후 해당 이름을 DB에 저장하기 위해 wait()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
let urlString: String = "http://condi.swu.ac.kr/student/M12/project2/insertUser.php"
guard let mrequestURL = URL(string: urlString) else {
return
}
request = URLRequest(url: mrequestURL)
request.httpMethod = "POST"
let restString:String = "id=" + textID.text! + "&password=" + textPassword.text! + "&name=" + textName.text! + "&profileImg=" + imageFileName + "&statusMsg=" + textStatus.text!
request.httpBody = restString.data(using: .utf8)
let session2 = URLSession.shared
let task2 = session2.dataTask(with: request){ (responseData, response, responseError) in
guard responseError == nil else {
print ("Error: Calling POST")
return
}
guard let receivedData = responseData else {
print("Error : not receiving Data")
return
}
if let utf8Data = String(data: receivedData, encoding: .utf8) {
DispatchQueue.main.async {
self.labelStatus.text = utf8Data
print(utf8Data)
}
}
}
task2.resume()
guard let writeVC = self.storyboard?.instantiateViewController(identifier: "write") as? writeViewController else {return}
writeVC.userId = textID.text
writeVC.userName = textName.text
}
func executeRequest(request: URLRequest) -> Void {
let session2 = URLSession.shared
let task2 = session2.dataTask(with: request){ (responseData, response, responseError) in
guard responseError == nil else {
print ("Error: Calling POST")
return
}
guard let receivedData = responseData else {
print("Error : not receiving Data")
return
}
if let utf8Data = String(data: receivedData, encoding: .utf8) {
DispatchQueue.main.async {
self.labelStatus.text = utf8Data
print(utf8Data)
}
}
}
task2.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/diaryProject/diaryProject/VCs/LoginViewController.swift
//
// LoginViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/06/22.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var loginUserid: UITextField!
@IBOutlet var loginPassword: UITextField!
@IBOutlet var loginStatusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.loginUserid {
textField.resignFirstResponder()
self.loginPassword.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
@IBAction func loginBtn() {
if loginUserid.text == "" {
loginStatusLabel.text = "ID를 입력하세요."
}
if loginPassword.text == "" {
loginStatusLabel.text = "비밀번호를 입력하세요."
}
let urlString: String = "http://condi.swu.ac.kr/student/M12/project2/loginUser.php"
guard let requestURL = URL(string: urlString) else {return}
self.loginStatusLabel.text = ""
var request = URLRequest(url: requestURL)
request.httpMethod = "POST"
let restString:String = "id=" + loginUserid.text! + "&password=" + loginPassword.text!
request.httpBody = restString.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: request){ (responseData, response, responseError) in
guard responseError == nil else {
print ("Error: Calling POST")
return
}
guard let receivedData = responseData else {
print("Error : not receiving Data")
return
}
do {
let response = response as! HTTPURLResponse
if !(200...299 ~= response.statusCode){
print("HTTP Error!")
return
}
guard let jsonData = try JSONSerialization.jsonObject(with: receivedData, options: .allowFragments) as? [String:Any] else {
print("JSON Serialization Error!")
return
}
guard let success = jsonData["success"] as? String else{
print("Error:PHP failure(success)")
return
}
if success == "YES" {
DispatchQueue.main.async {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.userId = self.loginUserid.text
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabView = storyboard.instantiateViewController(identifier: "tabView")
tabView.modalPresentationStyle = .fullScreen
self.present(tabView, animated: true, completion: nil)
}
}
else {
if let errMessage = jsonData["error"] as? String {
DispatchQueue.main.async {
self.loginStatusLabel.text = errMessage
}
}
}
}
catch{
print("Error: \(error)")
}
}
task.resume()
}
}
<file_sep>/diaryProject/diaryProject/VCs/FriendsProfileTableViewController.swift
//
// FriendsProfileTableViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/06/22.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class FriendsProfileTableViewController: UITableViewController {
private var profileList:[FriendsData] = Array()
private var myList:[FreindsInformation] = []
override func viewDidLoad() {
super.viewDidLoad()
profileList = []
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
setProfileList()
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
profileList = []
self.downloadDataFromServer()
}
func downloadDataFromServer() ->Void {
let urlString: String = "http://condi.swu.ac.kr/student/M12/project2/favoriteTable.php"
guard let requestURL = URL(string: urlString) else { return }
let request = URLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseError == nil else { print("Error: calling POST"); return; }
guard let receivedData = responseData else {
print("Error: not receiving Data"); return;
}
let response = response as! HTTPURLResponse
if !(200...299 ~= response.statusCode) { print("HTTP response Error!"); return }
do {
if let jsonData = try JSONSerialization.jsonObject (with: receivedData,
options:.allowFragments) as? [[String: Any]] {
for i in 0...jsonData.count-1 {
var newData: FriendsData = FriendsData()
var jsonElement = jsonData[i]
newData.userid = jsonElement["userid"] as! String
newData.name = jsonElement["name"] as! String //제목
newData.passwd = jsonElement["passwd"] as! String
newData.profileImg = jsonElement["profileImg"] as! String
newData.statusMsg = jsonElement["statusMsg"] as! String
self.profileList.append(newData)
}
DispatchQueue.main.async { self.tableView.reloadData() }
}
} catch { print("Error: Catch") }
}
task.resume()
}
//
private func setProfileList(){
//
let me = FreindsInformation(profileImg:"beauty_1585659625845.jpeg" , profileName: "황지은", statusLabel: "")
myList = [me]
//
}
//
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// if section == 0{
// return myList.count
// }
return profileList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) as! profileTableViewCell
let item = profileList[indexPath.row]
cell.profileImage.image = UIImage(named: item.profileImg)
print(item.profileImg)
cell.profileNameLabel.text = item.name
cell.profileStatusMsg.text = item.statusMsg
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "나의 친구 보기"
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/diaryProject/diaryProject/Cell/mainTableViewCell.swift
//
// mainTableViewCell.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class mainTableViewCell: UITableViewCell {
@IBOutlet var mainID: UILabel!
@IBOutlet var mainImg: UIImageView!
@IBOutlet var mainTitle: UILabel!
@IBOutlet var mainDate: UILabel!
@IBOutlet var mainStatus: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/README.md
# project2
모바일앱프로그래밍 iOS project2
<file_sep>/diaryProject/diaryProject/VCs/writeViewController.swift
//
// writeViewController.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
import CoreData
class writeViewController: UIViewController,UITextFieldDelegate {
var userId:String?
var userName:String?
var date:Date?
@IBOutlet var diaryTitle: UITextField!
@IBOutlet var todayStatus: UITextField!
@IBOutlet var diaryDetail: UITextView!
@IBOutlet var status: UILabel!
@IBOutlet var openToggle: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func savePressed(_ sender: UIButton) {
let context = self.getContext()
let entity = NSEntityDescription.entity(forEntityName: "MyDiary", in: context)
let object = NSManagedObject(entity: entity!, insertInto: context)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
object.setValue(diaryTitle.text, forKey: "title")
object.setValue(todayStatus.text, forKey: "status")
object.setValue(diaryDetail.text, forKey: "diaryDetail")
object.setValue(appDelegate.userId, forKey: "userid")
do {
try context.save()
print("saved")
print(object)
}
catch let error as NSError
{
print("Could not save \(error), \(error.userInfo)")
}
if diaryTitle.text == "" {
status.text = "제목을 입력하세요."
}
if todayStatus.text == "" {
status.text = "오늘의 기분을 입력하세요."
}
if diaryDetail.text == "" {
status.text = "일기 내용을 입력하세요."
}
// guard let signUpVC = self.storyboard?.instantiateViewController(identifier: "signUp") as? SignUpViewController else {return}
guard let userId = self.userId else {return}
guard let userName = self.userName else {return}
let urlString = URL(string: "http://condi.swu.ac.kr/student/M12/project2/insertDiary.php")
var request = URLRequest(url:urlString!)
request.httpMethod = "POST"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let myDate = formatter.string(from: Date())
object.setValue(myDate, forKey: "saveDate")
var restString:String = "userid=" + userId + "&title=" + diaryTitle.text!
restString += "&diaryDetail=" + diaryDetail.text!
restString += "&statusMsg=" + todayStatus.text!
restString += "&userName=" + userName
restString += "&date=" + myDate
request.httpBody = restString.data(using: .utf8)
executeRequest(request: request)
print(restString)
}
func executeRequest(request: URLRequest) -> Void {
let session2 = URLSession.shared
let task2 = session2.dataTask(with: request){ (responseData, response, responseError) in
guard responseError == nil else {
print ("Error: Calling POST")
return
}
guard let receivedData = responseData else {
print("Error : not receiving Data")
return
}
if let utf8Data = String(data: receivedData, encoding: .utf8) {
DispatchQueue.main.async {
self.status.text = utf8Data
print(utf8Data)
}
}
}
task2.resume()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
<file_sep>/diaryProject/diaryProject/Sources/diaryData.swift
//
// diaryData.swift
// diaryProject
//
// Created by 황지은 on 2020/07/05.
// Copyright © 2020 황지은. All rights reserved.
//
import UIKit
class diaryData: NSObject {
var userid: String = ""
var title: String = ""
var diaryDetail: String = ""
// var profileImg: String = ""
var statusMsg: String = ""
var userName: String = ""
var date: String = ""
// var openStatus: Bool = true
}
|
7dd5b2fb0e274ab202c98ca3127ed6c610918f7e
|
[
"Swift",
"Markdown"
] | 13
|
Swift
|
hwangJi-dev/project2
|
b2872b787aafba75746ad161f6049108f6639ecb
|
cb023da0e974a4652c9f2893de99086b9cbd735a
|
refs/heads/master
|
<file_sep>post '/issue_statuses/update_issue_closed' => 'issue_statuses#update_issue_closed'<file_sep>require 'redmine'
require 'rubygems'
require 'delayed_job'
require File.dirname(__FILE__) + '/lib/issue_closed.rb'
Redmine::Plugin.register :redmine_issue_closed do
name 'Redmine Issue Closed plugin'
author 'Equelli'
description 'This is a plugin for Redmine'
version '0.0.1'
project_module "issue_closed" do
permission :run_autoclose, { :issue => :update }
end
end<file_sep>= Issue_closed http://stillmaintained.com/edtsech/redmine_x_closed.png
v1.1.2
This redmine plugin closing issues a week after their "Resolving".
== Installing delayed_job:
To working plugin Redmine Issue Closed you need to install and start delayed_job. Delayed job is plugin for background processes.
In your terminal:
1) script/plugin install git://github.com/collectiveidea/delayed_job.git -r v2.0
(only v2.0 works with Rails 2.x)
2) script/generate delayed_job
rake db:migrate
3) create config/initializers/delayed_job_config.rb and add this code into it:
Delayed::Worker.backend = :active_record
silence_warnings do
Delayed::Job.const_set("MAX_ATTEMPTS", 3)
Delayed::Job.const_set("MAX_RUN_TIME", 7.days)
end
4) rake jobs:work
(for starting background processes)
If you have any problem regarding DelayedJobs, go to:
http://github.com/collectiveidea/delayed_job
== Installing Redmine Issues Closed on Redmine 0.9+ (tested on 1.2.1)
1) script/plugin install git://github.com/edtsech/redmine_x_closed.git
2) rake db:migrate_plugins
3) go to Admin -> Issue Statuses and set up plugin (select "resolved" & "closed" statuses)
== Installing Redmine Issues Closed on Redmine 0.8.*
1) Go to "Download" tab
2) Download "Redmineight" archive
3) Unpack archive to vendor/plugins
4) rake db:migrate_plugins
5) go to Admin -> Issue Statuses and set up plugin (select "resolved" & "closed" statuses)
== To turn off Redmine Issue Closed Plugin:
project/settings/ > Modules
<file_sep>module IssueClosed
module Hooks
class ControllerIssueHook < Redmine::Hook::ViewListener
def controller_issues_bulk_edit_after_save(context={})
@issue = context[:issue]
changed_attrs = context[:changed_attrs]
if module_enable? && changed_attrs.include?('status_id')
to_destroy_id = @issue.delayed_job_id
delayed_job_id = nil
if @issue.status.state == false
job = Delayed::Job.enqueue DelayedClose.new(@issue.id), 0, 7.days.from_now
delayed_job_id = job.id
end
@issue.delayed_job_id = delayed_job_id
@issue.save :callbacks => false
# in case of change closed to resolved dj could not exists
dj = Delayed::Job.find_by_id(to_destroy_id) unless to_destroy_id == nil
dj.destroy unless dj.nil?
end
end
def module_enable?
not (@issue.project.enabled_modules.detect { |enabled_module| enabled_module.name == 'issue_closed' }) == nil
end
end
end
end<file_sep>Rails.configuration.to_prepare do
require 'hooks/controller_issue_hook'
end
module IssueClosed
class DelayedClose < Struct.new(:issue_id)
def perform
issue = Issue.find issue_id
if issue.status.state == false
# add journal
bot_user = User.find_by_login(Setting.bot_login)
issue.init_journal(bot_user) unless bot_user.nil?
issue.status = IssueStatus.find_by_state true
issue.save
end
end
end
module IssueStatusesController
def self.included base
base.class_eval do
# alias_method :_index, :index unless method_defined? :_index
# def index
# _index
# render :template => 'issue_statuses/issue_closed_list' unless request.xhr?
# end
def update_issue_closed
(statuses = IssueStatus.all).each do |status|
case status.id
when params[:closed].to_i
status.state = true
when params[:resolved].to_i
status.state = false
else
status.state = nil
end
status.save!
end
redirect_to :action => :index
end
end
end
end
module MixinIssue
def self.included base
base.class_eval do
after_destroy :destroy_issue
private
def destroy_issue
Delayed::Job.destroy(delayed_job_id) if Delayed::Job.find_by_id(delayed_job_id) != nil
end
end
end
end
module IssuesController
def self.included base
base.class_eval do
alias_method :_update, :update unless method_defined? :_edit
def update
status_before_update = @issue.status
_update
if not (@issue.project.enabled_modules.detect { |enabled_module| enabled_module.name == 'issue_closed' }) == nil and \
status_before_update != @issue.status
to_destroy_id = @issue.delayed_job_id
delayed_job_id = nil
if @issue.status.state == false
job = Delayed::Job.enqueue DelayedClose.new(@issue.id), 0, 7.days.from_now
delayed_job_id = job.id
end
@issue.delayed_job_id = delayed_job_id
@issue.save :callbacks => false
# in case of change closed to resolved dj could not exists
dj = Delayed::Job.find_by_id(to_destroy_id) unless to_destroy_id == nil
dj.destroy unless dj.nil?
end
end
end
end
end
end
ActionDispatch::Callbacks.to_prepare do
begin
require_dependency 'application'
rescue LoadError
require_dependency 'application_controller'
end
IssueStatusesController.send :include, IssueClosed::IssueStatusesController
IssuesController.send :include, IssueClosed::IssuesController
Issue.send :include, IssueClosed::MixinIssue
end
<file_sep>class AddStateToIssueStatus < ActiveRecord::Migration
def self.up
add_column :issue_statuses, :state, :boolean
#include GLoc
#include Redmine::DefaultData::Loader
#puts l(:default_issue_status_resolved)
#IssueStatus.find_by_name(l(:default_issue_status_resolved)).toggle_attribute(:is_resolved)
end
def self.down
remove_column :issue_statuses, :state
end
end
|
c513d9f25a6a956871a2c3b3415c68855886036d
|
[
"RDoc",
"Ruby"
] | 6
|
Ruby
|
SnowdogApps/redmine_issue_closed
|
049e76c6bf31abe3ab7892cc79e9491c1b48421f
|
f0a3ce0a5a2f472b7bcb96148e1f1cab1512dbe3
|
refs/heads/master
|
<repo_name>Godfrey1989/JXC<file_sep>/src/main/java/com/gtt/repository/UserRepository.java
package com.gtt.repository;
import com.gtt.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User, Integer>,JpaSpecificationExecutor<User>{
@Query(value = "select * from t_user where user_name=?1",nativeQuery = true)
public User findByUserName(String userName);
}
<file_sep>/src/main/java/com/gtt/repository/RoleRepository.java
package com.gtt.repository;
import com.gtt.entity.Role;
import com.gtt.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface RoleRepository extends JpaRepository<Role, Integer>{
@Query(value = "select r.* from t_user u, t_role r, t_user_role ur where ur.user_id=u.id and ur.role_id=r.id and u.id=?1",nativeQuery = true)
public List<Role> findByUserId(Integer id);
}
<file_sep>/src/main/java/com/gtt/service/MenuService.java
package com.gtt.service;
import com.gtt.entity.Menu;
import java.util.List;
public interface MenuService {
public List<Menu> findByParentIdAndRoleId(int parentId, int roleId);
}
<file_sep>/src/main/java/com/gtt/service/UserRoleService.java
package com.gtt.service;
public interface UserRoleService {
public void deleteByUserId(Integer id);
}
<file_sep>/src/main/java/com/gtt/service/UserService.java
package com.gtt.service;
import apple.laf.JRSUIConstants;
import com.gtt.entity.Role;
import com.gtt.entity.User;
import org.springframework.data.domain.Sort;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
public interface UserService {
public User findByUserName(String userName);
public List<User> list(User user, Integer page, Integer pageSize, Sort.Direction direction, String...properties);
public Long getCount(User user);
public void save(User user);
public void delete(Integer id);
}
|
c638aad4d9cd15acf80051bc9131c0997e27890b
|
[
"Java"
] | 5
|
Java
|
Godfrey1989/JXC
|
898d612d9e4c7e059973ff262163de279ed1bfd6
|
aa8fa9f7b1cc09c8e252a031c497752fa5247f88
|
refs/heads/master
|
<file_sep>import React from 'react';
import Todo from './Todo'
const TodosList = (props) => {
let todos = props.todos
const todosList = todos.map((todo) => {
let id = todos.indexOf(todo)
console.log(todo)
return(
<Todo
id={id}
text={todo.text}
removeTodo={props.removeTodo}
/>
)
})
return (
<div className='todos-list'>
<ul>
{todosList}
</ul>
</div>
)
}
export default TodosList;<file_sep>LifeCycle Methods Lab by <NAME>
<file_sep>import React from 'react'
const Todo = (props) => {
return (
<li>
{props.text}<span></span><button id={`${props.id}`} onClick={props.removeTodo}>remove</button>
</li>
)
}
export default Todo;<file_sep>## Phases
- Mounting
1. Constructor
2. Render
3. ComponentDidMount
- Updating
1. Render
2. ComponentDidUpdate
- Unmounting
1. ComponentWillUnmount
|
1fbe208b208090f0232398d5ba462455dd9c7a5f
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
hupaulcamacho/lifecycle-methods-lab
|
bd6be1cfd9f84b6cfae7a92322ff2222f94874ce
|
94bfe303c9aba3404ec53b85a72e2dcc08a61921
|
refs/heads/master
|
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "citizenaction.h"
Koushin::CitizenAction::CitizenAction(Koushin::Citizen* citizen, QString action)
: Koushin::Action()
, m_citizen(citizen)
{
m_action = action;
}
Koushin::CitizenAction::~CitizenAction()
{
}
QMap<QString, Koushin::ActionProperties > Koushin::CitizenAction::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
actions.insert("addCondition", Koushin::ActionProperties(
QStringList() << QString("string"),
"Citizen: Adds a condition. Parameter: name of a condition"));
actions.insert("removeCondition", Koushin::ActionProperties(
QStringList() << "string",
"Citizen: Removes a condition. Parameter: name of a condition"));
return actions;
}
#include <kdebug.h>
bool Koushin::CitizenAction::execute()
{
if (m_action == "addCondition") {
Koushin::citizenCondition parameter;
if (!m_parameters.isEmpty() && (parameter = Koushin::Citizen::citizenConditionFromQString(m_parameters.first())))
return m_citizen->addCondition(parameter);
} else if (m_action == "removeCondition") {
Koushin::citizenCondition parameter;
if (!m_parameters.isEmpty() && (parameter = Koushin::Citizen::citizenConditionFromQString(m_parameters.first())))
return m_citizen->removeCondition(parameter);
} else {
kDebug() << "Undefined action called!";
}
return false; //action not parsed -> return false
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "playeraction.h"
#include "player.h"
#include "actionmanager.h"
Koushin::PlayerAction::PlayerAction(Player* recipient)
: Koushin::Action()
, m_recipient(recipient)
{
}
Koushin::PlayerAction::~PlayerAction()
{
}
QMap< QString, Koushin::ActionProperties> Koushin::PlayerAction::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
actions.insert("setGlobalTo", Koushin::ActionProperties(
QStringList() << "string" << "string",
"Player: overwrites a value. string=NameOfGlobal, string=NewValue "));
actions.insert("addToGlobal", Koushin::ActionProperties(
QStringList() << "string" << "string",
"Player: add a string to a global. string=NameOfGlobal, string=AdditionalContent"));
return actions;
}
bool Koushin::PlayerAction::execute()
{
if(m_action == "setGlobalTo") {
return m_recipient->getActionManager()->setGlobalParameterContent(m_parameters[0], m_parameters[1]);
} else if(m_action == "addToGlobal") {
return m_recipient->getActionManager()->addContentToGlobalParameter(m_parameters[0], m_parameters[1]);
} else {
kDebug() << "Unknown action " << m_action;
}
return false;
}
<file_sep>set(Koushin_SRCS
action.cpp
actionmanager.cpp
actionobject.cpp
actionparser.cpp
building.cpp
citizen.cpp
field.cpp
game.cpp
main.cpp
player.cpp
population.cpp
town.cpp
GUI/buildinginfowidget.cpp
GUI/constructionmenu.cpp
GUI/fielditem.cpp
GUI/resourceinfowidget.cpp
GUI/townwidget.cpp
GUI/gameview.cpp
)
add_subdirectory(TownEditor)
set(QT_USE_QTSCRIPTTOOLS TRUE)
set(CMAKE_CXX_FLAGS "-fexceptions")
kde4_add_executable(Koushin ${Koushin_SRCS})
target_link_libraries(Koushin ${KDE4_KDEUI_LIBS} ${KDEGAMES_LIBRARY} ${QT_QTSCRIPT_TOOLS_LIBRARY_RELEASE})
install(TARGETS Koushin ${INSTALL_TARGETS_DEFAULT_ARGS} )
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef FIELD_H
#define FIELD_H
#include "actionobject.h"
#include <QString>
#include "town.h"
#include <qgraphicsitem.h>
#include "GUI/fielditem.h"
#include <KConfigGroup>
class QGraphicsRectItem;
class QGraphicsWidget;
class QGraphicsItem;
namespace Koushin {
class Action;
class Building;
class Field : public ActionObject {
Q_OBJECT
public:
Field(Town* town = 0, FieldType type = plainField);
// Field() {Field(0);} //for using the marcro Q_DECLARE_METATYPE
Field(const Field& oldField);
//virtual functions from ActionObject:
virtual const actionObjectType getActionObjectType();
virtual const QString getLocal(QString name, QString additionalContent = QString());
const QMap<QString, ActionProperties> getPossibleActions();
//getters and setters:
void setType(FieldType type) {m_type = type;}
FieldType getType() const {return m_type;}
void setResource(ResourceType type, int newValue) {m_resources.insert(type, newValue);}
void addToResource(ResourceType type, int value) {value += getResource(type); m_resources.insert(type, value);}
int getResource(ResourceType type) {return m_resources.value(type, 0);}
void addBuilding(Building* building) {m_building = building;}
QMap<ResourceType, int > getResources() const {return m_resources;}
Building* getBuilding() const {return m_building;}
Town* getTown() const {return m_town;}
void setPos(QPoint pos) {m_fieldItem->setPos(pos);}
::KoushinGUI::FieldItem* getFieldItem () const {return m_fieldItem;}
void markField(QColor color = Qt::red) {
m_isMarked = true; m_fieldItem->setMarkColor(color); m_fieldItem->update(m_fieldItem->boundingRect());
}
void unmarkField() {m_isMarked = false; m_fieldItem->update(m_fieldItem->boundingRect());}
bool isMarked() const {return m_isMarked;}
static QString fieldTypeToQString(FieldType type);
static FieldType QStringToFieldType(QString string);
//actions for parser:
public Q_SLOTS:
bool gatherResource(ResourceType type, int value);
bool growResource(ResourceType type, int value);
private:
FieldType m_type;
Town* m_town;
QMap<ResourceType, int > m_resources;
Building* m_building;
::KoushinGUI::FieldItem* m_fieldItem;
bool m_isMarked;
};
}
// Q_DECLARE_METATYPE(Koushin::Field*)
#endif // FIELD_H
<file_sep>#include "editor.h"
#include "field.h"
#include <KDebug>
#include <kconfig.h>
#include <QListWidget>
#include <QString>
Koushin_TownEditor::Editor::Editor()
: m_fieldSize(1)
, m_type("plainField")
{
}
void Koushin_TownEditor::Editor::fieldClicked(Koushin_TownEditor::EditorField* field)
{
int x = field->boundingRect().topLeft().x() / m_fieldSize;
int y = field->boundingRect().topLeft().y() / m_fieldSize;
QString xString = QString("%1").arg(QString::number(x), 3, QLatin1Char('0'));
QString yString = QString("%1").arg(QString::number(y), 3, QLatin1Char('0'));
kDebug() << "Field clicked at " << xString << "," << yString;
if(m_type == "plainField")
field->setBrush(QBrush(Qt::white));
if(m_type == "fieldWithForest")
field->setBrush(QBrush(Qt::green));
if(m_type == "fieldWithRocks")
field->setBrush(QBrush(Qt::black));
if(m_type == "fieldWithWater")
field->setBrush(QBrush(Qt::blue));
if(m_type == "fieldNotUsable")
field->setBrush(QBrush(Qt::yellow));
field->update(field->boundingRect());
if(m_config) {
foreach(QString groupName, m_fieldTypes) {
if(groupName == m_type) {
KConfigGroup group = m_config->group(groupName);
group.writeEntry("field"+xString+yString, QString::number(x) + "," + QString::number(y));
group.config()->sync();
} else {
KConfigGroup group = m_config->group(groupName);
group.deleteEntry("field"+xString+yString);
group.config()->sync();
}
}
}
}
void Koushin_TownEditor::Editor::fieldTypeChanged(QListWidgetItem* item)
{
m_type = item->text();
}
#include "editor.moc"<file_sep>#ifndef KOUSHIN_TOWNEDITOR_FIELD_H
#define KOUSHIN_TOWNEDITOR_FIELD_H
#include <qgraphicsitem.h>
#include <KDebug>
namespace Koushin_TownEditor {
enum FieldType {
plainField = 0,
fieldWithForest,
fieldWithRocks,
fieldWithWater,
fieldWithBuilding,
fieldNotUsable,
numberOfFieldTypes
};
class Editor;
class EditorField : public QGraphicsRectItem {
public:
EditorField(int x, int y, int width, int height);
Editor* m_editor;
QString m_fieldType;
void mousePressEvent(QGraphicsSceneMouseEvent* event);
static QString fieldTypeToQString(FieldType type);
static FieldType QStringToFieldType(QString string);
};
}
#endif //KOUSHIN_TOWNEDITOR_FIELD_H<file_sep>set(Koushin_TownEditor_SRCS
main.cpp
editor.cpp
field.cpp
)
# set(QT_USE_QTSCRIPTTOOLS TRUE)
# set(CMAKE_CXX_FLAGS "-fexceptions")
kde4_add_executable(Koushin_TownEditor ${Koushin_TownEditor_SRCS})
target_link_libraries(Koushin_TownEditor ${KDE4_KDEUI_LIBS} ${KDEGAMES_LIBRARY})
install(TARGETS Koushin_TownEditor ${INSTALL_TARGETS_DEFAULT_ARGS} )
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "resourceinfowidget.h"
#include <QLabel>
#include <KDebug>
#include <QResizeEvent>
KoushinGUI::ResourceInfoWidget::ResourceInfoWidget(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
, m_label(new QLabel("Resources:\tWood: 0\tStone: 0\tRice: 0", this))
{
// setGeometry(0,0,m_label->minimumSizeHint().width(), m_label->minimumSizeHint().height());
}
KoushinGUI::ResourceInfoWidget::~ResourceInfoWidget()
{
}
void KoushinGUI::ResourceInfoWidget::updateInfos(QList< Koushin::Resource* > resources)
{
QString newText("Resources:\n");
foreach(Koushin::Resource* res, resources) {
if(res->type == Koushin::ResourceWood)
newText += "Wood: " + QString("%1").arg(res->amount) + "\t";
if(res->type == Koushin::ResourceStone)
newText += "Stone: " + QString("%1").arg(res->amount) + "\t";
if(res->type == Koushin::ResourceRice)
newText += "Rice: " + QString("%1").arg(res->amount) + "\t";
}
m_label->setText(newText);
// m_label->update();
// updateGeometry();
// setGeometry(0,0,m_label->sizeHint().width(), m_label->sizeHint().height());
}
void KoushinGUI::ResourceInfoWidget::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "constructionmenu.h"
#include <QListWidget>
#include <QListWidgetItem>
#include <QResizeEvent>
#include <QPushButton>
#include <KDebug>
#include <qgraphicsscene.h>
#include <QGraphicsView>
KoushinGUI::ConstructionMenu::ConstructionMenu(QMap<QString, QString> buildings, QWidget* parent)
: QWidget(parent)
, m_list(new QListWidget(this))
, m_okButton(new QPushButton("Construct selected building", this))
, m_paintRange(QRect())
{
m_okButton->setDisabled(true);
setPossibleBuildings(buildings);
connect(m_list, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(listitemSelected(QListWidgetItem*)));
connect(m_okButton, SIGNAL(clicked(bool)), this, SLOT(okButtonClicked()));
}
KoushinGUI::ConstructionMenu::~ConstructionMenu()
{
}
void KoushinGUI::ConstructionMenu::setPossibleBuildings(QMap< QString, QString > possibleBuildings)
{
m_buildings = possibleBuildings;
m_list->clear();
foreach(QString name, possibleBuildings.keys()) {
m_list->addItem(name);
}
}
void KoushinGUI::ConstructionMenu::resizeEvent(QResizeEvent* event)
{
QSize size = event->size();
QSize buttonSize = m_okButton->minimumSizeHint();
m_okButton->setGeometry((size.width() - buttonSize.width())/2, size.height()*3/4, buttonSize.width(), buttonSize.height());;
m_list->resize(size.width(), size.height()*3/4);
m_list->setSelectionMode(QAbstractItemView::SingleSelection);
QWidget::resizeEvent(event);
}
void KoushinGUI::ConstructionMenu::listitemSelected(QListWidgetItem* item)
{
if(item->text() != "")
m_okButton->setEnabled(true);
}
void KoushinGUI::ConstructionMenu::okButtonClicked()
{
emit buildingChosen(m_buildings.value(m_list->selectedItems().first()->text()));
}
void KoushinGUI::ConstructionMenu::setPaintRange(QRect rect)
{
m_paintRange = rect;
}
void KoushinGUI::ConstructionMenu::showEvent(QShowEvent* event)
{
QRect newRect = QRect(pos(), QSize(180,120));
if(newRect.right() > m_paintRange.right()) {
newRect.moveRight(m_paintRange.right());
}
if(newRect.bottom() > m_paintRange.bottom()) {
newRect.moveBottom(m_paintRange.bottom());
}
setGeometry(newRect);
QWidget::showEvent(event);
}
#include "constructionmenu.moc"<file_sep>set (koushin_TOWNS
town.config
)
set (koushin_TOWN_IMAGES
landscape.jpg
)
install(FILES ${koushin_TOWNS} ${koushin_TOWN_IMAGES} DESTINATION ${DATA_INSTALL_DIR}/koushin/data/towns)
<file_sep>#include <ctime>
#include <QMap>
// #include <QGraphicsScene>
#include <KAboutData>
#include <KApplication>
#include <KCmdLineArgs>
#include <KConfigGroup>
#include <KConfig>
#include <KStandardDirs>
#include <KMainWindow>
#include "actionmanager.h"
#include "actionparser.h"
#include "building.h"
#include "citizen.h"
#include "player.h"
#include "town.h"
#include <kdebug.h>
#include "GUI/townwidget.h"
#include <QDir>
#include <QStringList>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsView>
#include <QObject>
#include <QDockWidget>
#include <QListWidget>
#include <QVBoxLayout>
#include "GUI/resourceinfowidget.h"
#include <QPushButton>
#include "game.h"
#include "GUI/buildinginfowidget.h"
#include <QToolBar>
#include <qglobal.h> //for Q_WS_X11
#include "GUI/constructionmenu.h"
#include "GUI/constructionmenu.h"
#include "GUI/gameview.h"
static const char description[] =
I18N_NOOP("A round based strategy game.");
static const char version[] = "0.2";
//0.1: the start
//0.2: create buildings, draw graphical map, parse first actions, introduce town editor
int main(int argc, char** argv)
{
KAboutData about("Koushin", 0, ki18n("Koushin"), version, ki18n(description), KAboutData::License_GPL, ki18n("(C) 2010 <NAME>"), KLocalizedString(), 0, "<EMAIL>");
about.addAuthor(ki18n("<NAME>"), KLocalizedString(), "<EMAIL>");
KCmdLineArgs::init(argc, argv, &about);
#ifdef Q_WS_X11
QApplication::setGraphicsSystem("raster");
#endif //Q_WS_X11
KApplication app;
qsrand(std::time(0));
Koushin::Game* game = new Koushin::Game;
game->addPlayer("Felix");
Koushin::Player* tester = game->getPlayers().first();
KStandardDirs stdDirs;
QString townConfigFile = stdDirs.findResource("data", "koushin/data/towns/town.config");
Koushin::Town* town = new Koushin::Town(tester, new KConfig(townConfigFile));
///@todo later: prefer building downloaded or created by the user (in ~/.kde4/share/apps/Koushin/...) :
QMap<QString, QString> buildings;
foreach(QString dirString, stdDirs.resourceDirs("data")) {
QDir dir(dirString + "koushin/data/buildings/");
dir.setNameFilters(QStringList() << "*.config");
foreach(QString entry, dir.entryList()) {
KConfig config(dir.path() + "/" + entry);
KConfigGroup general(&config, "general");
buildings.insert(general.readEntry("name", QString()), dir.path() + "/" + entry);
}
}
tester->setBuildingList(buildings); ///@todo should be part of the game instead of the player
KMainWindow* window = new KMainWindow;
window->setMinimumSize(700,500);
window->show();
KoushinGUI::GameView* gameView = new KoushinGUI::GameView;
window->setCentralWidget(gameView);
gameView->showTownView(tester->getTowns().first());
gameView->changePlayer(tester);
window->addToolBar(Qt::BottomToolBarArea, new QToolBar()); //draw toolbar to resize the gameView
game->startRound();
return app.exec();
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "fielditem.h"
#include "field.h"
#include "GUI/townwidget.h"
#include <qpainter.h>
#include <KDebug>
#include <building.h>
#include <player.h>
#include "buildinginfowidget.h"
#include <QTextItem>
// #include <QGraphicsSceneMouseEvent>
KoushinGUI::FieldItem::FieldItem(Koushin::Field* field)
: m_field(field)
, m_textItem(new QGraphicsTextItem())
, m_markColor(Qt::red)
{
setParentItem(field->getTown()->getTownWidget());
}
void KoushinGUI::FieldItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
if(m_field->getType() == Koushin::plainField)
painter->setPen(QPen());
else
painter->setPen(QPen(Qt::NoPen));
if(m_field->getType() == Koushin::fieldWithForest)
painter->setBrush(QBrush(Qt::green));
if(m_field->getType() == Koushin::fieldWithBuilding)
painter->setBrush(QBrush(Qt::white));
painter->setOpacity(0.3);
painter->drawRect(0, 0, 1, 1);
if(m_field->getType() == Koushin::fieldWithBuilding && m_field->getBuilding()) {
painter->setPen(QPen());
painter->setOpacity(1.0);
painter->drawEllipse(0,0,1,1);
if(m_field->getBuilding()->getAge() < 0)
m_textItem->setPlainText(QString("%1").arg(-m_field->getBuilding()->getAge()));
else
m_textItem->setPlainText(m_field->getBuilding()->getName());
m_textItem->setScale(1 / m_textItem->boundingRect().width());
m_textItem->setPos(0, 0.5 - m_textItem->boundingRect().height()/(2*m_textItem->boundingRect().width()));
m_textItem->setParentItem(this);
}
if(m_field->isMarked()) {
painter->setOpacity(0.5);
painter->setBrush(QBrush(m_markColor));
painter->setPen(QPen());
painter->drawRect(0,0,1,1);
}
}
QRectF KoushinGUI::FieldItem::boundingRect() const
{
return QRectF(0.0, 0.0, 1.0, 1.0);
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to
the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ACTIONPARSER_H
#define ACTIONPARSER_H
#include <QMultiMap>
#include <QPair>
#include <QString>
#include <QList>
#include <KConfigGroup>
class KConfig;
namespace Koushin {
class Building;
class Field;
class Player;
class ActionObject;
class ActionManager;
class Action;
class ActionOwner;
class Player;
class Town;
/**
* @class ActionParser
* @brief This class interprets the tasks configuration and creates a appropriate Action.
*
* This class handles all string interpretation work. It is pure static. So nothing is stored here.
*
* The configuration should contain a group with:
* \code
* [tasks][globals]
* VarName=10
* Var2=100-#VarName#
*
* [tasks][conditions]
* myCondition=task1->task2
*
* [tasks][task1]
* recipient=player(current)
* action=setGlobalTo(VarName, 50)
* priority=20
*
* [tasks][task2]
* recipient=town()
* action=doSomething(para1, #Var2#)
*
* \endcode
* In this example two actions are defined: \c task1 and \c task2. \c task2 use the \b global \c Var2 to calculate his second parameter. \c Var2 itself contains the global \c VarName. At parsing time the value of \c Var2 is <tt>100-10=90</tt>.
*
* The condition \c myConditioin means, that \c task2 is only executed, if \c task1 succeeded. But \c task2 overwrite the global with the value \c 50. So at run time \c task2 is called with <tt>Var2 = 100-50=50</tt>, not with \c 90.
*
**/
class ActionParser {
public:
/**
* @brief This function creats all Action objects given in the "tasks" configuration group.
* This function also adds all conditions to the Action. So the Action is ready to use.
*
* @param tasksGroup This configuration group should contain all actions, so pass the whole "tasks" group to this function.
*
* @param newOwner The owner must be ActionObject and is neseccary to find the propper recipient.
*
* @param currentRound The round the Action is created.
*
* @param selectedGroup It is possible to choose only on action that should be created from all found actions. The default is an empty QString, that means all actions will be created.
*
* @return QList<Action* > The list containing all actions from the configuration.
**/
static QList<Action* > createActionsFromConfig(KConfigGroup* tasksGroup, Koushin::ActionObject* newOwner, int currentRound, QString selectedGroup = QString());
/**
* @brief This function finds the recipients.
* It is possible to have multiple recipients, e.g. all town containing a port.
*
* @param configLine The configuration line discribing the recipient/s.
*
* @param owner Because the owner is not stored in this static class you have to give the owner again, to find the appropriate recipient.
*
* @return QList<ActionObject* > The list of all recipients. This list can be empty.
**/
static QList<ActionObject* > parseRecipient(const QString& configLine, ActionObject* owner);
/**
* @brief This function just adds all given parameters to the manager.
* @todo remove this function, because here is nothing to parse
*
* @param parameterList List of all parameters.
*
* @param manager The manager who stores the parameters.
*
* @return bool Returns true when function succeeded (everytime true).
**/
static bool parseGlobals(const KConfigGroup& parameterList, ActionManager* manager);
/**
* @brief This function tries to find the wanted player for the recipient.
* \n If the owner is a Building the following parameters are known:
* - current (standard) -- the player constructed the Building
* If the owner is a Field the following parameters are known:
* - current (standard) -- the player owning the town the field belongs to
* If the owner is a Town the following parameters are known:
* - current (standard) -- the player owning the town
* If the owner is a Player the following parameters are known:
* - current (standard) -- the player itself
*
* @param parameters The list of the parameters to choose the player.
*
* @param owner For some parameters it is nessecary to know the owner (like for "current").
*
* @return QList<:Player* > All players fitting in the given parameters.
**/
static QList<Player* > findPlayers(QStringList parameters, ActionObject* owner);
/**
* @brief This function tries to find the wanted town for the recipient.
* \n If the owner is a Building the following parameters are knwon:
* - current (standard) -- the town the Building belongs to
* If the owner is a Field the following parameters are known:
* - current (standard) -- the town the field belongs to
* If the owner is a Town the following parameters are known:
* - current (standard) -- the town itslef
* If the owner is a Player the following parameters are known:
*
* @param parameters The list of the parameters to choose the town.
*
* @param owner For some parameters it is nessecary to know the owner (like for "current").
*
* @return QList<:Town* > All towns fitting in the given parameters.
**/
static QList<Town* > findTowns(QStringList parameters, ActionObject* owner, QList<Player* > players);
/**
* @brief This function tries to find the wanted building for the recipient.
* \n If the owner is a Building the following parameters are knwon:
* - current (standard) -- the building itself
* If the owner is a Field the following parameters are known:
* - current (standard) -- the building on the field (if there is one)
* If the owner is a Town the following parameters are known: (none)
* If the owner is a Player the following parameters are known: (none)
*
* @param parameters The list of the parameters to choose the building.
*
* @param owner For some parameters it is nessecary to know the owner (like for "current").
*
* @return QList<:Player* > All buildings fitting in the given parameters.
**/
static QList<Building* > findBuildings(QStringList parameters, ActionObject* owner, QList<Town* > towns);
/** @brief This function tries to find the wanted fields for the recipient.
* \n If the owner is a Building the following parameters are knwon:
* - current (standard) -- the field on which the building stands
* If the owner is a Field the following parameters are known:
* - current (standard) -- the field itself
* If the owner is a Town the following parameters are known: (none)
* If the owner is a Player the following parameters are known: (none)
*
* @param parameters The list of the parameters to choose the fields.
*
* @param owner For some parameters it is nessecary to know the owner (like for "current").
*
* @return QList<:Player* > All fields fitting in the given parameters.
**/
static QList<Field* > findFields(QStringList parameters, ActionObject* owner, QList<Town* > towns);
/**
* @brief This functions separates a function name and his parameter.
*
* @param string The line to separate in the form "functionName(para1, para2,...)".
*
* @return QPair< QString, QStringList > The name a all parameters as list.
**/
static QPair< QString, QStringList > separateNameAndParameters(QString string);
/**
* @brief This function adds all requirements to the actions.
*
* @param conditionStrings The list of all conditions.
*
* @param actions All actions as a pair of name and pointer.
*
* @return void
**/
static void addRequirementsToActions(QStringList conditionStrings, QMap<QString, Action* > actions);
/**
* @brief This function reads the round limits and prepares the Action.
*
* @param action The configuration of this Action will be changes.
*
* @param config From this configuration group the parameters are read.
*
* @param currentRount the current round to calculate the right round limitations
*
* @return void
**/
static void setRoundLimit(Action* action, KConfigGroup* config, int currentRound);
/**
* @brief This function creates a list of open field actions.
* The actions are read from the \c fieldtasks group. If the building level is zero, the start number of free fields is used, else the number resulting from <tt>(int)(level*newFieldsPerLevel+startNumber)-stillCreatedActions</tt> is used.
*
* This function also sets the right number of the created actions for the building and adds the open field action to the list of the building.
*
* @param config The whole configuration for the building. The whole configuration is nessecary, because the number of actiones can be found in the \c general group.
*
* @return void
**/
static void createOpenFieldActions(KConfigGroup* config, Koushin::Building* building);
};
}
#endif // ACTIONPARSER_H
<file_sep>#include <KApplication>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KMainWindow>
#include <KStandardDirs>
#include <KConfigGroup>
#include <QGraphicsView>
#include <qgraphicsitem.h>
#include <QObject>
#include <KDebug>
#include <QListWidget>
#include "editor.h"
#include "field.h"
#include <QDockWidget>
int main(int argc, char** argv) {
KAboutData about("Koushin_TownEditor", 0, ki18n("Koushin Town Editor"), "0.1", ki18n("Town editor for Koushin"), KAboutData::License_GPL, ki18n("(C) 2010 <NAME>"), KLocalizedString(), 0, "<EMAIL>");
about.addAuthor(ki18n("<NAME>"), KLocalizedString(), "<EMAIL>");
KCmdLineArgs::init(argc, argv, &about);
KApplication app;
KMainWindow* window = new KMainWindow;
KStandardDirs dirs;
QString fileName = dirs.findResource("data", "koushin/data/towns/town.config");
KConfig* config = new KConfig(fileName);
KConfigGroup imageGroup = config->group("Image");
QString imageName = imageGroup.readEntry("image", QString());
QString imageFile = dirs.findResource("data", "koushin/data/towns/" + imageName);
QGraphicsView* view = new QGraphicsView;
QGraphicsScene* scene = new QGraphicsScene;
QGraphicsPixmapItem* image = new QGraphicsPixmapItem(imageFile);
scene->addItem(image);
view->setScene(scene);
view->fitInView(image->boundingRect());
Koushin_TownEditor::Editor* editor = new Koushin_TownEditor::Editor;
int fieldsHorizontal = imageGroup.readEntry("fieldsHorizontal", int(-1));
int fieldsVertical = imageGroup.readEntry("fieldsVertical", int(-1));
int fieldSize = 1;
if(fieldsHorizontal + fieldsVertical == -2) {
fieldsHorizontal = 10;
fieldSize = image->boundingRect().width() / fieldsHorizontal;
fieldsVertical = image->boundingRect().height() / fieldSize;
} else if(fieldsHorizontal == -1) {
fieldSize = image->boundingRect().height() / fieldsVertical;
fieldsHorizontal = image->boundingRect().width() / fieldSize;
} else if(fieldsVertical == -1) {
fieldSize = image->boundingRect().width() / fieldsHorizontal;
fieldsVertical = image->boundingRect().height() / fieldSize;
} else {
fieldSize = qMin(image->boundingRect().width() / fieldsHorizontal, image->boundingRect().height() / fieldsVertical);
}
editor->m_fieldSize = fieldSize;
for(int i = 0; i < fieldsHorizontal; ++i) {
for(int j = 0; j < fieldsVertical; ++j) {
Koushin_TownEditor::EditorField* rect = new Koushin_TownEditor::EditorField(i*fieldSize, j*fieldSize, fieldSize, fieldSize);
rect->m_editor = editor;
rect->setOpacity(0.2);
rect->setBrush(QBrush(Qt::cyan));
scene->addItem(rect);
}
}
QStringList dataDirs = dirs.findDirs("data", "");
QString homeDir;
foreach(QString dir, dataDirs)
if(dir.contains("/home/")) homeDir = dir;
kDebug() << "home dir " << homeDir;
KConfig* newConfig = new KConfig(homeDir + "koushin/data/towns/town.config");
KConfigGroup newImageGroup = newConfig->group("Image");
foreach(QString key, imageGroup.keyList())
newImageGroup.writeEntry(key, imageGroup.readEntry(key, QString()));;
newConfig->sync();
KConfigGroup* fieldGroup = new KConfigGroup(newConfig->group("fields"));
// KConfigGroup* forstGroup = new KConfigGroup(fieldGroup->group("forestField"));
editor->m_config = fieldGroup;
window->setCentralWidget(view);
QStringList fieldTypes = QStringList() << "plainField" << "fieldWithForest" << "fieldWithRocks" << "fieldWithWater" << "fieldNotUsable";
QListWidget* list = new QListWidget;
list->addItems(fieldTypes);
editor->m_fieldTypes = fieldTypes;
list->setSelectionMode(QAbstractItemView::SingleSelection);
QObject::connect(list, SIGNAL(itemClicked(QListWidgetItem*)), editor, SLOT(fieldTypeChanged(QListWidgetItem*)));
QDockWidget* rightWidget = new QDockWidget;
rightWidget->setWidget(list);
window->addDockWidget(Qt::RightDockWidgetArea, rightWidget);
window->show();
return app.exec();
}<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef TOWNWIDGET_H
#define TOWNWIDGET_H
#include <QGraphicsItem>
#include <QMap>
#include <QPoint>
class KConfig;
class QGraphicsSceneMouseEvent;
static const int fieldNumber = 15;
namespace Koushin {
class Building;
}
namespace KoushinGUI {
class TownWidget : public QObject, public QGraphicsItem {
Q_OBJECT
Q_INTERFACES(QGraphicsItem)
public:
TownWidget(QGraphicsItem* parent = 0);
virtual ~TownWidget();
QRectF boundingRect() const;
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0);
// void sendSignalTownClicked(QPoint point) {emit townClicked(point);}
void updateTownPixmap(KConfig* config);
protected:
// void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
// void mousePressEvent(QGraphicsSceneMouseEvent* event);
Q_SIGNALS:
void townClicked(QPoint point);
private:
QPixmap* m_townPixmap;
QRect m_boundingRect;
QRect m_portionRect;
};
}
#endif // TOWNWIDGET_H
<file_sep>#include "field.h"
#include "editor.h"
#include <KDebug>
Koushin_TownEditor::EditorField::EditorField(int x, int y, int width, int height)
: QGraphicsRectItem(x,y,width,height)
, m_editor(0)
, m_fieldType("plainField")
{
}
void Koushin_TownEditor::EditorField::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if(m_editor)
m_editor->fieldClicked(this);
QGraphicsRectItem::mousePressEvent(event);
}
QString Koushin_TownEditor::EditorField::fieldTypeToQString(Koushin_TownEditor::FieldType type)
{
if(type == Koushin_TownEditor::plainField)
return "plainField";
if(type == Koushin_TownEditor::fieldWithBuilding)
return "fieldWithBuilding";
if(type == Koushin_TownEditor::fieldWithForest)
return "fieldWithForest";
if(type == Koushin_TownEditor::fieldWithRocks)
return "fieldWithRocks";
if(type == Koushin_TownEditor::fieldWithWater)
return "fieldWithWater";
if(type == Koushin_TownEditor::fieldNotUsable)
return "fieldNotUsable";
return "";
}
Koushin_TownEditor::FieldType Koushin_TownEditor::EditorField::QStringToFieldType(QString string)
{
kDebug() << string;
if(string == "fieldWithBuilding")
return Koushin_TownEditor::fieldWithBuilding;
if(string == "fieldWithForest")
return Koushin_TownEditor::fieldWithForest;
if(string == "fieldWithRocks")
return Koushin_TownEditor::fieldWithRocks;
if(string == "fieldWithWater")
return Koushin_TownEditor::fieldWithWater;
if(string == "fieldNotUsable")
return Koushin_TownEditor::fieldNotUsable;
return Koushin_TownEditor::plainField;
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CONSTRUCTIONMENU_H
#define CONSTRUCTIONMENU_H
#include <QMap>
#include <QString>
#include <QWidget>
#include <QList>
#include <qevent.h>
class QListWidgetItem;
class QListWidget;
class QResizeEvent;
class QPushButton;
namespace KoushinGUI {
class ConstructionMenu : public QWidget {
Q_OBJECT
public:
ConstructionMenu(QMap<QString, QString> possibleBuildings, QWidget* parent = 0);
virtual ~ConstructionMenu();
void setPossibleBuildings(QMap<QString, QString> possibleBuildings);
void setPaintRange(QRect rect);
protected:
void resizeEvent(QResizeEvent* event);
void showEvent(QShowEvent* event);
Q_SIGNALS:
void buildingChosen(QString buildingConfig);
public Q_SLOTS:
void listitemSelected(QListWidgetItem* item);
void okButtonClicked();
private:
QListWidget* m_list;
QMap<QString, QString> m_buildings; //this map contains building name and the config file (/absolutePath/fileName.config)
QPushButton* m_okButton;
QRect m_paintRange;
};
}
#endif // CONSTRUCTIONMENU_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "townwidget.h"
#include <QBrush>
#include <QColor>
#include <QGraphicsRectItem>
#include <QGraphicsLineItem>
#include <QGraphicsSceneMouseEvent>
#include "building.h"
#include "field.h"
#include <QGraphicsScene>
#include <KStandardDirs>
KoushinGUI::TownWidget::TownWidget(QGraphicsItem* parent)
: QGraphicsItem(parent)
, m_townPixmap(0)
, m_boundingRect(0, 0, fieldNumber, fieldNumber)
, m_portionRect(m_boundingRect)
{
}
KoushinGUI::TownWidget::~TownWidget()
{
}
QRectF KoushinGUI::TownWidget::boundingRect() const
{
return m_boundingRect;
}
#include <KDebug>
#include <qpainter.h>
#include <kconfig.h>
void KoushinGUI::TownWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
if(m_townPixmap) {
painter->drawPixmap(m_boundingRect, *m_townPixmap, m_portionRect);
}
}
void KoushinGUI::TownWidget::updateTownPixmap(KConfig* config)
{
if(m_townPixmap) {
delete m_townPixmap;
m_boundingRect = QRect(0,0,fieldNumber,fieldNumber);
m_townPixmap = 0; //set Pointer to 0 if something happens with creating a new QPixmap
}
//open file:
KStandardDirs dir;
KConfigGroup imageGroup = config->group("Image");
//read file:
QString imageName = imageGroup.readEntry("image", QString());
QString fileName = dir.findResource("data", "koushin/data/towns/" + imageName);
if(fileName.isEmpty()) return; //do not create pixmap if file not found
//read parameters for rendering:
int fieldsHorizontal = imageGroup.readEntry("fieldsHorizontal", int(-1));
int fieldsVertical = imageGroup.readEntry("fieldsVertical", int(-1));
m_townPixmap = new QPixmap(fileName);
if(m_townPixmap->height() + m_townPixmap->width() == 0) {//empty image
m_townPixmap = 0;
return;
}
//use proper standard paremters
int fieldSize = 1;
if(fieldsHorizontal + fieldsVertical == -2) {
fieldsHorizontal = fieldNumber;
fieldSize = m_townPixmap->width() / fieldsHorizontal;
fieldsVertical = m_townPixmap->height() / fieldSize;
} else if(fieldsHorizontal == -1) {
fieldSize = m_townPixmap->height() / fieldsVertical;
fieldsHorizontal = m_townPixmap->width() / fieldSize;
} else if(fieldsVertical == -1) {
fieldSize = m_townPixmap->width() / fieldsHorizontal;
fieldsVertical = m_townPixmap->height() / fieldSize;
} else {
fieldSize = qMin(m_townPixmap->width() / fieldsHorizontal, m_townPixmap->height() / fieldsVertical);
}
// m_boundingRect = QRect(3, 3, 10, 10);
m_boundingRect = QRect(0, 0, fieldsHorizontal, fieldsVertical);
m_portionRect = QRect(0, 0, fieldSize*fieldsHorizontal, fieldSize*fieldsVertical);
}
// void KoushinGUI::TownWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
// {
// kDebug() << "moving";
// }
// void KoushinGUI::TownWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)
// {
// kDebug() << "clicking";
// }
#include "townwidget.moc"<file_sep>project(Koushin)
cmake_minimum_required(VERSION 2.6)
find_package(Qt4 REQUIRED)
include(${QT_USE_FILE})
find_package(KDE4 REQUIRED)
include(KDE4Defaults)
include_directories(${QT_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR})
FIND_LIBRARY(QT_QTSCRIPT_TOOLS_LIBRARY_RELEASE NAMES QtScriptTools QtScriptTools4 PATHS ${QT_LIBRARY_DIR} NO_DEFAULT_PATH)
# message("${KDE4_DEFINITIONS}:" ${KDE4_DEFINITIONS})
add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS})
remove_definitions(-DQT_NO_STL)
include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_BINARY_DIR}
${KDE4_INCLUDES}
${KDEGAMES_INCLUDE_DIRS}
)
add_subdirectory(src)
add_subdirectory(data)
<file_sep>set(Koushin_GUI
townwidget.cpp
)
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "actionmanager.h"
#include "action.h"
#include "player.h"
#include <kdebug.h>
#include <stdexcept>
#include <QScriptEngine>
#include "building.h"
Koushin::ActionManager::ActionManager(Player* owner)
: m_owner(owner)
{
m_owner->setActionManager(this);
}
Koushin::ActionManager::~ActionManager()
{
}
void Koushin::ActionManager::executeActions(int currentRound)
{
QMap<int, Koushin::Action* > actions;
foreach(Koushin::ActionObject* object, m_actionObjects) {
foreach(Koushin::Action* action, object->getAllActions()) {
action->resetAction();
actions.insert(action->getPriority(), action);
}
}
kDebug() << "Number of Objects: " << m_actionObjects.size() << ". Number of Actions: " << actions.size();
//get all priorities and sort them descending
QList<int > priorityList = actions.uniqueKeys();
qSort(priorityList.begin(), priorityList.end(), qGreater<int>()); //execute first actions with height priority
//execute actions beginning with highest priority
QList<Koushin::Action* > actionsToExecute;
for (QList<int >::const_iterator it = priorityList.begin(); it != priorityList.end(); ++it) {
actionsToExecute << actions.values(*it); //apend actions to ToDo-List
kDebug() << "Execute jobs with priority = " << *it;
foreach(Koushin::Action* action, actionsToExecute) {
if(!action->shouldExecuteInEveryRound() && !action->getExecutionRounds().contains(currentRound)) {
actionsToExecute.removeAll(action);
continue;
}
if(executeAction(action)) {
actionsToExecute.removeAll(action); //action executed, remove from list (and all [not possible] duplicates)
}
}
}
//some dependencies are not execute, but the list of priorities is empty (e.g. some actions requiere actions with lowest priority)
while(!actionsToExecute.isEmpty()) { //make list empty
foreach(Koushin::Action* action, actionsToExecute) {
if(executeAction(action)) {
actionsToExecute.removeAll(action);
}
}
}
}
//false does not mean the action is failed, false means the action can not be executed because of missing requirements
bool Koushin::ActionManager::executeAction(Koushin::Action* action)
{
if(action->getStatus() == Koushin::actionFailed) {
return true; //the action can not be execute, but it is not necessary to try it again
}
if(action->getStatus() != Koushin::actionNotStarted) {
return false; //action is no ready, skip at this moment
}
if(!action->requirementsFinished()) {
action->setStatus(Koushin::actionWaitsForRequirement);
setStatusOfDependensies(action);
return false;
}
kDebug() << "Execute action " << action->getActionString() << " with " << action->getParameters();
if(action->execute()) {
action->setStatus(Koushin::actionSucceeded);
kDebug() << "action " << action->getActionString() << " succeded";
} else {
action->setStatus(Koushin::actionFailed);
kDebug() << "action " << action->getActionString() << " failed";
}
setStatusOfDependensies(action);
return true;
}
bool Koushin::ActionManager::addActionObject(Koushin::ActionObject* object)
{
if(m_actionObjects.contains(object)) return false;
m_actionObjects << object;
return true;
}
bool Koushin::ActionManager::removeActionObject(Koushin::ActionObject* object)
{
if(!m_actionObjects.contains(object)) return false;
m_actionObjects.removeAll(object);
return true;
}
void Koushin::ActionManager::setStatusOfDependensies(Koushin::Action* action)
{
foreach(Koushin::Action* dependency, action->getDependencies().keys()) {
if(action->getStatus() == Koushin::actionFailed && action->getDependencies().value(dependency) == true) {
dependency->setStatus(Koushin::actionFailed);
}
if(action->getStatus() == Koushin::actionFailed && action->getDependencies().value(dependency) == false) {
dependency->closeRequirement(action);
if(dependency->noOpenRequirements())
dependency->setStatus(Koushin::actionNotStarted);
}
if(action->getStatus() == Koushin::actionSucceeded && action->getDependencies().value(dependency) == false) {
dependency->setStatus(Koushin::actionFailed);
}
if(action->getStatus() == Koushin::actionSucceeded && action->getDependencies().value(dependency) == true) {
dependency->closeRequirement(action);
if(dependency->noOpenRequirements())
dependency->setStatus(Koushin::actionNotStarted);
}
if(action->getStatus() == Koushin::actionNotStarted || action->getStatus() == Koushin::actionWaitsForRequirement) {
dependency->setStatus(Koushin::actionWaitsForRequirement);
}
setStatusOfDependensies(dependency);
}
}
bool Koushin::ActionManager::addGlobalParameter(QString name, QString content)
{
if(m_globalParameters.keys().contains(name)) {
kDebug() << "Parameter allready in use. I do not overwright it. Use instead setGlobalTo or addToGlobal. " << name;
return false;
}
if(name.contains(QRegExp("![A-Za-z0-9]*"))) {
kDebug() << "Use only letters and numbers for parameter names: " << name;
return false;
}
//test for endless loops
if(expandParameter(content, name) == "NOT_VALID")
{
kDebug() << "Content of " << name << " is not expandable";
return false;
}
m_globalParameters.insert(name, content);
return true;
}
int Koushin::ActionManager::evalContent ( QString content, QString parameter )
{
content = expandParameter(content, parameter);
if (content == "NOT_VALID") {
kDebug() << "Can not expand parameter: " << parameter;
throw std::runtime_error(QString("Parameter not expandable:" + parameter).toAscii().constData());
return 0;
}
if(QScriptEngine::checkSyntax(content).state() != QScriptSyntaxCheckResult::Valid) {
kDebug() << "Sorry, but can not calculate string: " << content;
throw std::runtime_error(QString("Parameter can not calculated:" + parameter).toAscii().constData());
}
QScriptEngine calc;
return calc.evaluate(content).toInteger();
}
int Koushin::ActionManager::evalParameter(QString parameter)
{
//Do not write expanded content to m_globalParameters: later manipulation of values should be possible
// kDebug() << "Expand parameter: " << parameter << " = " << m_globalParameters.value(parameter);
return evalContent(m_globalParameters.value(parameter), parameter);
}
QString Koushin::ActionManager::expandParameter(QString line, QString name)
{
QString part;
int replacePart = 1;
while((part = line.section("#", replacePart, replacePart)) != "") {
if (line.contains("#" + name + "#")) {
kDebug() << "Found recursion." << line << " contains " << name;
return QString("NO_VALID");
}
if(m_globalParameters.keys().contains(part)) {
line.replace("#" + part + "#", expandParameter(m_globalParameters.value(part), part));
} else {
replacePart += 2; //jump to next part => skip unknown Parameter
}
}
return line;
}
bool Koushin::ActionManager::addContentToGlobalParameter ( QString name, QString content )
{
if(!m_globalParameters.keys().contains(name)) {
kDebug() << "Global not known: " << name;
return false;
}
m_globalParameters.insert(name, m_globalParameters.value(name) + content);
kDebug() << "new content is " << m_globalParameters.value(name);
return true;
}
bool Koushin::ActionManager::setGlobalParameterContent ( QString name, QString content )
{
if(!m_globalParameters.keys().contains(name)) {
kDebug() << "Global not known: " << name;
return false;
}
m_globalParameters.insert(name, content); //overwrites content, because it is not a QMultiMap
return true;
}
void Koushin::ActionManager::resetGlobalParameters()
{
m_globalParameters.clear();
foreach(Koushin::ActionObject* object, m_actionObjects) {
if(object->getActionObjectType() == Koushin::actionObjectIsBuilding)
Koushin::ActionParser::parseGlobals(((Koushin::Building*)object)->getConfig()->group("tasks").group("globals"), this);
}
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BUILDING_H
#define BUILDING_H
#include "town.h"
#include "actionobject.h"
#include "field.h"
#include "GUI/fielditem.h"
class KConfig;
class KConfigGroup;
namespace Koushin {
class Action;
class Field;
class Building : public ActionObject {
Q_OBJECT
public:
Building(Town* town = 0, KConfig* config = 0);
virtual ~Building();
void setName(QString name) {m_name = name;}
QString getName() const {return m_name;}
Town* getTown() {return m_town;}
int getLevel() const {return m_level;}
int increaseLevel() {return ++m_level;}
void setLevel(int newLevel) {m_level = newLevel;}
int getNumberOfCreatedOpenFieldActions(QString name) const {return m_createdOpenFieldActions.value(name, 0);}
void addOpenFieldAction(QString groupName);
void removeOpenFieldAction(QString groupName);
QStringList getOpenFieldActions() const {return m_openFieldActions;}
void setField(Field* field) {m_field = field;}
Field* getField() const {return m_field;}
QPointF pos() const {return m_field->getFieldItem()->pos();}
void useField(Field* field) {m_usedFields << field;}
QList<Field* > getUsedFields() const {return m_usedFields;}
KConfig* getConfig() const {return m_config;}
void select();
void unselect();
void setAge(int time) {m_age = time;}
int getAge() const {return m_age;}
const actionObjectType getActionObjectType() {return actionObjectIsBuilding;};
const QMap<QString, ActionProperties> getPossibleActions();
const QString getLocal(QString name, QString additionalContent = QString());
public Q_SLOTS:
//define here public actions
private:
Town* m_town;
QString m_name;
int m_level;
QMap<QString, int > m_createdOpenFieldActions;
QStringList m_openFieldActions;
QList<Field* > m_usedFields;
Field* m_field;
KConfig* m_config;
int m_age;
};
}
#endif // BUILDING_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef TOWN_H
#define TOWN_H
#include <QMap>
#include <QPoint>
#include "actionobject.h"
class KConfig;
namespace KoushinGUI {
class TownWidget;
}
namespace Koushin {
enum ResourceType {
ResourceUnspezifed = 0,
ResourceWood,
ResourceStone,
ResourceRice,
ResourceTypeCount
};
enum FieldType {
plainField = 0,
fieldWithForest,
fieldWithRocks,
fieldWithWater,
fieldWithBuilding,
fieldNotUsable,
numberOfFieldTypes
};
class Resource {
public:
Resource(ResourceType type = ResourceUnspezifed)
: maximumCapacity(0)
, amount(0)
, type(type) {}
void setAmount(int val) {amount = val;}
int maximumCapacity;
int amount;
ResourceType type;
};
class Building;
class Field;
class Player;
class Town : public ActionObject {
Q_OBJECT
public:
Town(Player* owner = 0, KConfig* config = 0);
virtual ~Town();
Player* getOwner() {return m_owner;}
// Function to access also with parser
public Q_SLOTS:
bool increaseResource(ResourceType type, int difference) {return changeResource(type, difference);}
bool decreaseResource(ResourceType type, int difference) {return changeResource(type, -difference);}
bool setResourceCapacity(ResourceType type, int value);
public:
//other functions
bool changeResource(ResourceType type, int difference);
QMap<ResourceType, Resource*> getResources() {return m_resources;}
::KoushinGUI::TownWidget* getTownWidget() const {return m_townWidget;}
bool addBuilding(Building* building, QPoint pos);
QMap<Building*, QPoint> getBuildings() const {return m_buildings;}
QMap<QString, QString> getPossibleBuildings(QMap<QString, QString> allBuildings) const;
QList<Field* > getPossibleFields(QPoint aroundPos, qreal radius, QList<FieldType> types, const QStringList& buildingNames = QStringList());
void markFields(QList<Field* > fields);
void unmarkAllFields();
Field* getFieldFromBuilding(Building* building);
KConfig* getTownConfig() const {return m_townConfig;}
Field* getFieldFromPoint(QPoint point);
QMap<QString, QString> getBuildingList();
void completeBuildingConstruction(Building* building);
void growBuildings();
static ResourceType getResourceTypeFromQString(QString resourceName);
const actionObjectType getActionObjectType() {return actionObjectIsTown;};
const QMap<QString, ActionProperties> getPossibleActions();
const QString getLocal(QString name, QString additionalContent = QString());
private:
Player* m_owner;
QMap<ResourceType, Resource*> m_resources;
QMap<Building*, QPoint> m_buildings;
QMap<QPoint, Field* > m_fields;
::KoushinGUI::TownWidget* m_townWidget;
KConfig* m_townConfig;
};
}
#endif // TOWN_H
<file_sep>add_subdirectory(buildings)
add_subdirectory(town)
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "actionobject.h"
#include <QString>
#include <KDebug>
#include "action.h"
Koushin::ActionObject::ActionObject()
{
}
bool Koushin::ActionObject::addToLocal(QString name, QString content, bool replaceGlobal)
{
if(replaceGlobal)
m_globalReplacements.insert(name, m_globalReplacements.value(name) + content);
else
m_globalAdditions.insert(name, m_globalAdditions.value(name) + content);
return true;
}
bool Koushin::ActionObject::setLocalTo(QString name, QString content, bool replaceGlobal)
{
if(replaceGlobal)
m_globalReplacements.insert(name, content);
else
m_globalAdditions.insert(name, content);
return true;
}
const QMap< QString, Koushin::ActionProperties > Koushin::ActionObject::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
actions.insert("setLocalTo", Koushin::ActionProperties(
QStringList() << "string" << "string" << "bool",
"ActionObject: overwrites a value only for specified ActionObject. string=NameOfGlobal, string=NewValue, bool=the locals replaces the global "));
actions.insert("addToLocal", Koushin::ActionProperties(
QStringList() << "string" << "string" << "bool",
"ActionObject: add a string to a local. string=NameOfGlobal, string=AdditionalContent, bool=the locals replaces the global"));
return actions;
}
QMap< QString, Koushin::ActionProperties > Koushin::ActionObject::adjustActionProperties(QMap< QString, Koushin::ActionProperties >& actions)
{
foreach(QString name, Koushin::ActionObject::getPossibleActions().keys()) {
Koushin::ActionProperties prop = Koushin::ActionObject::getPossibleActions().value(name);
prop.activate(prop.description);
actions.insert(name, prop);
}
foreach(QString name, actions.keys())
if(!actions.value(name).activated) actions.remove(name);
return actions;
}
QList<Koushin::Action* > Koushin::ActionObject::getAllActions()
{
return m_actions;
}
bool Koushin::ActionObject::insertAction(Koushin::Action* action)
{
if(m_actions.contains(action)) return false;
m_actions << action;
kDebug() << "############### Insert Action" << action->getActionString();
return true;
}
bool Koushin::ActionObject::deleteAction(Koushin::Action* action)
{
if(!m_actions.contains(action)) return false;
m_actions.removeAll(action);
return true;
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "building.h"
#include <qpainter.h>
#include <KDebug>
#include <KConfigGroup>
#include <kconfig.h>
#include "actionparser.h"
#include <QMetaClassInfo>
Koushin::Building::Building(Town* town, KConfig* config)
: m_town(town)
, m_name("NoName")
, m_level(1)
, m_field(0)
, m_config(config)
, m_age(0)
{
}
Koushin::Building::~Building()
{
}
const QMap< QString, Koushin::ActionProperties > Koushin::Building::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
for(int i = 0; i < metaObject()->methodCount(); ++i) {
QPair<QString, QStringList> function = Koushin::ActionParser::separateNameAndParameters(metaObject()->method(i).signature());
Koushin::ActionProperties prop(function.second, QString());
actions.insert(function.first, prop);
}
adjustActionProperties(actions);
kDebug() << actions.keys();
return actions;
}
const QString Koushin::Building::getLocal(QString name, QString additionalContent)
{
if(m_globalReplacements.contains(name))
return m_globalReplacements.value(name);
if(m_globalAdditions.contains(name))
additionalContent += m_globalAdditions.value(name);
return m_town->getLocal(name, additionalContent);
}
void Koushin::Building::addOpenFieldAction(QString groupName)
{
m_openFieldActions << groupName;
m_createdOpenFieldActions.insert(groupName, getNumberOfCreatedOpenFieldActions(groupName) + 1);
}
void Koushin::Building::removeOpenFieldAction(QString groupName)
{
//remove only one: the same object is inserted more then one times to save memory
m_openFieldActions.removeOne(groupName);
}
void Koushin::Building::select()
{
m_field->markField(Qt::gray);
foreach(Koushin::Field* field, m_usedFields)
field->markField(Qt::gray);
}
void Koushin::Building::unselect()
{
m_field->unmarkField();
foreach(Koushin::Field* field, m_usedFields)
field->unmarkField();
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef FIELDITEM_H
#define FIELDITEM_H
#include <qgraphicsitem.h>
#include <QColor>
namespace Koushin {
class Field;
}
namespace KoushinGUI {
class FieldItem : public QGraphicsItem {
public:
FieldItem(Koushin::Field* field);
virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0);
virtual QRectF boundingRect() const;
void setMarkColor(QColor color) {m_markColor = color;}
protected:
private:
::Koushin::Field* m_field;
QGraphicsTextItem* m_textItem;
QColor m_markColor;
};
}
#endif // FIELDITEM_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BUILDINGINFOWIDGET_H
#define BUILDINGINFOWIDGET_H
#include <QWidget>
#include <QListWidget>
class QPushButton;
namespace Koushin {
class Building;
}
namespace KoushinGUI {
class BuildingInfoWidget : public QWidget {
Q_OBJECT
public:
BuildingInfoWidget();
void setBuilding(::Koushin::Building* building) {m_building = building;}
::Koushin::Building* getBuilding() const {return m_building;}
QPushButton* getNextLevelButton() const {return m_nextLevelButton;}
public Q_SLOTS:
void repaint();
Q_SIGNALS:
void fieldActionSelected(QListWidgetItem* item);
private:
::Koushin::Building* m_building;
QListWidget m_list;
QPushButton* m_nextLevelButton;
};
}
#endif // BUILDINGINFOWIDGET_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef GAMEVIEW_H
#define GAMEVIEW_H
#include <QtGui/qwidget.h>
class QGraphicsView;
class QPushButton;
namespace Koushin {
class Town;
class Field;
class Player;
}
namespace KoushinGUI {
class TownWidget;
class BuildingInfoWidget;
class ConstructionMenu;
class ResourceInfoWidget;
class GameView : public QWidget {
Q_OBJECT
public:
GameView();
public Q_SLOTS:
void showResourceInfo(Koushin::Town*);
void showConstructionMenu(Koushin::Town*, QPoint);
void closeConstructionMenu();
void showFieldInfo(Koushin::Field* field);
void showTownView(::Koushin::Town*);
void changePlayer(::Koushin::Player*); //update the connections to the given player
protected:
virtual void resizeEvent(QResizeEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void wheelEvent(QWheelEvent* event);
private:
QPoint mapFieldToDisplay(QPoint fieldPos) const;
ResourceInfoWidget* m_resourceInfo;
ConstructionMenu* m_constructionMenu;
QPushButton* m_endRoundButton;
BuildingInfoWidget* m_fieldInfo;
QGraphicsView* m_townView;
QRectF m_focusRect;
QPointF m_oldPos;
bool m_townClicked;
//old properties: needed for deleting this objects
::Koushin::Player* m_player;
TownWidget* m_townWidget;
};
}
#endif // GAMEVIEW_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "building.h"
#include "player.h"
#include <kdebug.h>
#include "town.h"
#include "GUI/townwidget.h"
#include "GUI/buildinginfowidget.h"
#include "GUI/constructionmenu.h"
#include <QGraphicsScene>
#include <KConfigGroup>
#include <KConfig>
#include "actionparser.h"
#include "actionmanager.h"
#include "GUI/resourceinfowidget.h"
#include "action.h"
#include "game.h"
#include "field.h"
#include <QMetaClassInfo>
#include <QGraphicsView>
Koushin::Player::Player(QString name, Koushin::Game* game)
: m_actionManager(new Koushin::ActionManager(this))
, m_buildingLot(QPoint(0,0))
, m_name(name)
, m_game(game)
, m_selectedBuilding(0)
, m_openFieldConfig("")
, m_lastInteraction(Koushin::PlayerInteraction::noInteraction)
{
}
Koushin::Player::~Player()
{
delete m_actionManager;
}
const QMap< QString, Koushin::ActionProperties > Koushin::Player::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
for(int i = 0; i < metaObject()->methodCount(); ++i) {
QPair<QString, QStringList> function = Koushin::ActionParser::separateNameAndParameters(metaObject()->method(i).signature());
Koushin::ActionProperties prop(function.second, QString());
if(function.first == "setGlobalTo") {
prop.activate("Player: overwrites a value. string=NameOfGlobal, string=NewValue ");
}
else if(function.first == "addToGlobal") {
prop.activate("Player: add a string to a global. string=NameOfGlobal, string=AdditionalContent");
}
actions.insert(function.first, prop);
}
adjustActionProperties(actions);
kDebug() << actions.keys();
return actions;
}
bool Koushin::Player::addToGlobal(QString name, QString content)
{
if(!m_actionManager) {
kDebug() << "no action manager given";
return false;
}
kDebug() << "call addToGlobal" << name << " = " << content;
return m_actionManager->addContentToGlobalParameter(name, content);
}
bool Koushin::Player::setGlobalTo(QString name, QString content)
{
return m_actionManager->setGlobalParameterContent(name, content);
}
const QString Koushin::Player::getLocal(QString name, QString additionalContent)
{
if(m_globalReplacements.contains(name))
return m_globalReplacements.value(name);
if(m_globalAdditions.contains(name))
additionalContent += m_globalAdditions.value(name);
return m_actionManager->getGlobalParameterValue(name) + additionalContent;
}
void Koushin::Player::townClicked(QPoint point) //create member with active town
{
if(!m_townList.isEmpty()) {
m_buildingLot = point;
emit showConstructionMenu(m_townList.first(), point);
}
}
void Koushin::Player::buildingChosen(QString buildingConfig)
{
if(!m_actionManager) {
kDebug() << "No ActionManger set. Can't create Building without a manager.";
return;
}
KConfig* config = new KConfig(buildingConfig);
Koushin::Building* newBuilding = new Koushin::Building(m_townList.first(), config);
m_townList.first()->addBuilding(newBuilding, m_buildingLot);
KConfigGroup settings(config, "general");
newBuilding->setName(settings.readEntry("name", QString("NoName")));
newBuilding->setAge(-settings.readEntry("constructiontime", int(0)));
if(newBuilding->getAge() == 0) m_townList.first()->completeBuildingConstruction(newBuilding);
ActionParser::createOpenFieldActions(new KConfigGroup(config, "fieldTasks"), newBuilding);
newBuilding->getField()->getFieldItem()->update(newBuilding->getField()->getFieldItem()->boundingRect());
emit closeConstructionMenu();
}
void Koushin::Player::endRound()
{
if(m_selectedBuilding)
m_selectedBuilding->unselect();
setSelectedBuilding(0);
m_fieldsForFieldAction.clear();
m_actionManager->resetGlobalParameters();
m_game->endRound();
}
void Koushin::Player::startRound()
{
emit showResourceInfo(m_townList.first());
emit showFieldInfo(0);
foreach(Koushin::Town* town, m_townList)
town->growBuildings();
m_lastInteraction = Koushin::PlayerInteraction::roundedStarted;
}
void Koushin::Player::fieldActionSelected(QListWidgetItem* item)
{
if(!m_selectedBuilding) return;
m_openFieldConfig = item->text();
KConfigGroup group = m_selectedBuilding->getConfig()->group("fieldTasks").group(m_openFieldConfig);
qreal radius = group.readEntry("fieldRadius", qreal(100));
QString typeLine = group.readEntry("needs", QString()); ///@todo prevent crash when "needs=" is empty
kDebug() << "needs: " << typeLine;
QPair<QString, QStringList> typeDescription = ActionParser::separateNameAndParameters(typeLine);
if(typeDescription.first == "building")
m_fieldsForFieldAction = m_townList.first()->getPossibleFields(m_selectedBuilding->pos().toPoint(), radius, QList<Koushin::FieldType>() << Koushin::fieldWithBuilding, typeDescription.second);
else if (typeDescription.first == "field") {
QList<Koushin::FieldType > types;
foreach(QString type, typeDescription.second)
types << Koushin::Field::QStringToFieldType(type);
m_fieldsForFieldAction = m_townList.first()->getPossibleFields(m_selectedBuilding->pos().toPoint(), radius, types);
}
foreach(Koushin::Field* field, m_selectedBuilding->getUsedFields())
m_fieldsForFieldAction.removeOne(field);
m_townList.first()->markFields(m_fieldsForFieldAction);
}
void Koushin::Player::setSelectedBuilding(Koushin::Building* building)
{
m_selectedBuilding = building;
if(building)
emit showFieldInfo(building->getField());
}
void Koushin::Player::fieldForActionChosen(Koushin::Field* field)
{
if(!m_selectedBuilding) return;
KConfigGroup* fieldsGroup = new KConfigGroup(m_selectedBuilding->getConfig()->group("fieldTasks"));
//create actions
QList<Action* > actions = Koushin::ActionParser::createActionsFromConfig(fieldsGroup, field, m_game->getCurrentRound(), m_openFieldConfig);
kDebug() << "##### load actions: " << actions.size();
foreach(Koushin::Action* action, actions)
m_selectedBuilding->insertAction(action);
m_actionManager->addActionObject(m_selectedBuilding);
m_fieldsForFieldAction.clear();
m_selectedBuilding->useField(field);
m_selectedBuilding->removeOpenFieldAction(m_openFieldConfig);
emit showFieldInfo(field);
}
void Koushin::Player::fieldClicked(Koushin::Field* field)
{
switch (m_lastInteraction) {
case Koushin::PlayerInteraction::roundedStarted: case Koushin::PlayerInteraction::noInteraction:
if(field->getType() == Koushin::plainField) {
townClicked(field->getFieldItem()->pos().toPoint());
}
if(field->getType() == Koushin::fieldWithBuilding && field->getBuilding()) {
setSelectedBuilding(field->getBuilding());
field->getBuilding()->select();
m_lastInteraction = Koushin::PlayerInteraction::buildingClicked;
}
break;
case Koushin::PlayerInteraction::buildingClicked:
if(m_fieldsForFieldAction.contains(field)) {
fieldForActionChosen(field);
field->getTown()->unmarkAllFields();
m_selectedBuilding->select();
emit showFieldInfo(field);
} else {
setSelectedBuilding(0);
field->getTown()->unmarkAllFields();
emit showFieldInfo(field);
m_lastInteraction = Koushin::PlayerInteraction::noInteraction;
}
break;
default:
kDebug() << "Do not know what to do.";
}
}
void Koushin::Player::levelupBuilding()
{
if(m_selectedBuilding) {
kDebug() << m_selectedBuilding->getName();
m_actionManager->removeActionObject(m_selectedBuilding);
// m_actionManager->removeActions((Koushin::ActionObject*)m_selectedBuilding);
// foreach(Koushin::Field* field, m_selectedBuilding->getUsedFields())
// m_actionManager->removeActions(field);
}
}
#include "player.moc"
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "townaction.h"
#include "town.h"
#include "player.h"
#include "actionmanager.h"
Koushin::TownAction::TownAction(Town* recipient)
: m_recipient(recipient)
{
// PUBLIC_ACTION;
// kDebug() << ACTION_NAME;
}
Koushin::TownAction::~TownAction()
{
}
QMap< QString, Koushin::ActionProperties> Koushin::TownAction::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
actions.insert("increaseResource", Koushin::ActionProperties(
QStringList() << "string" << "int",
"Town: Add the given parameter to the given resource. string=ResourceName, int=difference"));
actions.insert("decreaseResource", Koushin::ActionProperties(
QStringList() << "string" << "int",
"Town: Removes the given parameter from the given resource. string=ResourceName, int=difference"));
actions.insert("setResourceCapacity", Koushin::ActionProperties(
QStringList() << "string" << "int",
"Town: Sets the capacity of a given resource to the given value. string=ResourceName, int=new value"));
return actions;
}
bool Koushin::TownAction::execute()
{
if(m_action == "increaseResource") {
Koushin::ResourceType type = Koushin::Town::getResourceTypeFromQString(m_parameters[0]);
try{
int diff = m_recipient->getOwner()->getActionManager()->evalContent(m_parameters.value(1, QString("0")));
return m_recipient->changeResource(type, diff);
}
catch (std::exception & e) {return false;}
}
else if(m_action == "decreaseResource") {
Koushin::ResourceType type = Koushin::Town::getResourceTypeFromQString(m_parameters[0]);
try{
int diff = m_recipient->getOwner()->getActionManager()->evalContent(m_parameters.value(1, QString("0")));
return m_recipient->changeResource(type, -diff);
}
catch (std::exception & e) {return false;}
}
else if(m_action == "setResourceCapacity") {
Koushin::ResourceType type = Koushin::Town::getResourceTypeFromQString(m_parameters[0]);
try{
int value = m_recipient->getOwner()->getActionManager()->evalContent(m_parameters.value(1, QString("0")));
kDebug() << "####=> set Capacity to: " << value;
return m_recipient->setResourceCapacity(type, value);
}
catch (std::exception & e) {return false;}
} else {
kDebug() << "Unknown action " << m_action;
}
return false; //action not parsed -> return false
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "game.h"
#include "player.h"
#include "actionmanager.h"
Koushin::Game::Game()
: m_currentPlayer(0)
, m_currentRound(0)
{
}
Koushin::Game::~Game()
{}
void Koushin::Game::startRound()
{
if(m_players.isEmpty()) return;
if(m_currentPlayer != m_players.last())
m_currentPlayer = m_players.value(m_players.indexOf(m_currentPlayer) + 1);
else
m_currentPlayer = m_players.first();
++m_currentRound;
m_currentPlayer->getActionManager()->executeActions(m_currentRound);
m_currentPlayer->startRound();
}
void Koushin::Game::endRound()
{
///@todo prepare requests for other players
startRound();
}
bool Koushin::Game::playernameAlreadyExists(QString name)
{
foreach(::Koushin::Player* player, m_players)
if(player->getName() == name) return true;
return false;
}
void Koushin::Game::shufflePlayers()
{
QList<Player* > tmpList;
for(int i = m_players.length() - 1; i >= 0; --i)
tmpList << m_players.takeAt(qrand() % i);
m_players = tmpList;
}
#include "game.moc"
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ACTION_H
#define ACTION_H
#include <QMap>
#include <QString>
#include <QList>
#include <QStringList>
#include <kdebug.h>
#include <KConfigGroup>
#include <kconfig.h>
#include "actionparser.h"
namespace Koushin {
class Field;
class Town;
class Player;
class Building;
class Town;
class ActionManager;
class ActionObject;
enum actionStatus {
actionNotStarted = 0,
actionSucceeded,
actionFailed,
actionWaitsForRequirement
};
class Action {
public:
Action();
virtual ~Action();
actionStatus getStatus() const {return m_status;}
int getPriority() const {return m_config->readEntry("priority", QString("10")).toInt();}
QMap<Action*, bool> getRequirements() const {return m_requirements;}
QMap<Action*, bool> getDependencies() const {return m_requirementFor;}
QList<Action* > getRecursiveRequirements(Action* action);
/**
* @brief This functions reads the action name from the configuration.
*The configuration must contain a key called \c action that holds a value like <tt>functionName(para1, para2,...)</tt>. To separate the function name from the parameters it uses the static \c separateNameAndParameters from the ActionParser.
*
* @return QString The name of the action
**/
QString getActionString() const {
return ActionParser::separateNameAndParameters(m_config->readEntry("action", QString())).first;}
QStringList getParameters() const {
return ActionParser::separateNameAndParameters(m_config->readEntry("action", QString())).second;}
/**
* @brief This function executes the specified action.
* At first it checks, if all necessary parameters are given. Then it uses the parser to create the right objects to the parameter. Finally it calls the belonging execution action.
*
* Checking the status and the requirements is part of the ActionManager.
*
* @return bool The execution status. If all parameters are correct and the sub-execution gives \c true this functions returns \c true, else \c false.
**/
bool execute(bool failIfOneRecipientFail = false);
/**
* @brief Use this function to store the configuration.
*
* @param config The configuration part of the <tt>[tasks][taskname]</tt> group.
* @return void
**/
void setConfiguration(KConfigGroup* config) {m_config = config;}
void setOwner(ActionObject* owner) {m_owner = owner;}
ActionObject* getOwner() {return m_owner;}
void setStatus(actionStatus status) {m_status = status;}
bool addRequirement(Action* action, bool positiv = true);
void executeInRounds(QList<int > rounds) {m_executionRounds = rounds;}
void executeInEveryRound(bool execute) {m_executeInEveryRound = execute;}
const QList<int > getExecutionRounds() const {return m_executionRounds;}
bool shouldExecuteInEveryRound() const {return m_executeInEveryRound;}
void closeRequirement(Action* action) {m_openRequirements.removeAll(action);}
bool noOpenRequirements() const {return m_openRequirements.isEmpty();}
bool requirementsFinished();
void resetAction();
protected:
KConfigGroup* m_config;
actionStatus m_status;
ActionObject* m_owner; //need this information to parse recipient using "current"
QMap<Action*, bool > m_requirements; ///keep this system -> action pointers can not change in runtime!
QMap<Action*, bool > m_requirementFor;
QList<Action* > m_openRequirements;
QList<int > m_executionRounds;
bool m_executeInEveryRound;
private:
QList< QGenericArgument > prepareArguments(QStringList types, QStringList parameter, Koushin::ActionManager* manager);
bool executePlayerAction(Player* recipient, const QPair<QString, QStringList>& action);
bool executeTownAction(Town* recipient, const QPair<QString, QStringList>& action);
bool executeBuildingAction(Building* recipient, const QPair<QString, QStringList>& action);
bool executeActionObjectAction(ActionObject* recipient, const QPair<QString, QStringList>& action);
bool setAsRequirementFor(Action* action, bool positiv = true);
bool possibleParametersGiven(ActionObject* recipient, QString actionName, QStringList parameters);
};
}
#endif // ACTION_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "action.h"
#include "actionobject.h"
#include "town.h"
#include "actionmanager.h"
#include "player.h"
#include "building.h"
#include "field.h"
#include <QMetaClassInfo>
Koushin::Action::Action()
: m_config(0)
, m_status(Koushin::actionNotStarted)
{
}
Koushin::Action::~Action()
{
}
bool Koushin::Action::requirementsFinished()
{
QList<Koushin::Action* > actions = m_requirements.keys();
for(QList<Action* >::const_iterator it = actions.begin(); it != actions.end(); ++it) {
if(((*it)->getStatus() == Koushin::actionSucceeded) & (m_requirements.value(*it))) continue;
if(((*it)->getStatus() == Koushin::actionFailed) & (!m_requirements.value(*it))) continue;
return false;
}
return true;
}
bool Koushin::Action::addRequirement(Koushin::Action* action, bool positiv)
{
if(getRecursiveRequirements(action).contains(this)) {
kDebug() << "Can not insert requirement: it requires itself. This would cause a endless loop in action manager.";
return false;
}
m_requirements.insert(action, positiv);
if(!action->getDependencies().keys().contains(action)) {
action->setAsRequirementFor(this, positiv);
}
return true;
}
bool Koushin::Action::setAsRequirementFor(Koushin::Action* action, bool positiv)
{
//this function is only used by addRequirement
m_requirementFor.insert(action, positiv);
return true;
}
QList< Koushin::Action* > Koushin::Action::getRecursiveRequirements(Koushin::Action* action)
{
QList<Action* > allRequirements(action->getRequirements().keys());
foreach(Koushin::Action* action, action->getRequirements().keys()) {
allRequirements << action->getRecursiveRequirements(action);
}
return allRequirements;
}
void Koushin::Action::resetAction()
{
m_status = actionNotStarted;
m_openRequirements = m_requirements.keys();
}
bool Koushin::Action::execute(bool failIfOneRecipientFailed)
{
if(!m_config || !m_owner) return false;
QString recipientLine = m_config->readEntry("recipient", QString());
QList<Koushin::ActionObject* > recipients = Koushin::ActionParser::parseRecipient(recipientLine, m_owner);
bool allRecipientsFailed = true;
bool oneRecipientFailed = false;
foreach(Koushin::ActionObject* recipient, recipients) {
QString actionLine = m_config->readEntry("action", QString("NO_ACTION_GIVEN"));
QPair<QString, QStringList> action = Koushin::ActionParser::separateNameAndParameters(actionLine);
if(!possibleParametersGiven(recipient, action.first, action.second)) {
oneRecipientFailed = true;
continue;
}
//assaign these values when you use the new QMetaMethod call:
QStringList parameterTypes;
Koushin::ActionManager* manager = 0;
//asseignment changes with recipients, so use this switch:
switch(recipient->getActionObjectType()) {
case Koushin::actionObjectIsBuilding:
parameterTypes = ((Koushin::Building*)recipient)->getPossibleActions().value(action.first).parameterTypes;
manager = ((Koushin::Building*)recipient)->getTown()->getOwner()->getActionManager();
break;
case Koushin::actionObjectIsTown:
parameterTypes = ((Koushin::Town*)recipient)->getPossibleActions().value(action.first).parameterTypes;
manager = ((Koushin::Town*)recipient)->getOwner()->getActionManager();
break;
case Koushin::actionObjectIsPlayer:
parameterTypes = ((Koushin::Player*)recipient)->getPossibleActions().value(action.first).parameterTypes;
manager = ((Koushin::Player*)recipient)->getActionManager();
break;
case Koushin::actionObjectIsField:
parameterTypes = ((Koushin::Field*)recipient)->getPossibleActions().value(action.first).parameterTypes;
manager = ((Koushin::Field*)recipient)->getTown()->getOwner()->getActionManager();
break;
default:
oneRecipientFailed = true;
} // switch(recipient->getActionObjectType())
if(manager) {
//find right method:
int index = recipient->metaObject()->indexOfMethod(QString(action.first + "(" + parameterTypes.join(",") + ")").toLatin1());
QMetaMethod method = recipient->metaObject()->method(index);
//create QGenericArguments from strings:
QList<QGenericArgument> args;
for(int i = 0; i < 10; ++i) {
QString type = parameterTypes.value(i);
if(type.isEmpty())
args.insert(i, QGenericArgument());
else if (type == "ResourceType") {
kDebug() << "Insert ResourceType = " << action.second.value(i);
args.insert(i, Q_ARG(Koushin::ResourceType, Koushin::Town::getResourceTypeFromQString(action.second.value(i))));
}
else if (type == "int") {
try{
int value = manager->evalContent(action.second.value(i));
kDebug() << "Insert int = " << value;
args.insert(i, Q_ARG(int, value));
}
catch (std::exception & e) {
kDebug() << "Can not calculate " << action.second.value(i) << ". Reason: " << e.what();
args.insert(i, QGenericArgument());
}
}
else if(type == "QString") {
kDebug() << "Insert QString = " << action.second.value(i);
args.insert(i, Q_ARG(QString, *(new QString(action.second.value(i)))));
kDebug() << args.at(i).data();
}
else {
kDebug() << "Unknown parameter type: " << type;
args.insert(i, QGenericArgument());
}
}
//execute the functions:
bool rtnValue = false;
method.invoke(recipient, Qt::DirectConnection, Q_RETURN_ARG(bool, rtnValue),
args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
if(rtnValue)
allRecipientsFailed = false;
else
oneRecipientFailed = true;
} // if(manager)
} // loop over recipients
if(failIfOneRecipientFailed && oneRecipientFailed) return false;
if(allRecipientsFailed) return false;
return true;
}
bool Koushin::Action::possibleParametersGiven(Koushin::ActionObject* recipient, QString actionName, QStringList parameters)
{
QMap<QString, Koushin::ActionProperties> possibleActions;
if(recipient->getActionObjectType() == Koushin::actionObjectIsBuilding)
possibleActions = Koushin::Building().getPossibleActions();
if(recipient->getActionObjectType() == Koushin::actionObjectIsField)
possibleActions = Koushin::Field().getPossibleActions();
if(recipient->getActionObjectType() == Koushin::actionObjectIsTown)
possibleActions = Koushin::Town().getPossibleActions();
if(recipient->getActionObjectType() == Koushin::actionObjectIsPlayer)
possibleActions = Koushin::Player().getPossibleActions();
if(!recipient || !possibleActions.contains(actionName)) {
kDebug() << "Action is not in list of possible actions: " << actionName;
return false;
}
Koushin::ActionProperties properties = possibleActions.value(actionName);
if (parameters.length() != properties.parameterTypes.length()) {
kDebug() << "Wrong parameter Number: Expected = " << properties.parameterTypes.length() << "; Given = " << parameters.length();
return false;
}
return true;
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "town.h"
#include "GUI/townwidget.h"
#include "player.h"
#include <KDebug>
#include "building.h"
#include <math.h>
#include "game.h"
#include "actionmanager.h"
#include "field.h"
#include <kconfig.h>
#include "actionparser.h"
#include <QMetaClassInfo>
//define operator "<" for QPoint after lexigographic order for using it as key in QMap:
bool operator<(const QPoint& lPoint, const QPoint& rPoint) {
if(lPoint.x() < rPoint.x())
return true;
if(lPoint.x() == rPoint.x() && lPoint.y() < rPoint.y())
return true;
return false;
}
qreal distance(QPoint p1, QPoint p2) {
QPoint tmpP = p2 - p1;
return sqrt(pow(tmpP.x(), 2) + pow(tmpP.y(), 2));
}
Koushin::Town::Town(Player* owner, KConfig* config)
: m_owner(owner)
, m_townWidget(new KoushinGUI::TownWidget)
, m_townConfig(config)
{
if(owner) {
//Create Resources with town
for (int i = 1; i < (int)Koushin::ResourceTypeCount; ++i) {
Koushin::ResourceType type = (Koushin::ResourceType)i;
m_resources.insert(type, new Koushin::Resource(type));
}
m_owner->addTown(this);
if(m_townConfig) {
m_townWidget->updateTownPixmap(m_townConfig);
KConfigGroup fieldGroup = m_townConfig->group("fields");
foreach(QString groupName, fieldGroup.groupList()) {
KConfigGroup group = fieldGroup.group(groupName);
foreach(QString key, group.keyList()) {
QPoint point = group.readEntry(key, QPoint(0,0));
Koushin::Field* field = new Koushin::Field(this);
field->setType(Koushin::Field::QStringToFieldType(groupName));
field->setPos(point);
m_fields.insert(point, field);
if(field->getType() == Koushin::fieldWithForest)
field->setResource(Koushin::ResourceWood, 1000);
if(field->getType() == Koushin::fieldWithRocks)
field->setResource(Koushin::ResourceStone, 1000);
}// loop over fields
}// loop over field types
}// if(m_townConfig)
} // if(owner)
}
Koushin::Town::~Town()
{
}
const QMap< QString, Koushin::ActionProperties > Koushin::Town::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
for(int i = 0; i < metaObject()->methodCount(); ++i) {
QPair<QString, QStringList> function = Koushin::ActionParser::separateNameAndParameters(metaObject()->method(i).signature());
Koushin::ActionProperties prop(function.second, QString());
if(function.first == "increaseResource") {
prop.activate("Town: Add the given parameter to the given resource. string=ResourceName, int=difference");
}
else if(function.first == "decreaseResource") {
prop.activate("Town: Removes the given parameter from the given resource. string=ResourceName, int=difference");
}
else if(function.first == "setResourceCapacity") {
prop.activate("Town: Sets the capacity of a given resource to the given value. string=ResourceName, int=new value");
}
actions.insert(function.first, prop);
}
adjustActionProperties(actions);
kDebug() << actions.keys();
return actions;
}
const QString Koushin::Town::getLocal(QString name, QString additionalContent)
{
if(m_globalReplacements.contains(name))
return m_globalReplacements.value(name);
if(m_globalAdditions.contains(name))
additionalContent += m_globalAdditions.value(name);
return m_owner->getLocal(name, additionalContent);
}
bool Koushin::Town::changeResource(Koushin::ResourceType type, int difference)
{
Koushin::Resource* res = m_resources.value(type);
if (res->type == Koushin::ResourceUnspezifed) {
kDebug() << "Resource not found.";
return false;
}
if (res->amount + difference > res->maximumCapacity) {
kDebug() << "Capacity reached" << res->amount + difference << " of " << res->maximumCapacity;
res->amount = res->maximumCapacity;
return false;
}
if (res->amount + difference < 0) {
kDebug() << "Not enough resources: " << res->amount << " of " << qAbs(difference);
return false;
}
res->amount += difference;
return true;
}
bool Koushin::Town::setResourceCapacity(Koushin::ResourceType type, int value)
{
Koushin::Resource* res = m_resources.value(type);
kDebug() << (int)type << " = " << value;
res->maximumCapacity = value;
return true; //nothing can go wrong, or?
}
Koushin::ResourceType Koushin::Town::getResourceTypeFromQString(QString resourceName)
{
if(resourceName == "Wood") return Koushin::ResourceWood;
if(resourceName == "Stone") return Koushin::ResourceStone;
if(resourceName == "Rice") return Koushin::ResourceRice;
return Koushin::ResourceUnspezifed;
}
bool Koushin::Town::addBuilding(Koushin::Building* building, QPoint pos)
{
if(m_buildings.contains(building)){
kDebug() << "Building is allready on the map at" << m_buildings.value(building).x() << ", " << m_buildings.value(building).y();
return 0;
}
if(m_buildings.key(pos, 0) != 0) {
kDebug() << "There is allready a building at this position" << pos.x() << ", " << pos.y();
return 0;
}
m_buildings.insert(building, pos);
Koushin::Field* field = m_fields.value(pos, 0);
if(field) {
field->setType(Koushin::fieldWithBuilding);
field->addBuilding(building);
building->setField(field);
}
return 1;
}
QMap< QString, QString > Koushin::Town::getPossibleBuildings(QMap< QString, QString > allBuildings) const
{
//Look for prerequisits, now: no prerequisits are implemented, so all buildings will returned
return allBuildings;
}
void Koushin::Town::markFields(QList< Koushin::Field* > fields)
{
foreach(Koushin::Field* field, fields)
field->markField();
}
bool isQStringListEmpty(const QStringList& list) {
foreach(QString entry, list)
if(!entry.isEmpty()) return false;
return true;
}
QList< Koushin::Field* > Koushin::Town::getPossibleFields(QPoint aroundPos, qreal radius, QList<Koushin::FieldType> types, const QStringList& buildingNames)
{
QList<Koushin::Field* > list;
foreach(QPoint point, m_fields.keys()) {
if(distance(point, aroundPos) <= radius) {
Koushin::Field* field = m_fields.value(point);
if(types.indexOf(field->getType()) != -1) {
if(field->getType() != Koushin::fieldWithBuilding || (isQStringListEmpty(buildingNames) || (field->getBuilding() && buildingNames.indexOf(field->getBuilding()->getName()) != -1 && field->getBuilding()->getAge() >= 0)))
list << field;
}
}
}
return list;
}
void Koushin::Town::unmarkAllFields()
{
foreach(Koushin::Field* field, m_fields.values())
field->unmarkField();
}
Koushin::Field* Koushin::Town::getFieldFromBuilding(Koushin::Building* building)
{
return m_fields.value(m_buildings.value(building));
}
Koushin::Field* Koushin::Town::getFieldFromPoint(QPoint point)
{
return m_fields.value(point);
}
QMap< QString, QString > Koushin::Town::getBuildingList()
{
if(m_owner)
return m_owner->getBuildingList();
return QMap<QString, QString>(); //avoid crash, but this case is actual not possible
}
void Koushin::Town::completeBuildingConstruction(Koushin::Building* building)
{
kDebug() << "Create Action";
KConfigGroup* tasksGroup = new KConfigGroup(building->getConfig(), "tasks");
QList<Action* > actions = ActionParser::createActionsFromConfig(tasksGroup, building, m_owner->getGame()->getCurrentRound());
foreach(Koushin::Action* action, actions)
building->insertAction(action);
m_owner->getActionManager()->addActionObject(building);
Koushin::ActionParser::parseGlobals(tasksGroup->group("globals"), m_owner->getActionManager());
}
void Koushin::Town::growBuildings()
{
foreach(Koushin::Building* building, m_buildings.keys()) {
building->setAge(building->getAge() + 1);
if(building->getAge() == 0)
completeBuildingConstruction(building);
}
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef GAME_H
#define GAME_H
#include "QObject"
#include "player.h"
namespace Koushin {
class Game : public QObject {
Q_OBJECT
public:
Game();
virtual ~Game();
void addPlayer(QString name) {if(!playernameAlreadyExists(name)) m_players << new Player(name, this);}
const QList<Player* > getPlayers() const {return m_players;}
const Player* getCurrentPlayer() const {return m_currentPlayer;}
const int getCurrentRound() const {return m_currentRound;}
void endRound();
void startRound();
private:
void shufflePlayers();
bool playernameAlreadyExists(QString name);
QList<Player* > m_players;
Player* m_currentPlayer;
int m_currentRound;
};
}
#endif // GAME_H
<file_sep>set (koushin_BLDGS
forester.config
lumberjack.config
lumbermill.config
warehouse.config
)
install(FILES ${koushin_BLDGS} DESTINATION ${DATA_INSTALL_DIR}/koushin/data/buildings)<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ACTIONOBJECT_H
#define ACTIONOBJECT_H
#include <QString>
#include <QStringList>
#include <QMap>
/**
* @brief This class provides like a QObject the possibility to receive or send actions.
* This class can not used direct.
**/
namespace Koushin {
class Action;
/**
* @brief This enum provides the information about the type of the derived class.
* Often the base class ActionObject is stored or returned. Before a cast to the derived class test the type. Each derived class should have his onw entry in this enum, so do not forget to add it here.
**/
enum actionObjectType{
actionObjectNotSpecified = 0,
actionObjectIsBuilding,
actionObjectIsTown,
actionObjectIsPlayer,
actionObjectIsField,
actionObjectNumber
};
/**
* @brief A little helper class to store informations about a function for an Action.
**/
class ActionProperties {
public:
ActionProperties(QStringList parameterTypes = QStringList(), QString description = "")
: parameterTypes(parameterTypes)
, description(description)
, activated(false) {}
void activate(QString desc) {
activated = true;
description = desc;
}
QStringList parameterTypes;
QString description;
bool activated;
};
/**
* @brief The basis class for all objects receiving of sending an Action.
* To derive from this class you have to implmenent the following functions:
* @code
* virtual const actionObjectType getActionObjectType()
* virtual const QString getLocal(QString name, QString additionalContent = QString())
* @endcode
* The the documentations belonging to this functions for details.
**/
class ActionObject : public QObject {
Q_OBJECT
public:
ActionObject();
/**
* @brief This function helps to find out the derived class.
*
* @return actionObjectType Each derived class should have a entry in the enum actionObjectType.
**/
virtual const actionObjectType getActionObjectType() = 0; // each class using this class has to return his type
/**
* @brief The Action can only be executed if this function provides the function name and the right parameters.
*
* @return QMap<QString, ActionProperties > The QMap contains the name and the corresponding properties.
**/
static const QMap<QString, ActionProperties> getPossibleActions();
QList<Action* > getAllActions();
bool insertAction(Action* action);
bool deleteAction(Action* action);
/**
* @brief This function replaces a local with a new value.
* Each derived class can have his own local parameter (here locals). Every local can either be added the the global or can replace the global.
*
* @param name The name of the local.
*
* @param content The new content for the local.
*
* @param replaceGlobal Decide, if the local replaces the global (true) or adds content to a global (false). Default is false.
*
* @return bool Like every action this function has to return a bool, indicating the succes of the execution.
**/
bool setLocalTo(QString name, QString content, bool replaceGlobal = false);
/**
* @brief This function add content to a local.
* Each derived class can have his own local parameter (here locals). Every local can either be added the the global or can replace the global.
*
* @param name The name of the local.
*
* @param content The additional content for the local.
*
* @param replaceGlobal Decide, if the local replaces the global (true) or adds content to a global (false). Default is false.
*
* @return bool Like every action this function has to return a bool, indicating the succes of the execution.
**/
bool addToLocal(QString name, QString content, bool replaceGlobal = false);
/**
* @brief Returns the local parameter.
* This final function should decide, if the parameter a global replacement or an additional content. If the parameter is an additional content add the content from the next "heigher" class (e.g. Town is the next heigher class for Building). As example the implementation from the building:
* @code
* if(m_globalReplacements.contains(name))
* return m_globalReplacements.value(name);
* if(m_globalAdditions.contains(name))
* additionalContent += m_globalAdditions.value(name);
* return m_town->getLocal(name, additionalContent);
* @endcode
*
* @param name The name of the local.
*
* @param additionalContent The optional additional content from a lower class. Default is QString().
*
* @return const QString The content of the local.
**/
virtual const QString getLocal(QString name, QString additionalContent = QString()) = 0;
QMap< QString, ActionProperties > adjustActionProperties(QMap< QString, Koushin::ActionProperties >& actions);
protected:
QMap<QString, QString> m_globalAdditions;
QMap<QString, QString> m_globalReplacements;
QList<Action* > m_actions;
};
}
#endif // ACTIONOBJECT_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gameview.h"
#include "resourceinfowidget.h"
#include "constructionmenu.h"
#include "townwidget.h"
#include <QtGui/QPushButton>
#include "buildinginfowidget.h"
#include <QtGui/QGraphicsView>
#include <QResizeEvent>
#include "player.h"
#include <KDebug>
class NonInteractiveView : public QGraphicsView {
public:
NonInteractiveView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent) {}
protected:
void mousePressEvent(QMouseEvent* event) {event->ignore();}
void mouseMoveEvent(QMouseEvent* event) {event->ignore();}
void mouseReleaseEvent(QMouseEvent* event) {event->ignore();}
void wheelEvent(QWheelEvent* event) {event->ignore();}
};
QPoint toPoint(const QPointF p1) {
return QPoint((int)p1.x(), (int)p1.y());
}
KoushinGUI::GameView::GameView()
: QWidget() //parent is not planed, because this widget shoul be the central widget showing all other widgets
, m_resourceInfo(new KoushinGUI::ResourceInfoWidget(this))
, m_constructionMenu(new KoushinGUI::ConstructionMenu(QMap<QString, QString>(), this))
, m_endRoundButton(new QPushButton("End Round",this))
, m_fieldInfo(new KoushinGUI::BuildingInfoWidget())
, m_townView(new NonInteractiveView(new QGraphicsScene(this), this))
, m_player(0)
, m_townWidget(0)
, m_focusRect(3, 3, 6, 6)
, m_townClicked(false)
{
// m_resourceInfo->close();
m_fieldInfo->setParent(this);
m_constructionMenu->close();
m_constructionMenu->setWindowFlags(Qt::Popup);
// m_fieldInfo->close();
m_townView->close();
m_townView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_townView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
void KoushinGUI::GameView::resizeEvent(QResizeEvent* event)
{
QRect widgetRect = QRect(QPoint(0,0), event->size());
QRect resourceInfoRect = QRect(widgetRect.left(), widgetRect.top(), widgetRect.width() * 2.0/3.0, 50);
QRect fieldInfoRect = QRect(resourceInfoRect.right(), widgetRect.top(),
widgetRect.width() - resourceInfoRect.width(), resourceInfoRect.height());
QRect townRect = QRect(widgetRect.left(), resourceInfoRect.bottom(),
widgetRect.width(), widgetRect.height() - resourceInfoRect.height());
QSize buttonHint = m_endRoundButton->minimumSizeHint();
QRect buttonRect = QRect(resourceInfoRect.right() - buttonHint.width(), (resourceInfoRect.height() - buttonHint.height())/2,
buttonHint.width(), buttonHint.height());
//adjust resource info widget:
m_resourceInfo->setGeometry(resourceInfoRect);
//adjust field info widget:
m_fieldInfo->setGeometry(fieldInfoRect);
//adjust town view:
// int zoom = 150; //per cent
// QRect zoomRect(0, 0, m_townView->sceneRect().width()*100/zoom, m_townView->sceneRect().height()*100/zoom);
m_townView->setGeometry(townRect);
m_townView->fitInView(m_focusRect, Qt::KeepAspectRatio);
m_focusRect = m_townView->mapToScene(m_townView->viewport()->geometry()).boundingRect();
//adjust construction menu:
m_constructionMenu->setPaintRange(QRect(mapToGlobal(townRect.topLeft()), mapToGlobal(townRect.bottomRight())));
//adjust end round button:
m_endRoundButton->setGeometry(buttonRect);
//call original resive event of QWidget:
QWidget::resizeEvent(event);
}
void KoushinGUI::GameView::changePlayer(Koushin::Player* player)
{
if(!player) return; //avoid crash
///@todo disconnect events
if(m_player) {
disconnect(m_player, SIGNAL(showConstructionMenu(Koushin::Town*,QPoint)));
disconnect(m_player, SIGNAL(closeConstructionMenu()));
disconnect(m_constructionMenu, SIGNAL(buildingChosen(QString)));
disconnect(m_player, SIGNAL(showResourceInfo(Koushin::Town*)));
disconnect(m_endRoundButton);
disconnect(m_player, SIGNAL(showFieldInfo(Koushin::Field*)));
disconnect(m_fieldInfo);
}
// change player:
m_player = player;
///@todo connect with new player
connect(m_player, SIGNAL(showConstructionMenu(Koushin::Town*, QPoint)), this, SLOT(showConstructionMenu(Koushin::Town*, QPoint)));
connect(m_player, SIGNAL(closeConstructionMenu()), this, SLOT(closeConstructionMenu()));
connect(m_constructionMenu, SIGNAL(buildingChosen(QString)), m_player, SLOT(buildingChosen(QString)));
connect(m_player, SIGNAL(showResourceInfo(Koushin::Town*)), this, SLOT(showResourceInfo(Koushin::Town*)));
connect(m_endRoundButton, SIGNAL(pressed()), m_player, SLOT(endRound()));
connect(m_player, SIGNAL(showFieldInfo(Koushin::Field*)), this, SLOT(showFieldInfo(Koushin::Field*)));
connect(m_fieldInfo, SIGNAL(fieldActionSelected(QListWidgetItem*)), m_player, SLOT(fieldActionSelected(QListWidgetItem*)));
connect(m_fieldInfo->getNextLevelButton(), SIGNAL(clicked()), m_player, SLOT(levelupBuilding()));
m_player->getTowns().first()->getTownWidget()->setParent(this);
}
void KoushinGUI::GameView::showTownView(Koushin::Town* town)
{
kDebug() << "Draw town";
if(town) {
if(m_townWidget) m_townView->scene()->removeItem(m_townWidget);
m_townWidget = town->getTownWidget();
m_townView->scene()->addItem(m_townWidget);
m_townView->show();
}
}
#include <KDebug>
#include <field.h>
void KoushinGUI::GameView::showConstructionMenu(Koushin::Town* town, QPoint point)
{
if(town) {
m_constructionMenu->setPossibleBuildings(town->getBuildingList());
point = mapFieldToDisplay(point);
m_constructionMenu->move(point.x(), point.y());
m_constructionMenu->show();
}
}
void KoushinGUI::GameView::closeConstructionMenu()
{
m_constructionMenu->close();
}
void KoushinGUI::GameView::showFieldInfo(Koushin::Field* field)
{
if(field)
m_fieldInfo->setBuilding(field->getBuilding());
else
m_fieldInfo->setBuilding(0);
m_fieldInfo->repaint();
m_fieldInfo->show();
}
void KoushinGUI::GameView::showResourceInfo(Koushin::Town* town)
{
m_resourceInfo->updateInfos(town->getResources().values());
m_resourceInfo->show();
}
QPoint KoushinGUI::GameView::mapFieldToDisplay(QPoint fieldPos) const
{
QPoint globalPoint = m_townView->mapFromScene(fieldPos);
globalPoint = m_townView->mapToGlobal(globalPoint);
return globalPoint;
}
void KoushinGUI::GameView::mouseMoveEvent(QMouseEvent* event)
{
qreal scale = m_townView->geometry().width() / m_focusRect.width();
QPointF shift = QPointF(event->posF() - m_oldPos) / scale;
QPointF centerPoint = m_focusRect.center() - shift;
m_townView->centerOn(centerPoint);
if((centerPoint.x() - m_focusRect.width()/2 < 0) ||
(centerPoint.x() + m_focusRect.width()/2 > m_townView->sceneRect().width())) {
m_oldPos.setX(m_oldPos.x() + shift.x());
}
if((centerPoint.y() - m_focusRect.height()/2 < 0) ||
(centerPoint.y() + m_focusRect.height()/2 > m_townView->sceneRect().height())) {
m_oldPos.setY(m_oldPos.y() + shift.y());
}
}
void KoushinGUI::GameView::mousePressEvent(QMouseEvent* event)
{
m_oldPos = event->posF();
//adjust focus rect, because with Qt::KeepAspectRation the rect is different from wanted rect
// if(items(m_oldPos).contains(m_townView->scene()));
m_townClicked = false;
if(m_townView->geometry().contains(m_oldPos.x(), m_oldPos.y())) m_townClicked = true;
m_focusRect = m_townView->mapToScene(m_townView->viewport()->geometry()).boundingRect();
}
void KoushinGUI::GameView::mouseReleaseEvent(QMouseEvent* event)
{
if(m_townClicked) {
qreal scale = m_townView->geometry().width() / m_focusRect.width();
if(m_oldPos == event->posF()) {
QPoint townPoint = toPoint(m_townView->mapToScene(event->pos() + pos() - m_townView->pos()));
m_player->fieldClicked(m_player->getTowns().first()->getFieldFromPoint(townPoint));
} else {
m_focusRect = m_townView->mapToScene(m_townView->viewport()->geometry()).boundingRect();
}
}
}
void KoushinGUI::GameView::wheelEvent(QWheelEvent* event)
{
qreal scale = 1.0;
if(event->delta() > 0)
scale = 2.0 - event->delta()/100.0;
else
scale = -event->delta()/100.0;
m_focusRect.setWidth(m_focusRect.width()*scale);
m_focusRect.setHeight(m_focusRect.height()*scale);
QPoint townPoint = toPoint(m_townView->mapToScene(event->pos() + pos() - m_townView->pos()).toPoint());
m_focusRect.moveCenter(townPoint);
m_townView->fitInView(m_focusRect);
m_focusRect = m_townView->mapToScene(m_townView->viewport()->geometry()).boundingRect();
QWidget::wheelEvent(event);
}
#include "gameview.moc"<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef RESOURCEINFOWIDGET_H
#define RESOURCEINFOWIDGET_H
#include <QtGui/QWidget>
#include "../town.h"
class QResizeEvent;
class QLabel;
namespace KoushinGUI {
class ResourceInfoWidget : public QWidget {
public:
ResourceInfoWidget(QWidget* parent = 0, Qt::WindowFlags f = 0);
virtual ~ResourceInfoWidget();
void updateInfos(QList<Koushin::Resource* > resources);
protected:
void resizeEvent(QResizeEvent* event);
private:
QLabel* m_label;
};
}
#endif // RESOURCEINFOWIDGET_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "actionparser.h"
#include "actionmanager.h"
#include "building.h"
#include "field.h"
#include "player.h"
#include "town.h"
#include <QRegExp>
#include <QString>
#include <kdebug.h>
#include "action.h"
#include "field.h"
QPair< QString, QStringList > Koushin::ActionParser::separateNameAndParameters(QString string)
{
QString actionName = string.split("(")[0];
string.remove(0, string.indexOf("(")+1); //remove all untill/inclusive the first "("
string.remove(string.length()-1, 1); //remove last char, should be ")"
QStringList parameters = string.split(",");
if (string.isEmpty()) parameters = QStringList();
return QPair<QString, QStringList>(actionName, parameters);
}
QList< Koushin::Action* > Koushin::ActionParser::createActionsFromConfig(KConfigGroup* tasksGroup, Koushin::ActionObject* newOwner, int currentRound, QString selectedGroup)
{
QMap<QString, Koushin::Action* > actions;
QStringList actionNames = tasksGroup->groupList();
//Create Actions:
foreach(QString actionName, actionNames) {
if(actionName == "globals" || actionName == "conditions") continue;
if(selectedGroup.isEmpty() || selectedGroup == actionName) {
KConfigGroup* actionGroup = new KConfigGroup(tasksGroup->group(actionName));
Koushin::Action* newAction = new Koushin::Action();
newAction->setOwner(newOwner);
newAction->setConfiguration(actionGroup);
setRoundLimit(newAction, actionGroup, currentRound);
actions.insert(actionName, newAction);
}
}
//write conditions to action:
///no conditions for field tasks are possible, because you can create more then one field action from one config
KConfigGroup conditionGroup = tasksGroup->group("conditions");
QStringList conditionsList;
foreach(QString condition, conditionGroup.keyList())
conditionsList << conditionGroup.readEntryUntranslated(condition, QString());
addRequirementsToActions(conditionsList, actions);
return actions.values();
}
void Koushin::ActionParser::setRoundLimit(Koushin::Action* action, KConfigGroup* config, int currentRound)
{
if(!action) return;
int fromRound = config->readEntry("fromRound", int(-1));
int toRound = config->readEntry("toRound", int(-1));
int intervall = config->readEntry("intervall", int(-1));
if(fromRound + toRound + intervall == -3)
action->executeInEveryRound(true);
else {
if(fromRound <= 0)
fromRound = currentRound + 1; //execute next round the first time
else
fromRound += currentRound;
if(toRound < fromRound)
toRound = fromRound;
else
toRound += currentRound;
if(intervall <= 0)
intervall = 1;
QList<int > roundList;
for(int i = fromRound; i <= toRound; i += intervall)
roundList << i;
action->executeInRounds(roundList);
action->executeInEveryRound(false);
}
}
void Koushin::ActionParser::addRequirementsToActions(QStringList conditionStrings, QMap< QString, Koushin::Action* > actions)
{
foreach(QString condition, conditionStrings) {
QStringList actionNames = condition.split("->");
if(actionNames.size() != 2) {
kDebug() << "Wrong condition string: " << condition;
continue;
}
QString requirement = actionNames[0];
requirement.remove(QRegExp("^!"));
if(actions.value(requirement, 0) == 0) {
kDebug() << "Requirement is not a valid action: " << actionNames[0];
}
if(actions.value(actionNames[1], 0) == 0) {
kDebug() << "The conditional action is not valid: " << actionNames[1];
}
if (requirement == actionNames[0]) {//no "!" as first char, so no char is removed, the strings are equal
actions.value(actionNames[1])->addRequirement(actions.value(requirement));
} else {
actions.value(actionNames[1])->addRequirement(actions.value(requirement), false);
}
}
}
bool Koushin::ActionParser::parseGlobals(const KConfigGroup& parameterList, Koushin::ActionManager* manager)
{
kDebug() << parameterList.keyList();
foreach(QString parameter, parameterList.keyList()) {
kDebug() << "################## Add Global " << parameter << "=" << parameterList.readEntry(parameter, QString()) << "########";
manager->addGlobalParameter(parameter, parameterList.readEntry(parameter, QString()));
}
return true;
}
QList<Koushin::ActionObject* > Koushin::ActionParser::parseRecipient(const QString& configLine, ActionObject* owner)
{
QString expectedObject = Koushin::ActionParser::separateNameAndParameters(configLine.split("->").last()).first;
QString linePart;
//find Players:
QList<Koushin::Player* > players;
if(!(linePart = configLine.section(QRegExp("player([A-Za-z0-9,=]*)"), 0)).isEmpty()) { //find e.g.: player(all,minPoints=1000)
players = findPlayers(Koushin::ActionParser::separateNameAndParameters(linePart).second, owner);
} else {
players = findPlayers(QStringList(), owner);
}
if(players.isEmpty()) {
kDebug() << "No reasonable player found" << linePart;
return QList<Koushin::ActionObject* >();
}
if(expectedObject == "player") {
QList<Koushin::ActionObject* > objects;
foreach(Koushin::Player* player, players)
objects << (Koushin::ActionObject*)player;
return objects;
}
//find Towns:
QList<Koushin::Town* > towns;
if(!(linePart = configLine.section(QRegExp("town([A-Za-z0-9,=]*)"), 0)).isEmpty()) { //find e.g.: town(all,hasBuilding=lumbermill)
towns = findTowns(Koushin::ActionParser::separateNameAndParameters(linePart).second, owner, players);
} else {
towns = findTowns(QStringList(), owner, players);
}
if(towns.isEmpty()) {
kDebug() << "No reasonable town found" << linePart;
return QList<Koushin::ActionObject* >();
}
if(expectedObject == "town") {
QList<Koushin::ActionObject* > objects;
foreach(Koushin::Town* town, towns)
objects << (Koushin::ActionObject*)town;
return objects;
}
//find Buildings:
QList<Koushin::Building* > buildings;
if(!(linePart = configLine.section(QRegExp("building([A-Za-z0-9,=]*)"), 0)).isEmpty()) { //find e.g.: building(current)
buildings = findBuildings(Koushin::ActionParser::separateNameAndParameters(linePart).second, owner, towns);
} else {
buildings = findBuildings(QStringList(), owner, towns);
}
if(buildings.isEmpty() && expectedObject != "field") {
kDebug() << "No reasonable building found" << linePart;
return QList<Koushin::ActionObject* >();
}
if(expectedObject == "building") {
QList<Koushin::ActionObject* > objects;
foreach(Koushin::Building* building, buildings)
objects << (Koushin::ActionObject*)building;
return objects;
}
//find Fields:
QList<Koushin::Field* > fields;
if(!(linePart = configLine.section(QRegExp("field([A-Za-z0-9,=]*)"), 0)).isEmpty()) { //find e.g.: field(current)
fields = findFields(Koushin::ActionParser::separateNameAndParameters(linePart).second, owner, towns);
} else {
fields = findFields(QStringList(), owner, towns);
}
if(fields.isEmpty()) {
kDebug() << "No reasonable field found" << linePart;
return QList<Koushin::ActionObject* >();
}
if(expectedObject == "field") {
QList<Koushin::ActionObject* > objects;
foreach(Koushin::Field* field, fields)
objects << (Koushin::ActionObject*)field;
return objects;
}
kDebug() << "Config contains unexpected recipient type: " << expectedObject;
return QList<Koushin::ActionObject* >();
}
QList< Koushin::Player* > Koushin::ActionParser::findPlayers(QStringList parameters, Koushin::ActionObject* owner)
{
QList<Koushin::Player* > players;
if(parameters.isEmpty()) parameters.insert(0, "current"); //set "current" as default
switch(owner->getActionObjectType()) {
case Koushin::actionObjectIsBuilding:
if(parameters.value(0) == "current")
players << ((Koushin::Building*)owner)->getTown()->getOwner();
break;
case Koushin::actionObjectIsField:
if(parameters.value(0) == "current")
players << ((Koushin::Field*)owner)->getTown()->getOwner();
break;
case Koushin::actionObjectIsTown:
if(parameters.value(0) == "current")
players << ((Koushin::Town*)owner)->getOwner();
break;
case Koushin::actionObjectIsPlayer:
if(parameters.value(0) == "current")
players << (Koushin::Player*)owner;
break;
default:
kDebug() << "Unknown action object type";
}
///@todo implement filters for players here
return players;
}
QList<Koushin::Town* > Koushin::ActionParser::findTowns(QStringList parameters, Koushin::ActionObject* owner, QList<Koushin::Player* > players)
{
QList<Koushin::Town* > towns;
if(parameters.isEmpty()) parameters.insert(0, "current");
//parse parameter 0:
switch(owner->getActionObjectType()) {
case Koushin::actionObjectIsBuilding:
if(parameters.value(0) == "current")
towns << ((Koushin::Building*)owner)->getTown();
break;
case Koushin::actionObjectIsField:
if(parameters.value(0) == "current")
towns << ((Koushin::Field*)owner)->getTown();
break;
case Koushin::actionObjectIsTown:
if(parameters.value(0) == "current")
towns << (Koushin::Town*)owner;
break;
case Koushin::actionObjectIsPlayer:
if(parameters.value(0) == "current")
kDebug() << "\"current\" does not make sense for a player as owner";
break;
default:
kDebug() << "Unknown action object type";
}
//sort out the towns which are not owned by the players in list:
foreach(Koushin::Town* town, towns) {
if(!players.contains(town->getOwner())) towns.removeAll(town);
}
///@todo implement filters for towns here
return towns;
}
QList< Koushin::Building* > Koushin::ActionParser::findBuildings(QStringList parameters, Koushin::ActionObject* owner, QList< Koushin::Town* > towns)
{
QList<Koushin::Building* > buildings;
if(parameters.isEmpty()) parameters.insert(0, "current");
//parse parameter 0:
switch(owner->getActionObjectType()) {
case Koushin::actionObjectIsBuilding:
if(parameters.value(0) == "current")
buildings << (Koushin::Building*)owner;
break;
case Koushin::actionObjectIsField:
if(parameters.value(0) == "current") {
Koushin::Field* field = (Koushin::Field*)owner;
if (field->getBuilding())
buildings << field->getBuilding();
}
break;
case Koushin::actionObjectIsTown:
if(parameters.value(0) == "current")
kDebug() << "\"current\" does not make sense for a town as owner";
break;
case Koushin::actionObjectIsPlayer:
if(parameters.value(0) == "current")
kDebug() << "\"current\" does not make sense for a player as owner";
break;
default:
kDebug() << "Unknown action object type.";
}
//sort out the towns which are not owned by the players in list:
foreach(Koushin::Building* building, buildings) {
if(!towns.contains(building->getTown())) buildings.removeAll(building);
}
///@todo implement filters for towns here
return buildings;
}
QList<Koushin::Field* > Koushin::ActionParser::findFields(QStringList parameters, Koushin::ActionObject* owner, QList< Koushin::Town* > towns)
{
QList<Koushin::Field* > fields;
if(parameters.isEmpty()) parameters.insert(0, "current");
//parse parameter 0:
switch(owner->getActionObjectType()) {
case Koushin::actionObjectIsBuilding:
if(parameters.value(0) == "current")
fields << ((Koushin::Building*)owner)->getTown()->getFieldFromBuilding((Koushin::Building*)owner);
break;
case Koushin::actionObjectIsField:
if(parameters.value(0) == "current") {
fields << (Koushin::Field*)owner;
}
break;
case Koushin::actionObjectIsTown:
if(parameters.value(0) == "current")
kDebug() << "\"current\" does not make sense for a town as owner";
break;
case Koushin::actionObjectIsPlayer:
if(parameters.value(0) == "current")
kDebug() << "\"current\" does not make sense for a player as owner";
break;
default:
kDebug() << "Unknown action object type.";
}
//sort out the towns which are not owned by the players in list:
foreach(Koushin::Field* field, fields) {
if(!towns.contains(field->getTown())) fields.removeAll(field);
}
///@todo implement filters for towns here
return fields;
}
void Koushin::ActionParser::createOpenFieldActions(KConfigGroup* config, Koushin::Building* building)
{
foreach(QString name, config->groupList()) {
KConfigGroup* taskGroup = new KConfigGroup(config->group(name));
qreal number = taskGroup->readEntry("numberOfFields", qreal(1));
number += (qreal)building->getLevel() * taskGroup->readEntry("numberOfFieldsPerLevel", qreal(0));
number -= building->getNumberOfCreatedOpenFieldActions(name);
kDebug() << "Create " << (int)number << " actions of " << taskGroup->name();
for(int i = 0; i < (int)number; ++i) {
building->addOpenFieldAction(name);
}
}
}
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "field.h"
#include "GUI/townwidget.h"
#include <qgraphicsitem.h>
#include <QGraphicsRectItem>
#include <QBrush>
#include <kdebug.h>
#include <QMetaClassInfo>
#include "actionparser.h"
Koushin::Field::Field(Koushin::Town* town, Koushin::FieldType type)
: m_type(type)
, m_town(town)
, m_building(0)
, m_isMarked(false)
{
if(town)
m_fieldItem = new KoushinGUI::FieldItem(this);
else
m_fieldItem = 0;
}
Koushin::Field::Field(const Koushin::Field& oldField)
: m_type(oldField.getType())
, m_town(oldField.getTown())
, m_resources(oldField.getResources())
, m_building(oldField.getBuilding())
, m_fieldItem(oldField.getFieldItem())
, m_isMarked(oldField.isMarked())
{
kDebug() << "Field is copied";
}
QString Koushin::Field::fieldTypeToQString(Koushin::FieldType type)
{
if(type == Koushin::plainField)
return "plainField";
if(type == Koushin::fieldWithBuilding)
return "fieldWithBuilding";
if(type == Koushin::fieldWithForest)
return "fieldWithForest";
if(type == Koushin::fieldWithRocks)
return "fieldWithRocks";
if(type == Koushin::fieldWithWater)
return "fieldWithWater";
if(type == Koushin::fieldNotUsable)
return "fieldNotUsable";
return "";
}
Koushin::FieldType Koushin::Field::QStringToFieldType(QString string)
{
if(string == "fieldWithBuilding")
return Koushin::fieldWithBuilding;
if(string == "fieldWithForest")
return Koushin::fieldWithForest;
if(string == "fieldWithRocks")
return Koushin::fieldWithRocks;
if(string == "fieldWithWater")
return Koushin::fieldWithWater;
if(string == "fieldNotUsable")
return Koushin::fieldNotUsable;
return Koushin::plainField;
}
const Koushin::actionObjectType Koushin::Field::getActionObjectType()
{
return Koushin::actionObjectIsField;
}
const QString Koushin::Field::getLocal(QString name, QString additionalContent)
{
if(m_globalReplacements.contains(name))
return m_globalReplacements.value(name);
if(m_globalAdditions.contains(name))
additionalContent += m_globalAdditions.value(name);
return m_town->getLocal(name, additionalContent);
}
const QMap< QString, Koushin::ActionProperties > Koushin::Field::getPossibleActions()
{
QMap<QString, Koushin::ActionProperties> actions;
for(int i = 0; i < metaObject()->methodCount(); ++i) {
QPair<QString, QStringList> function = Koushin::ActionParser::separateNameAndParameters(metaObject()->method(i).signature());
Koushin::ActionProperties prop(function.second, QString());
if(function.first == "gatherResource") {
prop.activate("Reduces the resource of this field and adds the amount to the town. string=ResourceType, int=value");
}
else if(function.first == "growResource") {
prop.activate("Increases a resource for a field. string=ResourceType, ind=value");
}
actions.insert(function.first, prop);
}
adjustActionProperties(actions);
kDebug() << actions.keys();
return actions;
}
bool Koushin::Field::gatherResource(Koushin::ResourceType type, int value)
{
if(!m_town)
kDebug() << "no town given";
kDebug() << "gather resource: " << value << " of " << ((type == Koushin::ResourceWood) ? "Wood" : "something");
int currentResource = getResource(type);
Koushin::Resource* resource = m_town->getResources().value(type);
int spaceInTown = resource->maximumCapacity - resource->amount;
kDebug() << "gather Resource. Space in Town: " << spaceInTown << " and remaining Resource: " << currentResource;
if(currentResource == 0 || spaceInTown == 0) return false;
value = qMin(value, currentResource);
value = qMin(value, spaceInTown);
addToResource(type, -value);
m_town->changeResource(type, value);
kDebug() << "gatherResource: " << value;
return true;
}
bool Koushin::Field::growResource(Koushin::ResourceType type, int value)
{
addToResource(type, value);
return true;
}
<file_sep>#ifndef KOUSHIN_EDITOR_H
#define KOUSHIN_EDITOR_H
#include <QObject>
#include "field.h"
#include <KConfigGroup>
class QListWidgetItem;
namespace Koushin_TownEditor {
class Editor : public QObject {
Q_OBJECT
public:
Editor();
int m_fieldSize;
KConfigGroup* m_config;
QStringList m_fieldTypes;
public Q_SLOTS:
void fieldClicked(EditorField* field);
void fieldTypeChanged(QListWidgetItem* item);
private:
QString m_type;
};
}
#endif //KOUSHIN_EDITOR_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PLAYER_H
#define PLAYER_H
#include <QList>
#include <QObject>
#include <QPoint>
#include <QMap>
#include "actionobject.h"
#include "GUI/resourceinfowidget.h"
#include <KConfigGroup>
class QListWidgetItem;
namespace KoushinGUI {
class ConstructionMenu;
class BuildingInfoWidget;
}
namespace Koushin {
class Game;
class ActionManager;
class Town;
class Game;
namespace PlayerInteraction {
enum Interaction {
noInteraction = 0,
plainFieldClicked,
buildingClicked,
freeFieldActionChoosen,
roundedEnded,
roundedStarted
};
}
class Player : public ActionObject {
Q_OBJECT
public:
Player(QString name = QString(), Game* game = 0);
virtual ~Player();
QList<Town* > getTowns() const {return m_townList;}
ActionManager* getActionManager() const {return m_actionManager;}
void setActionManager(ActionManager* manager) {m_actionManager = manager;}
void addTown(Town* town) {m_townList << town;}
void setBuildingList(QMap<QString, QString> buildings) {m_listOfAllBuildings = buildings;}
QString getName() const {return m_name;}
void setSelectedBuilding(Building* building);
Game* getGame() const {return m_game;}
const actionObjectType getActionObjectType() {return actionObjectIsPlayer;}
const QMap<QString, ActionProperties> getPossibleActions();
const QString getLocal(QString name, QString additionalContent = QString());
QMap<QString, QString> getBuildingList() const {return m_listOfAllBuildings;}
Q_SIGNALS:
void showConstructionMenu(Koushin::Town*, QPoint);
void closeConstructionMenu();
void showResourceInfo(Koushin::Town*);
void showFieldInfo(Koushin::Field*);
public Q_SLOTS:
//public actions
bool setGlobalTo(QString name, QString content);
bool addToGlobal(QString name, QString content);
//interactions with game
void endRound();
void startRound();
void fieldClicked(Field* field);
void buildingChosen(QString buildingConfig);
void fieldActionSelected(QListWidgetItem* item);
void levelupBuilding();
private:
void townClicked(QPoint point);
void fieldForActionChosen(Field* field);
QList<Town* > m_townList;
ActionManager* m_actionManager;
QMap<QString, QString> m_listOfAllBuildings;
QPoint m_buildingLot;
// KoushinGUI::BuildingInfoWidget* m_buildingInfo;
QString m_name;
Game* m_game;
Building* m_selectedBuilding;
QString m_openFieldConfig;
PlayerInteraction::Interaction m_lastInteraction;
QList<Field* > m_fieldsForFieldAction;
};
}
#endif // PLAYER_H
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "buildinginfowidget.h"
#include <building.h>
#include <KConfigGroup>
#include <KDebug>
#include <QPushButton>
KoushinGUI::BuildingInfoWidget::BuildingInfoWidget()
: m_building(0)
, m_list(new QListWidget(this))
, m_nextLevelButton(new QPushButton("Level up", this))
{
m_list.setSelectionMode(QAbstractItemView::SingleSelection);
connect(&m_list, SIGNAL(itemActivated(QListWidgetItem*)), this, SIGNAL(fieldActionSelected(QListWidgetItem*)));
m_nextLevelButton->hide();
}
void KoushinGUI::BuildingInfoWidget::repaint()
{
QSize buttonSize = m_nextLevelButton->minimumSizeHint();
m_list.setGeometry(0, 0, width(), height() - buttonSize.height());
m_nextLevelButton->setGeometry(0, height() - buttonSize.height(), buttonSize.width(), buttonSize.height());
kDebug() << "Repaint of building info";
if(!m_building || m_building->getAge() < 0) {
m_list.clear();
m_nextLevelButton->hide();
return;
}
QStringList itemStrings;
foreach(QString groupName, m_building->getOpenFieldActions())
if(!itemStrings.contains(groupName)) itemStrings << groupName;
m_list.clear();
m_list.addItems(itemStrings);
m_list.show();
m_nextLevelButton->show();
}
#include "buildinginfowidget.moc"
<file_sep>/*
<one line to give the library's name and an idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ACTIONMANAGER_H
#define ACTIONMANAGER_H
#include <QMultiMap>
#include <QString>
namespace Koushin {
class ActionObject;
class Action;
class Player;
class ActionManager {
public:
ActionManager(Player* owner);
virtual ~ActionManager();
bool addActionObject(ActionObject* object);
bool removeActionObject(ActionObject* object);
void executeActions(int currentRound);
bool executeAction(Action* action);
void setStatusOfDependensies(Action* failedAction);
Player* getOwner() {return m_owner;}
bool addGlobalParameter(QString name, QString content);
QString getGlobalParameterValue(QString name) const {return m_globalParameters.value(name);}
bool setGlobalParameterContent(QString name, QString content);
bool addContentToGlobalParameter(QString name, QString content);
int evalParameter(QString parameter);
int evalContent(QString content, QString parameter = "NOT_IN_LIST");
void resetGlobalParameters();
private:
QString expandParameter( QString line, QString name);
QList<ActionObject* > m_actionObjects;
Player* m_owner;
QMap<QString, QString> m_globalParameters; //map with name and content
};
}
#endif // ACTIONMANAGER_H
|
7a0f961ab9c3c85ca11f43ec222e6d077eb88c85
|
[
"CMake",
"C++"
] | 46
|
C++
|
HobbyBlobby/Koushin
|
4f59ce7285a55815db23781fa59905d3438dce7d
|
52e76e30c3293d23a96c7f89cf0e3614b79cacce
|
refs/heads/master
|
<repo_name>scaldas/CM20151_HW8_CaldasSebastian<file_sep>/codigoSubmissions/MiercolesRegresionPorEventos.R
library(lubridate)
library(caret)
library(dplyr)
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/training_set.csv'
file_test <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/test_set.csv'
dat <- read.csv(file,header=T)
dat_test <- read.csv(file_test,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat_test$diasemana <- wday(as.Date(dat_test$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat <- dplyr::mutate(dat, categoria = ifelse(dat$eventos=='Niebla' | dat$eventos== 'Niebla-Lluvia-Nieve' | dat$eventos== 'Niebla-Nieve' | dat$eventos== 'Lluvia-Tormenta', 'Otros', ifelse(dat$eventos=='Lluvia-Nieve','Lluvia-Nieve', ifelse(dat$eventos=='Niebla-Lluvia','Niebla-Lluvia',ifelse(dat$eventos=='Nieve','Nieve',ifelse(dat$eventos=='Lluvia', 'Lluvia', 'Ninguno'))))))
dat_test <- dplyr::mutate(dat_test, categoria = ifelse(dat_test$eventos=='Niebla' | dat_test$eventos== 'Niebla-Lluvia-Nieve' | dat_test$eventos== 'Niebla-Nieve' | dat_test$eventos== 'Lluvia-Tormenta', 'Otros', ifelse(dat_test$eventos=='Lluvia-Nieve','Lluvia-Nieve', ifelse(dat_test$eventos=='Niebla-Lluvia','Niebla-Lluvia',ifelse(dat_test$eventos=='Nieve','Nieve',ifelse(dat_test$eventos=='Lluvia', 'Lluvia', 'Ninguno'))))))
dat <- dplyr::mutate(dat, categoria_num = ifelse(dat$categoria=='Otros', 2, ifelse(dat$categoria=='Lluvia-Nieve',0, ifelse(dat$categoria=='Niebla-Lluvia',1,ifelse(dat$categoria=='Nieve',3,ifelse(dat$categoria=='Lluvia', 4, 5))))))
dat_test <- dplyr::mutate(dat_test, categoria_num = ifelse(dat_test$categoria=='Otros', 2, ifelse(dat_test$categoria=='Lluvia-Nieve',0, ifelse(dat_test$categoria=='Niebla-Lluvia',1,ifelse(dat_test$categoria=='Nieve',3,ifelse(dat_test$categoria=='Lluvia', 4, 5))))))
dat.cat <- dplyr::filter(dat, categoria_num==1 | categoria_num==2 | categoria_num==0)
dat_test.cat <- dplyr::filter(dat_test, categoria_num==1 | categoria_num==2 | categoria_num==0)
modFit <- train(conteo_ordenes ~ conteo_restaurantes + cod_calendario, method = "lm",data=dat.cat)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test.cat)
dat_test.cat$prediction <- round(pred,digits=0)
submission <- dat_test.cat
for (i in 3:5)
{
dat.cat <- dplyr::filter(dat, categoria_num==i)
dat_test.cat <- dplyr::filter(dat_test, categoria_num==i)
modFit <- train(conteo_ordenes ~ conteo_restaurantes + cod_calendario, method = "lm",data=dat.cat)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test.cat)
dat_test.cat$prediction <- round(pred,digits=0)
submission <- dplyr::union(submission, dat_test.cat)
}
sumbission.write <- data.frame(fecha = submission$fecha, conteo_ordenes = submission$prediction)
write.csv(sumbission.write, '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/scaldas_submission3.csv', row.names=FALSE)
<file_sep>/codigoSubmissions/MiercolesEventosAMejores.R
library(lubridate)
library(caret)
library(dplyr)
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/training_set.csv'
file_test <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/test_set.csv'
dat <- read.csv(file,header=T)
dat_test <- read.csv(file_test,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat_test$diasemana <- wday(as.Date(dat_test$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat <- dplyr::mutate(dat, categoria = ifelse(dat$eventos=='Niebla' | dat$eventos== 'Niebla-Lluvia-Nieve' | dat$eventos== 'Niebla-Nieve' | dat$eventos== 'Lluvia-Tormenta', 'Otros', ifelse(dat$eventos=='Lluvia-Nieve','Lluvia-Nieve', ifelse(dat$eventos=='Niebla-Lluvia','Niebla-Lluvia',ifelse(dat$eventos=='Nieve','Nieve',ifelse(dat$eventos=='Lluvia', 'Lluvia', 'Ninguno'))))))
dat_test <- dplyr::mutate(dat_test, categoria = ifelse(dat_test$eventos=='Niebla' | dat_test$eventos== 'Niebla-Lluvia-Nieve' | dat_test$eventos== 'Niebla-Nieve' | dat_test$eventos== 'Lluvia-Tormenta', 'Otros', ifelse(dat_test$eventos=='Lluvia-Nieve','Lluvia-Nieve', ifelse(dat_test$eventos=='Niebla-Lluvia','Niebla-Lluvia',ifelse(dat_test$eventos=='Nieve','Nieve',ifelse(dat_test$eventos=='Lluvia', 'Lluvia', 'Ninguno'))))))
dat <- dplyr::mutate(dat, categoria_num = ifelse(dat$categoria=='Otros', 2, ifelse(dat$categoria=='Lluvia-Nieve',0, ifelse(dat$categoria=='Niebla-Lluvia',1,ifelse(dat$categoria=='Nieve',3,ifelse(dat$categoria=='Lluvia', 4, 5))))))
dat_test <- dplyr::mutate(dat_test, categoria_num = ifelse(dat_test$categoria=='Otros', 2, ifelse(dat_test$categoria=='Lluvia-Nieve',0, ifelse(dat_test$categoria=='Niebla-Lluvia',1,ifelse(dat_test$categoria=='Nieve',3,ifelse(dat_test$categoria=='Lluvia', 4, 5))))))
dias <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
for (i in 1:7 )
{
dat.dia <- dplyr::filter(dat, diasemana==dias[i])
dat_test.dia <- dplyr::filter(dat_test, diasemana==dias[i])
modFit <- train(conteo_ordenes ~ conteo_restaurantes + cod_calendario + categoria_num, method = "lm",data=dat.dia)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test.dia)
dat_test.dia$prediction <- round(pred,digits=0)
if (i == 1)
{
submission <- dat_test.dia
}
else
{
submission <- dplyr::union(submission, dat_test.dia)
}
}
sumbission.write <- data.frame(fecha = submission$fecha, conteo_ordenes = submission$prediction)
write.csv(sumbission.write, '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/scaldas_submission3.csv', row.names=FALSE)
<file_sep>/HW8.Rmd
---
title: "HW8"
author: "<NAME>"
date: "May 21, 2015"
output: html_document
---
```{r, echo=FALSE, message=FALSE}
library(lubridate)
library(dplyr)
library(ggplot2)
library(caret)
```
This Markdown will be a simple one, answering the suggested questions by the Kaggle competition and briefly describing the process that led to the models selected for submission. The process will be presented as a journal, briefly showing the thought process that led to each day's particular submissions. Firstly, let's show the "journal":
1. Monday was the first day of work, and it was all about naive approaches. The first important insight was that the date by itself meant nothing, and more relevant information could be derived from it. The two pieces of information that could be obtained were day of the week (Monday, Tuesday, etc.) and month. Both derivations were straightforward using lubridate. The models submitted were the following:
+ A multiple lineal regression depending only on day of the week. The results were not good according to Kaggle.
+ A multiple lineal regression depending on day of the week and restaurant count. This other variable was chosen based on 1.png, where the cloud of dots suggest a correlation between restaurant count and order count.
+ A multiple lineal regression depending on day of the week, restaurant count and calendar code. This last variable was added after carefully looking at the data, and seeing that this code somehow represented holidays and the like. It is to be expected fot this holidays to affect any business. As such, it was included. **This model gave the best results of the day**.
+ A multiple lineal regression depending on the same variables as before plus month. The results deteriorated, and careful consideration shows that month will not be telling enough in this particular excercise. Although we have data for different months, but have no data of the months we wish to predict. As such, the real impact of this variable on the test data will not be known and we could be over-fitting to out testing set.
2. Tuesday was about trying to make several lineal regressions instead of just one. Particularly, the though was that a lineal regression for each different day of the week would treat business on Mondays as different from business on Tuesdays, and so on. This intuition seemed sound and the models implemented were the following:
+ A multiple lineal regression for each day of the week. Each regression used both restaurant count and calendar code as predicting variables.
+ A multiple lineal regression for each day of the week. Each regression used restaurant count, calendar code and precipitation as predicting variables. Precipitation was included just to start playing around with the influence of weather, but as 1.png shows, this particular variable does not seem to influence order count. **This model ended up being the best model of the day, although I don't trust it.**
+ The same as before but with average temperature instead of precipitation as a predicting variable ($\frac{temp_{max} + temp_{min}}{2}$).
+ The same as the two preceding but using minimum temperature instead of average temperature (it is seen in 1.png that both temperatures are related, and because the average is a function of the two, it is actually redundant).
3. Wednesday was about finally trying to fit weather into the predictions. The models follow this idea:
+ The first model still makes a lineal regression for each day of the week. Each regression depends on restaurant count, calendar code and a new variable X. X is derived from "events" by making it binary: It is 0 if there was no event, and 1 if there was any. I think this variable could take into account both temperature and precipitation.
+ The previous idea is refined a little. Instead of X being binary, it just merges the caregories with the lowest frequencies until each one has a minimum of 5 occurrences (this is based on the buckets that one uses to make a goodness of fit test, each having at least 5 occurrences). **This is the best model of the day, with similar results that the best of the second day and a model I am much more confident about**.
+ This model makes a lineal regression for each of the categories in variable X, not for each day! Each regression depends on restaurant count and calendar code. The implementation seems flawed though, as R warns that the model is ending up as a constant for some categories. The fix was to keep merging categories until the warning disappeared. As such, the model is not trusted (and the results were not that great either).
+ I return to a lineal regression for each day of the week and decide to divide precipitation into 11 buckets, and use the number of the bucket as a predicting variable.
+ I use the same idea as before with average temperature. Precipitation is kept as a predicting variable. The results deteriorate considerably.
3. Thursay is the day of organizing results. If there is time left, other models apart from lineal regressions will be tried (using the insights already found), but they will not be described in this Markdown.
```{r, echo=FALSE}
#Please change the file path!
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/training_set.csv'
dat <- read.csv(file,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
```
The following answers are taken from the testing data only:
1. The day of the week with the most orders is:
```{r, echo=FALSE}
dat_by_day <- group_by(dat, diasemana)
freq <- summarise(dat_by_day, count=sum(conteo_ordenes))
mx <- summarise(freq, max(count))
mx <- filter(freq, count == mx[[1]])
mx[[1]]
```
2. The day of the week with the least orders is:
```{r, echo=FALSE}
dat_by_day <- group_by(dat, diasemana)
freq <- summarise(dat_by_day, count=sum(conteo_ordenes))
mn <- summarise(freq, min(count))
mn <- filter(freq, count == mn[[1]])
mn[[1]]
```
3. Other information that may have been useful:
+ This task could have been more successful had we had information about the company: what does it produce? where does it opperate? The first question would have been especially useful, as it would have provided clues to predict peaks based on important dates. A company that produces candy will have peaks during early February and late October, while one that sells cleaning supplies may not have such variations in any months. The product or service offered would have also given insights about the relative importance of each variable. For example, if the company offers thermostat repairing services, it will be needed most in days when it snows. All of the previous examples could be hired by restaurants, and as such are plausible (if not a little far fetched) for the company we are predicting for.
+ I also believe that, just like business on Mondays is not the same as business on Tuesdays, business in September is not the same as business in October. As such, because we were not given any training data for October, any prediction about business in that month will necessarily be off. We are asked to predict for dates in a month for which we have no information. What if the company sold gummy bears? They would have a peak in October we could not predict in any way. The example is not realistic (no gummy bears company would have clients on a day with tempeartures under zero degrees) but presents my point: we are shooting in the dark here.
```{r, echo=FALSE, warning=FALSE}
#Please change the file path!
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/training_set.csv'
file_submitted <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/best_submission.csv'
dat <- read.csv(file,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat <- select(dat, fecha, diasemana, conteo_ordenes)
dat_submitted <- read.csv(file_submitted,header=T)
dat_submitted$diasemana <- wday(as.Date(dat_submitted$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat <- bind_rows(dat, dat_submitted)
```
The following answers take into account the best trusted submission (the best of the third day):
1. The day of the week with the most orders is:
```{r, echo=FALSE}
dat_by_day <- group_by(dat, diasemana)
freq <- summarise(dat_by_day, count=sum(conteo_ordenes))
mx <- summarise(freq, max(count))
mx <- filter(freq, count == mx[[1]])
mx[[1]]
```
2. The day of the week with the least orders is:
```{r, echo=FALSE}
dat_by_day <- group_by(dat, diasemana)
freq <- summarise(dat_by_day, count=sum(conteo_ordenes))
mn <- summarise(freq, min(count))
mn <- filter(freq, count == mn[[1]])
mn[[1]]
```
<file_sep>/codigoSubmissions/Domingo.R
library(lubridate)
library(dplyr)
library(ggplot2)
library(caret)
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/training_set.csv'
file_test <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/test_set.csv'
dat <- read.csv(file,header=T)
dat_test <- read.csv(file_test,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat_test$diasemana <- wday(as.Date(dat_test$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat$mes <- month(dat$fecha)
dat_test$mes <- month(dat_test$fecha)
dat$temp_prom <- (dat$temp_min + dat$temp_max)/2
dat_test$temp_prom <- (dat_test$temp_min + dat_test$temp_max)/2
#featurePlot(x=dat[,c("conteo_restaurantes","temp_max","temp_prom", "precipitacion")],
y = dat$conteo_ordenes,
plot="pairs")
#ggplot(dat, aes(x=fecha, y=conteo_ordenes)) + geom_point(shape=1) + facet_wrap( ~ diasemana, ncol=2)
#ggplot(dat, aes(x=fecha, y=conteo_ordenes)) + geom_point(shape=1) + facet_wrap( ~ mes, ncol=2)
#ggplot(dat, aes(x=fecha, y=conteo_ordenes)) + geom_point(shape=1) + facet_wrap( ~ cod_calendario, ncol=2)
#ggplot(dat, aes(x=fecha, y=conteo_ordenes)) + geom_point(shape=1) + facet_wrap( ~ eventos, ncol=2)
modFit <- train(conteo_ordenes ~ conteo_restaurantes + diasemana + cod_calendario + mes, method = "lm",data=dat)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test)
dat_test$prediction <- round(pred,digits=0)
submission <- data.frame(fecha = dat_test$fecha, conteo_ordenes = dat_test$prediction)
write.csv(submission, '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/scaldas_submission1.csv', row.names=FALSE)
<file_sep>/codigoSubmissions/Martes.R
library(lubridate)
library(caret)
library(dplyr)
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/training_set.csv'
file_test <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/test_set.csv'
dat <- read.csv(file,header=T)
dat_test <- read.csv(file_test,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat_test$diasemana <- wday(as.Date(dat_test$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat$mes <- month(dat$fecha)
dat_test$mes <- month(dat_test$fecha)
dat$temp_prom <- (dat$temp_min + dat$temp_max)/2
dat_test$temp_prom <- (dat_test$temp_min + dat_test$temp_max)/2
dias <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
for (i in 1:7 )
{
dat.dia <- dplyr::filter(dat, diasemana==dias[i])
dat_test.dia <- dplyr::filter(dat_test, diasemana==dias[i])
modFit <- train(conteo_ordenes ~ conteo_restaurantes + cod_calendario + temp_min, method = "lm",data=dat.dia)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test.dia)
dat_test.dia$prediction <- round(pred,digits=0)
if (i == 1)
{
submission <- dat_test.dia
}
else
{
submission <- dplyr::union(submission, dat_test.dia)
}
}
sumbission.write <- data.frame(fecha = submission$fecha, conteo_ordenes = submission$prediction)
write.csv(sumbission.write, '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/scaldas_submission2.csv', row.names=FALSE)
<file_sep>/codigoSubmissions/MiercolesEventosABinaria.R
library(lubridate)
library(caret)
library(dplyr)
file <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/training_set.csv'
file_test <- '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/CM20151_HW8_CaldasSebastian/data/test_set.csv'
dat <- read.csv(file,header=T)
dat_test <- read.csv(file_test,header=T)
dat$diasemana <- wday(as.Date(dat$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat_test$diasemana <- wday(as.Date(dat_test$fecha,'%Y-%m-%d'), label=TRUE, abbr = FALSE)
dat <- dplyr::mutate(dat, categoria = ifelse(dat$eventos=='Ninguno', 'Ninguno', 'Otro'))
dat_test <- dplyr::mutate(dat_test, categoria = ifelse(dat_test$eventos=='Ninguno', 'Ninguno', 'Otro'))
dias <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
for (i in 1:7 )
{
dat.dia <- dplyr::filter(dat, diasemana==dias[i])
dat_test.dia <- dplyr::filter(dat_test, diasemana==dias[i])
modFit <- train(conteo_ordenes ~ conteo_restaurantes + cod_calendario + categoria, method = "lm",data=dat.dia)
finMod <- modFit$finalModel
pred <- predict(modFit,dat_test.dia)
dat_test.dia$prediction <- round(pred,digits=0)
if (i == 1)
{
submission <- dat_test.dia
}
else
{
submission <- dplyr::union(submission, dat_test.dia)
}
}
sumbission.write <- data.frame(fecha = submission$fecha, conteo_ordenes = submission$prediction)
write.csv(sumbission.write, '/Users/caldasrivera/Dropbox/UniAndes/Semestres Academicos/Septimo Semestre/Metodos Computacionales/Tareas/Tarea8/datos/scaldas_submission3.csv', row.names=FALSE)
<file_sep>/README.md
# CM20151_HW8_CaldasSebastian
Desarrollo de la Tarea 8 de Métodos Computacionales (complemento a lo presentado en Kaggle)
|
c680191138c9171615a2cf7cb585b7acf42de45b
|
[
"Markdown",
"R",
"RMarkdown"
] | 7
|
R
|
scaldas/CM20151_HW8_CaldasSebastian
|
b33037ec38a73715f96edc5a4c37252a5c9466b2
|
d0cebb6246682000c51771b377bd808c47ef7c5d
|
refs/heads/master
|
<file_sep>'use strict';
var items = ['ivandro', 'ordnavi', 'leamsi', 'ismael'];
items.forEach((item, idx) => {
console.log(item);
});
console.log('Hello world');
<file_sep># BasicRouting
<file_sep>'use strict';
var http = require('http');
var fs = require('fs');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
if (req.url === "/home" || req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/index.html', 'utf8').pipe(res);
}
else if (req.url === "/contact") {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/contact.html', 'utf8').pipe(res);
}
else if (req.url === "/api/ninjas") {
res.writeHead(200, { 'Content-Type': 'application/json' });
var ninjas = [
{
name: 'ivandro',
age: 20,
job: 'ninja'
},
{
name: 'ordnavi',
age: 12,
job: 'gamer'
},
{
name: 'leamsi',
age: 23,
job: 'coder'
}
];
var jsonString = JSON.stringify(ninjas);
res.end(jsonString);
}
else {
res.writeHead(404, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/404.html', 'utf8').pipe(res);
}
}).listen(port);
// note: routing can be done with a "express" (package) <file_sep># ServingJson
<file_sep>'use strict';
const http = require('http');
const express = require('express');
const todoController = require('./controllers/todoController');
let app = express();
// set up template engine
app.set('view engine', 'ejs');
// static files
app.use(express.static('./public'));
todoController(app);
const port = 3000;
app.listen(port);
console.log(`you are listening to port: ${port}`);<file_sep>
var http = require('http');
var http1 = require("http");
var server = http.createServer(function (req, res) {
// prints out request url
console.log(req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hey ninjas');
});
const port = 3000;
// the ip is just localhost
server.listen(port, "127.0.0.1");
console.log('now listenning to port: ' + 3000);
// note: open default browser and type 127.0.0.1:3000 to display message
console.log('press any key to exit!');
// NOTE:
<file_sep>'use strict';
var http = require('http');
// filestream module
var fs = require('fs');
// creates readable stream
var streamReader = fs.createReadStream()
<file_sep># CreatingServer
<file_sep>'use strict';
const http = require('http');
const port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
var obj = {
name: 'ivandro',
age: 20,
job: 'ninja'
};
var jsonString = JSON.stringify(obj);
res.end(jsonString);
}).listen(port);
<file_sep># StreamsAndBuffers
<file_sep># StreamAndBuffer
<file_sep># ReaderAndWritingFiles
<file_sep>'use strict';
var fs = require('fs');
// delete file
fs.unlink('deleteme.txt');
// create dir
fs.mkdirSync('logs');
// remove dir
// fs.rmdir('logs');
// get file in a directory
function getFiles() {
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
})
// sync
//const testFolder = './tests/';
//const fs = require('fs');
//fs.readdirSync(testFolder).forEach(file => {
// console.log(file);
//})
}
console.log('Hello world');
<file_sep># ServingHtml
<file_sep>'use strict';
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var os = require('os');
var bodyParser = require('body-parser');
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// middleware (used to get static files like: css...)
/*app.use('/assets', function (res, res, next) {
console.log(req.url);
// https://www.youtube.com/watch?v=-lRgL9kj_h0&index=28&list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp
next();
});
*/-
// http://localhost:3000/assets/styles.css
app.use('/assets', express.static('stuff'));
app.get('/', function (req, res) {
// res.send('this is the home page!');
// res.sendfile(__dirname + "/index.html");
res.render('index');
});
app.post('/contact', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
// console.log(req.body + os.EOL);
// console.log(req.body);
/*
console.log('who: ' + req.body.who);
console.log('email: ' + req.body.email);
console.log('department: ' + req.body.department);
*/
res.render('contact-success', { data: req.body });
});
app.get('/contact', function (req, res) {
// res.sendfile(__dirname + "/contact.html");
console.log(req.query);
res.render('contact', { qs: req.query });
});
// respond to a particular request
app.get('/profile/:id', function (req, res) {
// res.send('you requested to see a profile with the id of: ' + req.params.id);
// browser: localhost:3000/profile/ivandrofly
var data = {
age: 29,
job: 'ninja',
hobbies: ['eating', 'fighting', 'fishing']
};
res.render('profile', { person: req.params.id, data: data });
})
app.listen(3000);
// NOTE: USE nodemon for easier dev...
// keyword: nodemon, template-engines, partial-views, partial-templates
// note: http://localhost:3000/contact?dept=okay&person=ivandroismael<file_sep># readinput
<file_sep># RoutingWithExpress
<file_sep># foreach-javascript
|
baacf454a44a8f23cf90c2bdafbdc2cb70e94182
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 18
|
JavaScript
|
ivandrofly/learning-nodejs
|
5b33a7a94c7df96a7de8f47902a51cdfecfdf099
|
dc536006e16e8a3c6ed4390b7c417387547fd928
|
refs/heads/master
|
<file_sep>import React from "react"
const countries=["Poland","Turkey","Spain","Italy","Czech Republic","Mexico","Colombia","Brazil","Argentine","Chile."]
const Footer = () => {
return (
<footer>
<p class="foot">
We are leaders in 10 countries:
{countries.map((el,i)=>i!==countries.length-1 ? el+", ": " and "+el)}
<br /><br />
<span className="paye">This site uses</span> cookies to deliver services in accordance with this Privacy Policy. You can specify the conditions for storing or accessing cookies on your browser.<br /><br />
www.docplanner.com © 2019
</p>
</footer>
)
}
export default Footer<file_sep>import React from 'react'
const menu = [{ title: "About us" }, { title: "Career" },
{
title: "Departments", sub: ["Marketing & PR", "Customer Success & Sales",
'IT, Product, Design & UX', 'Finance & Administration', 'HR & more']
}]
const paragraphe = [
"We want patients to find the perfect doctor and book an appointment in the most easy way.The patient journey should be enjoyable, and that's why we are always next to them: to help them find the best possible care. Anytime, anywhere."
,"We also help doctors to better manage their practice and build their online reputation. With our integrated end-to-end solution, doctors are able not only to improve their online presence, but also to devote their time to what really matters: their patients."
]
const Header = () => {
return (
<header>
<section className="top">
<div className="top1">
<div>
<img style={{ width: '310px', height: '33px' }} alt=""
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAABGCAMAAAAn+xosAAAAflBMVEX///8Aw6Wrq6sAwKAAv56mpqalpaW3t7fr+vcaxahx1MCc4NHu7u6J2snB6+Fq077n5+dW0LnKysrY2NjP8Om66uDl+PTe3t74/v2/v7/Q0NCm4tWxsbHz8/P5+fnj4+PW8u2V39Ba0Lqz6N1FzLN+2cczya7Dw8Nu1cHT8es1qIyqAAARVElEQVR4nO2deX/6LAzArT20nvM+57yq7v2/wactCRAIWP25uceP+WtaSil8DSEJrFbzSDsMlIRbX9G3vKW6ZASs3rOb85ZXkX6gg3V4dnPe8ipyJGC1n92<KEY> />
</div>
<div>
<ul className="menu">
{menu.map(el =>
<li className="dropdown">{el.title}
{(el.sub) ?
<div className="dropdown-content">
{el.sub.map(e =>
<a href="#">{e}</a>)
}
</div>
: ""}
</li>
)}
</ul>
</div>
</div>
</section>
<div className="mid">
<img src="https://www.docplanner.com/img/sygnet.png" />
<br /><br />
Making the healthcare experience more human
</div>
<ul className="paragraphe">
</ul>
<ul className="paragraphe">
{paragraphe.map(el =>
<li>{el}</li>)}
</ul>
</header>
)}
export default Header
|
391ecb05da35e211e1c97e04fd5e8011be09534b
|
[
"JavaScript"
] | 2
|
JavaScript
|
Ch-Omar/docplanner-clone
|
f5af42d6406ab71b7cffc13520aecb496b4ec8ef
|
0efdb98c47d2f5cf830a4aa2b50922539a9e9014
|
refs/heads/master
|
<file_sep>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
train_dir = 'cats_and_dogs/train'
validation_dir = 'cats_and_dogs/validation'
test_dir = 'cats_and_dogs/test'
# Get number of files in each directory. The train and validation directories
# each have the subdirecories "dogs" and "cats".
total_train = sum([len(files) for r, d, files in os.walk(train_dir)])
total_val = sum([len(files) for r, d, files in os.walk(validation_dir)])
total_test = len(os.listdir(test_dir))
# Variables for pre-processing and training.
batch_size = 128
epochs = 15
IMG_HEIGHT = 150
IMG_WIDTH = 150
train_image_generator = ImageDataGenerator(rescale= 1./255)
validation_image_generator = ImageDataGenerator(rescale= 1./255)
test_image_generator = ImageDataGenerator(rescale= 1./255)
train_data_gen = train_image_generator.flow_from_directory(directory=train_dir, target_size = (IMG_HEIGHT,IMG_WIDTH),
batch_size = batch_size, class_mode = 'binary')
val_data_gen = validation_image_generator.flow_from_directory(directory= validation_dir,
target_size = (IMG_HEIGHT,IMG_WIDTH),
batch_size = batch_size, class_mode = 'binary')
test_data_gen = test_image_generator.flow_from_directory(directory= 'cats_and_dogs',
target_size = (IMG_HEIGHT, IMG_WIDTH), batch_size = 1,
classes = ['test'], class_mode = None, shuffle=False, )
train_image_generator = ImageDataGenerator(rescale= 1./255,
rotation_range=90,
width_shift_range=1.0,
height_shift_range=1.0,
shear_range=0.2,
zoom_range=0.2,
vertical_flip= True)
train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
directory=train_dir,
target_size=(IMG_HEIGHT, IMG_WIDTH),
class_mode='binary')
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation = 'sigmoid'))
model.compile(optimizer= 'adam',
loss = 'binary_crossentropy',
metrics = ['accuracy'])
model.summary()
history = model.fit(train_data_gen, steps_per_epoch=None, epochs=epochs, validation_data=val_data_gen,
validation_steps=None)
model.save('trained_model')
model.predict(test_data_gen)
probabilities = model.predict(test_data_gen)
prediction = model.predict_classes(test_data_gen)
print(probabilities)
print(prediction)<file_sep>
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
books_filename = 'book-crossings/BX-Books.csv'
ratings_filename = 'book-crossings/BX-Book-Ratings.csv'
# import csv data into dataframes
df_books = pd.read_csv(
books_filename,
encoding = "ISO-8859-1",
sep=";",
header=0,
names=['isbn', 'title', 'author'],
usecols=['isbn', 'title', 'author'],
dtype={'isbn': 'str', 'title': 'str', 'author': 'str'})
#print(df_books)
df_ratings = pd.read_csv(
ratings_filename,
encoding = "ISO-8859-1",
sep=";",
header=0,
names=['user', 'isbn', 'rating'],
usecols=['user', 'isbn', 'rating'],
dtype={'user': 'int32', 'isbn': 'str', 'rating': 'float32'})
# add your code here - consider creating a new cell for each section of code
df = df_ratings
user_200 = df['user'].value_counts()
books_100 = df['isbn'].value_counts()
df = df[df['user'].isin(user_200[user_200 > 200].index)]
df = df[df['isbn'].isin(books_100[books_100 > 100].index)]
df = pd.merge(right=df, left=df_books, on='isbn')
df = df.drop_duplicates(['title', 'user'])
piv = df.pivot(index='title', columns='user', values='rating').fillna(0)
model_NN = NearestNeighbors(metric='cosine', algorithm='auto', n_neighbors= 6)
model_NN.fit(piv)
distance, indices = model_NN.kneighbors(piv, n_neighbors=6)
def get_recommends(book = ""):
list_recommandations = [book,[]]
isbn_book = piv.index.get_loc(str(book))
for i in range(5,0,-1):
list_kNN = [piv.index[indices[isbn_book][i]], distance[isbn_book][i]]
list_recommandations[1].append(list_kNN)
recommended_books = list_recommandations
return recommended_books
#books = get_recommends("Where the Heart Is (Oprah's Book Club (Paperback))")
#books = get_recommends('The Queen of the Damned (Vampire Chronicles (Paperback))')
#print(books)
import random
def random_book_recommend():
random_index = random.randint(0, piv.index.shape[0])
book = piv.index[random_index]
return get_recommends(book = book)
#books = get_recommends("Where the Heart Is (Oprah's Book Club (Paperback))")
#books = get_recommends('The Queen of the Damned (Vampire Chronicles (Paperback))')
#examples
#print(books)
#print title of example and nearest neigbors with distance
print(random_book_recommend())
#print random book with nearest neigbors with distance
<file_sep>import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
test_image_generator = ImageDataGenerator(rescale= 1./255)
test_data_gen = test_image_generator.flow_from_directory(directory= 'cats_and_dogs', target_size=(150, 150),
batch_size=1, classes = ['test'], class_mode=None,
shuffle=False )
trained_model = tf.keras.models.load_model('trained_model')
trained_model.summary()
probabilities = trained_model.predict(test_data_gen)
# only works until 31.12.2020
prediction = trained_model.predict_classes(test_data_gen)
#in 2021 use the following
prediction = (trained_model.predict(test_data_gen) > 0.5).astype('int32')
#showing the probabilities for the classification as a dog and the prediction (1 means dog and 0 cat)
print(probabilities)
print(prediction)
|
67aebccc68d267e69a98a3d3471b9d581e2badb9
|
[
"Python"
] | 3
|
Python
|
LennardFranz/machine_learning
|
5c2b7c4a415668c2c890f450e936ca07c3b4bef7
|
a81320dce7bab22f64c97c225185e4aa5703f4da
|
refs/heads/main
|
<file_sep>
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('./config/config');
app.use(bodyParser.urlencoded({extend: false}));
app.use(bodyParser.json());
app.get('/usuario', function(req, resp) {
resp.json('get Usuario');
});
app.post('/usuario', function(req, resp) {
let body = req.body;
if(body.nombre === undefined) {
resp.status(400).json({
ok: false,
mensaje: 'El nombre es necesario'
});
} else {
resp.json({
persona: body
});
}
});
app.put('/usuario/:id', function(req, resp) {
let id = req.params.id
resp.json({
id
});
});
app.delete('/usuario', function(req, resp) {
resp.json('delete Usuario');
});
app.listen(process.env.PORT, () => {
console.log('Escuchando desde el puerto 3000');
});
|
63d338f7a0828b19148e73dc72c43576bb70e0d0
|
[
"JavaScript"
] | 1
|
JavaScript
|
JorgeMochonBernal/node-rest-server
|
780078e661634be8049458e134139ac54f21c043
|
c4347a2b492595a489bd9b1404ffed403c66fa14
|
refs/heads/master
|
<file_sep>package ru.mail.aslanisl.devcandidates;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private ArrayList<String> mList;
private Call<ArrayList<String>> mCall;
private RecyclerView mRecyclerView;
private Adapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null ) {
getSupportActionBar().hide();
}
mList = new ArrayList<>();
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), tabletSize ? 3 : 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new Adapter(this);
mRecyclerView.setAdapter(mAdapter);
mCall = App.getApi().getList();
if (savedInstanceState != null){
mList = savedInstanceState.getStringArrayList("list");
mAdapter.addAll(mList);
} else mCall.enqueue(new Callback<ArrayList<String>>() {
@Override
public void onResponse(Call<ArrayList<String>> call, Response<ArrayList<String>> response) {
if (response.isSuccessful()){
mList = response.body();
mAdapter.addAll(mList);
}
}
@Override
public void onFailure(Call<ArrayList<String>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "An error occurred during networking", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mCall != null) {
mCall.cancel();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putStringArrayList("list", mList);
super.onSaveInstanceState(outState);
}
}
|
60b01c98b4b91d7d011d3c3f46bc4560902f5580
|
[
"Java"
] | 1
|
Java
|
Aslanisl/Devcandidates
|
58e2dda1689df3457759ef6718c041744e4dc36d
|
280b4d54b76fa5b1fea6af3b85040d2cc94e74aa
|
refs/heads/master
|
<repo_name>jasonsutter87/angular-decoupled-blog-frontend<file_sep>/src/app/posts/posts.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Post } from '../post';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/retry';
import 'rxjs/add/observable/of';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
readonly ROOT_URL = 'https://angular-decoupled-blog-backend.herokuapp.com'
posts: Observable<any>;
newPost: Observable<any>;
constructor(private http: HttpClient){}
// create get
getPosts() {
this.posts = this.http.get(this.ROOT_URL);
}
ngOnInit() {
}
// create post
createPost() {
let data: Post = {
id: 21,
title: 'My New Post9189281',
author: '<NAME>',
content: 'Hello 111World!!'
}
this.newPost = this.http.post<Post>(this.ROOT_URL+ '/posts', data);
}
}
|
91e209fc5faeb526e1c6374aa211a5b030839232
|
[
"TypeScript"
] | 1
|
TypeScript
|
jasonsutter87/angular-decoupled-blog-frontend
|
304c293e53fe2d12f7334abf0fd2e3799f812444
|
92634ab99bc0de98bdc3f76b46d555808c86bf17
|
refs/heads/master
|
<repo_name>agarcia-carecloud/m1-pulse-check<file_sep>/starter-code/src/assessment1.js
// Write a function that returns the product of 2 numbers
function product(x, y) {
if(x === null || x === undefined || y === null || y == undefined) return false;
return (x * y); //multiplies both parameters to return product.
}
// Write a function that returns whether a given number is even
function isEven(num) {
if(num%2 === 0){ //if remainder of num is 0 after modulo operator, return true.
return true;
}
else return false;
}
// Return the largest of 2 numbers
function maxOfTwoNumbers(a, b) {
if ( a > b){ //return either parameter if it is larger than the other.
return a;
}
else return b;
}
// Return the largest of 3 numbers
function maxOfThreeNumbers(a, b, c) {
if(typeof a !== "number" || typeof b !== "number" || typeof c !== "number"){
return false;
}
else if(a > b && a > c){ //conditional to check which number is larger than the others.
return a;
}
else if(b > a && b > c){
return b;
}
else return c;
}
// Calculate the sum of an array of numbers
function sumArray(numbers) {
let sum = 0;
if (!numbers.length){ //checks for empty array before beginning loop.
return 0;
}
else if (typeof numbers !== "object"){
return false;
}
for (i = 0; i < numbers.length; i++) {
if(typeof numbers[i] !== "number"){
return false;
}
else sum += numbers[i]; //for each element in the array, add the value to the current value of sum.
}
return sum;
}
// Return the largest number of a non-empty array
function maxOfArray(numbers) {
let largestNumber = 0;
if (!numbers.length) {
return false; //checks for empty array before beginning loop.
}
else if (typeof numbers !== "object"){
return false;
}
for(let i = 0; i < numbers.length; i++){
if(numbers[i] > largestNumber) { //iterate through the array and update largestNumber to the value of the current largest number.
largestNumber = numbers[i];
}
}
return largestNumber;
}
// Return the longest string in an array
function longestString(strings) {
let largestString = "";
for(let i = 0; i < strings.length; i++){
if (strings[i].length > largestString.length){
largestString = strings[i]; //checks if the length of the current string in the array is longer than longestString and updates the value of the variable if true.
}
}
return largestString;
}
// Return whether a word is in an array
function doesWordExist(wordsArr, word) {
for(let i = 0; i < wordsArr.length; i++){
if(wordsArr.includes(word) === true){
return true;
}
else return false;
}
}
// Finding the first non-duplicate (non-repeating) word in an array
function findUnique(wordsArr) {
let uniqueWord = "";
if(!wordsArr.length) return false;
for(let i = 0; i < wordsArr.length; i++){
if (i === wordsArr.indexOf(wordsArr[i]) && i === wordsArr.lastIndexOf(wordsArr[i])){
uniqueWord = wordsArr[i];
break;
}
}
return uniqueWord;
}
// Get the fullName from the object { firstName: 'Tony', lastName: 'Stark'}
function getFullName(personObj) {
return `${personObj.firstName } ${personObj.lastName}`;
}
// Return the largest number in a two dimensional array
function maxTwoDimArray(matrix) {
let largestNum = 0;
for(let i = 0; i < matrix.length; i++){
if(matrix[0][i] > largestNum && matrix[1][i] > largestNum && matrix[2][i] > largestNum){
largestNum = matrix[i][i];
}
}
return largestNum;
}
|
b6e2c13588e76c6e5bd4394550c63ae045ea88f5
|
[
"JavaScript"
] | 1
|
JavaScript
|
agarcia-carecloud/m1-pulse-check
|
99ed99ac5358841e6eec8a9f8e6e248ea9940e41
|
d7b551a58876ac3ad9482e53b236e1420edb4402
|
refs/heads/master
|
<file_sep>
#include<cstdio>
#include<ctime>
#include<cstdlib>
#include<cassert>
#include<algorithm>
#define sz 100000
#define MERGE 1
#define INS 2
int a[sz+5], b[sz+5], c[sz+5];
void merge(int A[],int p, int q, int r)
{
int n1= q-p +1 ;
int n2= r-q ;
int L[n1+1] , R[n2+1] ;
for(int i=0 ; i<n1; i++){
L[i]= A[p+i];
}
for(int j=0 ; j<n2 ; j++){
R[j]= A[q+1 + j ];
}
L[n1]=2147483647;
R[n2]=2147483647;
int s=0,t=0;
for ( int k = p ; k <= r ; k++){
if (L[s]<=R[t]){
A[k]=L[s];
s++;
}else{
A[k]= R[t];
t++;
}
}
}
void merge_sort(int A[],int p, int r)
{
int mid ;
if(p<r){
mid= (p+r)/2 ;
merge_sort(A,p,mid);
merge_sort(A,mid+1,r);
merge(A,p,mid,r);
}
}
void insertion_sort() {
int i,j,temp,n;
for(j=1; j<n; j++)
{
temp=a[j];
i=j-1;
while(i>=0 && a[i]>temp)
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=temp;
}
for(i=0; i<n; i++)
{
printf(" %d ",a[i]);
}
}
int sort_ok(int a[]) {
for (int i=0;i<sz;++i)
if (a[i] != c[i]) return 0;
return 1;
}
int main() {
/* do not change here */
int A[100];
printf("Enter 5 input\n");
for(int i=0;i<sz;i++)
{
scanf("%d",&A[i]);
}
srand(time(NULL));
for (int i=0;i<sz;++i) {
a[i] = rand() % 1000;
b[i] = a[i];
c[i] = a[i];
}
std::sort(c, c+sz);
clock_t s = clock();
merge_sort(A,0,sz-1);
clock_t e = clock();
assert(sort_ok(a));
printf("Time for merge sort: %d\n", e-s);
s = clock();
insertion_sort();
e = clock();
assert(sort_ok(b));
printf("Time for insertion sort: %d\n", e-s);
return 0;
}
<file_sep>#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
#define SIZE 102
void generate_random_array(int *A, int n)
{
srand(time(NULL));
for(int i = 1; i <= n; ++i)
A[i] = rand() % 100;
}
void print_array(int *A, int n)
{
for(int i = 1; i <= n; ++i)
printf("%d ", A[i]);
printf("\n");
}
void copy_array(int *source, int *target, int n)
{
for(int i = 1; i <= n; ++i)
target[i] = source[i];
}
int parent(int index)
{
return index/2;
}
// Returns the index of the left child of the node 'index'
int left_child(int index)
{
return 2*index;
}
// Returns the index of the right child of the node 'index'
int right_child(int index)
{
return (index*2+1);
}
// Max Heapify at node 'index'
void max_heapify(int *A, int heapSize, int index)
{
int i,L,R,largest,p;
L=left_child(index);
R=right_child(index);
if((L<=heapSize)&& A[L]>A[index])
{
largest=L;
}
else
largest=index;
if((R<=heapSize)&&(A[R]>A[largest]))
largest=R;
if(largest!=index)
{
p= A[index];
A[index] = A[largest];
A[largest] = p;
max_heapify(A,heapSize,largest);
}
}
// Builds the array A into a max heap
void build_max_heap(int *A, int heapSize)
{
for( int i = heapSize/2; i >= 1; i--)
{
max_heapify(A,heapSize,i);
}
}
// Sorts the array A using the Heapsort algorithm
void heapsort(int *A, int n)
{
int temp;
build_max_heap(A,n);
for (int i = n; i >= 2; i--)
{
temp= A[1];
A[1]= A[i];
A[i]= temp;
max_heapify(A,i-1,1);
}
}
void check_correctness(int *A, int *B, int n)
{
int i;
sort(B + 1, B + 1 + n);
for(i = 1; i <= n; ++i)
if(A[i] != B[i])
break;
printf("\n%s Sorting\n", i <= n ? "Incorrect" : "Correct");
}
int main()
{
int n, A[SIZE], B[SIZE];
printf("Enter Size: ");
scanf("%d", &n);
generate_random_array(A, n);
printf("Initial array: ");
print_array(A, n);
copy_array(A, B, n);
heapsort(A, n);
printf("\nSorted array: ");
print_array(A, n);
check_correctness(A, B, n);
return 0;
}
<file_sep>#include<cstdio>
using namespace std;
int factorial(int n)
{
if(n==0)
return 1;
else
return factorial(n-1)*n;
}
int main()
{
int n;
printf("enter the number to find factorial:\n");
scanf("%d",&n);
int f=factorial(n);
printf("the factorial is: %d", f);
}
<file_sep>#include<cstdio>
using namespace std;
int factorial(int n)
{
if(n==0)
return 1;
else
return factorial(n-1)*n;
}
int main()
{
int n;
printf("enter the number to find factorial:\n");
scanf("%d",&n);
int f=factorial(n);
printf("the factorial of %d is: %d", n,f);
return 0;
}
<file_sep>#include<stdio.h>
#include<conio.h>
#include<limits.h>
void printcoins(int n,int s[])
{
while(s[n]!=0)
{
printf("%d cents\n",s[n]);
n=n-s[n];
}
}
int dynamic_iterative(int n,int v[],int size)
{
int i;
int c[100],s[100];
c[0]=0,s[0]=0;
for(i=1;i<=n;i++)
{
c[i]=INT_MAX;
s[i]=-1;
for(int j=0;j<size;j++)
{
if(i>=v[j])
{
if(c[i-v[j]]+1<c[i])
{
c[i]=c[i-v[j]]+1;
s[i]=v[j];
}
}
}
}
printcoins(n,s);
return c[n];
}
int main()
{
int v[100];
int p,n,m,q;
printf("how many coins you have?\n");
scanf("%d",&m);
printf("enter the coins you have:\n");
for(q=0;q<m;q++)
{
scanf("%d",&v[q]);
}
printf("enter how much change you required:\n");
scanf("%d",&n);
int val=dynamic_iterative(n,v,m);
printf(" total %d coins were required!\n",val);
getch();
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
/////////0-1 knapsack////////
int w[10], p[10], v[10][10], n, i, j, capacity, x[10] = {0};
int max(int i, int j) {
return ((i > j) ? i : j);
}
int KnapSack(int i, int j) {
int value;
if (v[i][j] < 0) {
if (j < w[i])
value = KnapSack(i - 1, j);
else
value = max(KnapSack(i - 1, j), p[i] + KnapSack(i - 1, j - w[i]));
v[i][j] = value;
}
return (v[i][j]);
}
int main() {
int profit, count = 0;
printf("\nEnter the number of elements : ");
scanf("%d", &n);
printf("\nEnter the profit and weights of the elements\n");
for (i = 1; i <= n; i++) {
printf("Item no : %d\n", i);
scanf("%d %d", &p[i], &w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d", &capacity);
for (i = 0; i <= n; i++)
for (j = 0; j <= capacity; j++)
if ((i == 0) || (j == 0))
v[i][j] = 0;
else
v[i][j] = -1;
profit = KnapSack(n, capacity);
i = n;
j = capacity;
while (j != 0 && i != 0) {
if (v[i][j] != v[i - 1][j]) {
x[i] = 1;
j = j - w[i];
i--;
} else
i--;
}
printf("Items in the KnapSack are : \n\n");
printf("Sl.no \t weight \t profit\n");
printf("\n----------------------------------------\n");
for (i = 1; i <= n; i++)
if (x[i])
printf("%d \t %d \t\t %d\n", ++count, w[i], p[i]);
printf("Total profit = %d\n", profit);
getch();
return 0;
}
<file_sep>#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
#define SIZE 102
void generate_random_array(int *A, int n)
{
srand(time(NULL));
for(int i = 1; i <= n; ++i)
A[i] = rand() % 100;
}
void print_array(int *A, int n)
{
for(int i = 1; i <= n; ++i)
printf("%d ", A[i]);
printf("\n");
}
void copy_array(int *source, int *target, int n)
{
for(int i = 1; i <= n; ++i)
target[i] = source[i];
}
void quick_sort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quick_sort(list, low, j - 1);
quick_sort(list, j + 1, high);
}
}
void check_correctness(int *A, int *B, int n)
{
int i;
sort(B + 1, B + 1 + n);
for(i = 1; i <= n; ++i)
if(A[i] != B[i])
break;
printf("\n%s Sorting\n", i <= n ? "Incorrect" : "Correct");
}
int main()
{
int n, A[SIZE], B[SIZE];
printf("Enter how many numbers:\n");
scanf("%d", &n);
generate_random_array(A, n);
printf("Initial array: ");
print_array(A, n);
copy_array(A, B, n);
quick_sort(A, 1, n);
printf("\nSorted array: ");
print_array(A, n);
check_correctness(A, B, n);
return 0;
}
<file_sep>#include<cstdio>
using namespace std;
int sum(int n)
{
if(n==0)
return 0;
else
return sum(n-1)+n;
}
int main()
{
int n;
printf("Enter the number to sum up to: \n", n);
scanf("%d",&n);
int summation= sum(n);
printf("the sum is: %d", summation);
return 0;
}
<file_sep>#include <cstdio>
int lcm(int a, int b)
{
static int c = 1;
if (c % a == 0 && c % b == 0)
{
return c;
}
c++;
lcm(a, b);
return c;
}
int main()
{
int a, b, result;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
return 0;
}
<file_sep>#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
#define SIZE 102
void generate_random_array(int *A, int n)
{
srand(time(NULL));
for(int i = 1; i <= n; ++i)
A[i] = rand() % 100;
}
void print_array(int *A, int n)
{
for(int i = 1; i <= n; ++i)
printf("%d ", A[i]);
printf("\n");
}
void copy_array(int *source, int *target, int n)
{
for(int i = 1; i <= n; ++i)
target[i] = source[i];
}
void merge(int *A, int left, int mid, int right)
{
int L[100], R[100];
int n1=mid-left+1;
int n2=right-mid;
L[n1+1]=100000;
R[n2+1]=100000;
for(int i=1;i<=n1;++i)
{
L[i]=A[left+i-1];
}
for(int j=1;j<=n2;++j)
{
R[j]=A[mid+j];
}
int i=1,j=1;
for (int k=left;k<=right;k++){
if (L[i]<=R[j]){
A[k]=L[i];
i=i+1;
}
else{
A[k]=R[j];
j=j+1;
}
}
}
void merge_sort(int *A, int left, int right)
{
float mid;
if (left<right){
mid=(left+right)/2;
merge_sort(A,left,mid);
merge_sort(A,mid+1,right);
merge(A,left,mid,right);
}
}
void check_correctness(int *A, int *B, int n)
{
int i;
sort(B + 1, B + 1 + n);
for(i = 1; i <= n; ++i)
if(A[i] != B[i])
break;
printf("\n%s Sorting\n", i <= n ? "Incorrect" : "Correct");
}
int main()
{
int n, A[SIZE], B[SIZE];
printf("Enter how many numbers:\n");
scanf("%d", &n);
generate_random_array(A, n);
printf("Initial array: ");
print_array(A, n);
copy_array(A, B, n);
merge_sort(A, 1, n);
printf("\nSorted array: ");
print_array(A, n);
check_correctness(A, B, n);
return 0;
}
<file_sep>#include<stdio.h>
#include<stdlib.h>
#define PQSIZE 100
#define compare(a,b) a>b
#define parent(i) (i-1)/2
typedef int item;
typedef struct{
item key[PQSIZE];
int n;
}heap;
void swap(item* a,item* b)
{
item temp=*a;
*a=*b;
*b=temp;
}
void heapify(item A[],int i,int heapsize)
{
int selected=i,l=2*i+1,r=2*i+2;
if(l<heapsize && compare(A[l],A[selected]))
selected=l;
if(r<heapsize && compare(A[r],A[selected]))
selected=r;
if(selected!=i)
{
swap(&A[selected],&A[i]);
heapify(A,selected,heapsize);
}
}
void buildheap(item A[],int heapsize)
{
for(int i=heapsize/2;i>=0;i--)
heapify(A,i,heapsize);
}
void heapsort(heap* h)
{
buildheap(h->key,h->n);
for(int i=h->n-1;i>0;i--)
{
swap(&h->key[i],&h->key[0]);
heapify(h->key,0,i-1);
}
}
item remove(heap* h)
{
if(h->n == 0)
{
printf("remove failed! heap empty");
exit(0);
}
item temp=h->key[0];
h->key[0]=h->key[--h->n];
heapify(h->key,0,h->n);
return temp;
}
void update(heap* h,int i,int nVal)
{
if(h->key[i] > nVal)
{
h->key[i]=nVal;
heapify(h->key,i,h->n);
}
else
{
h->key[i]=nVal;
h->key[i]=nVal;
while(i>0 && compare(h->key[i],h->key[parent(i)]))
{
swap(&h->key[i],&h->key[parent(i)]);
i=parent(i);
}
}
}
void insert(heap* h,int nVal)
{
if(h->n == PQSIZE)
{
printf("insert failed! heap full");
exit(0);
}
else
{
int i=h->n++;
int p=(i-1)/2;
h->key[i]=nVal;
while(i>0 && compare(h->key[i],h->key[p]))
{
swap(&h->key[i],&h->key[p]);
i=p;
p=(i-1)/2;
}
}
}
int main(){
heap h;
/*h.n=10;
h.key[0]=12;h.key[1]=2;h.key[2]=92;h.key[3]=4;h.key[4]=17;
h.key[5]=34;h.key[6]=48;h.key[7]=19;h.key[8]=9;h.key[9]=3;
heapsort(&h);*/
h.n=0;
insert(&h,12);
insert(&h,2);
insert(&h,92);
insert(&h,4);
insert(&h,17);
insert(&h,34);
insert(&h,48);
insert(&h,19);
insert(&h,9);
insert(&h,3);
for(int i=0;i<h.n;i++){
printf("%d ",h.key[i]);
}
printf("\n");
remove(&h);
for(int i=0;i<h.n;i++){
printf("%d ",h.key[i]);
}
return 0;
} // end of main
<file_sep>#include <cstdio>
using namespace std;
int large(int[], int, int);
int main()
{
int size;
int largest;
int minest;
int list[20];
int i;
printf("Enter size of the list:");
scanf("%d", &size);
printf("Enter the list:\n");
for (i = 0; i < size ; i++)
{
scanf("%d", &list[i]);
}
if (size == 0)
{
printf("Empty list\n");
}
else
{
largest = list[0];
largest = large(list, size - 1, largest);
printf("\nThe largest number in the list is: %d\n", largest);
minest = list[0];
minest= min(list, size - 1, minest);
printf("\nThe largest number in the list is: %d\n", minest);
}
}
int large(int list[], int size, int largest)
{
if (size == 1)
return largest;
if (size > -1)
{
if (list[size] > largest)
{
largest = list[size];
}
return(largest = large(list, size - 1, largest));
}
else
{
return largest;
}
}
int large(int list[], int size, int minest)
{
if (size == 1)
return largest;
if (size > -1)
{
if (list[size] > largest)
{
largest = list[size];
}
return(largest = large(list, size - 1, largest));
}
else
return largest;
}
}
<file_sep>Ques:Find the summation of all element in an array
#include<stdio.h>
#include<conio.h>
int size;
int getsumElement(int arr[]){
int sum=0;
int i;
for (i =0; i<size; i++)
sum +=arr[i];
return sum;
getch();
}
int main(){
int arr[100],sum,i;
printf("Enter the size of the array: ");
scanf("%d",&size);
printf("Enter %d elements of an array: ",size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
sum=getsumElement(arr);
printf("sum of the element of an array is: %d",sum);
getch();
return 0;
}
<file_sep>#include<cstdio>
#include<stdio.h>
#include<iostream>
using namespace std;
#define SIZE 102
int heapSize=0;
// Returns the index of the parent of the node 'index'
int parent(int index)
{
return index/2;
}
// Returns the index of the left child of the node 'index'
int left_child(int index)
{
return 2*index;
}
// Returns the index of the right child of the node 'index'
int right_child(int index)
{
return (index*2+1);
}
// Max Heapify at node 'index'
void max_heapify(int *A, int heapSize, int index)
{
int L,R,largest,p;
L=left_child(index);
R=right_child(index);
if((L<=heapSize)&& A[L]>A[index])
{
largest=L;
}
else
largest=index;
if((R<=heapSize)&&(A[R]>A[largest]))
largest=R;
if(largest!=index)
{
p= A[index];
A[index] = A[largest];
A[largest] = p;
max_heapify(A,heapSize,largest);
}
}
void print_array(int *A, int n)
{
for(int i = 1; i <= n; ++i)
printf("%d ", A[i]);
printf("\n");
}
// Returns the maximum element of the priority queue A
int heap_maximum(int *A)
{
if(heapSize == 0)
{
printf("The heap is empty.");
return -1;
}
return A[1];
}
// Returns the maximum element of the max priority queue A; also deletes it from A
int heap_extract_max(int *A)
{
if(heapSize<1)
{
printf("underflow");
return -1;
}
int maximum=A[1];
A[1]=A[heapSize];
heapSize=heapSize-1;
max_heapify(A,heapSize,1);
return maximum;
}
void heap_increase_key(int *A, int i, int key)
{
int p;
if(key < A[i])
{
A[i]=key;
max_heapify(A,heapSize,i);
}
else
A[i]=key;
while(i >1 && A[parent(i)]<A[i])
{
p=A[i];
A[i]=A[parent(i)];
A[parent(i)]=p;
i=parent(i);
}
print_array(A,heapSize);
}
// Inserts the element key into the max priority queue A
void heap_insert(int *A, int key)
{
heapSize=heapSize+1;
A[heapSize]=-100000;
heap_increase_key(A,heapSize,key);
}
int main()
{
int opCode;
int A[SIZE]; // The max priority queue
printf("Operation codes:\n\n1. Max element\n2. Remove max element\n3. Insert element\n4. Exit\n\n");
while(true)
{
printf("\n\nEnter operation code: ");
scanf("%d", &opCode);
if(opCode == 1)
{
printf("Max element is: %d",heap_maximum(A));
}
else if(opCode == 2)
{
// Your code
printf(" %d ",heap_extract_max(A));
print_array(A,heapSize);
}
else if(opCode == 3)
{
// Your code
int key;
printf("Enter a number to insert: ");
scanf("%d",&key);
heap_insert(A,key);
}
else if(opCode == 4)
break;
else
puts("Invalid code.\n");
}
return 0;
}
<file_sep>//------ektu problem----//
#include<stdio.h>
#include<conio.h>
int w[10], p[10], v[10][10], n, i, j, capacity, x[10] = {0};
float greedyknapsack(int p[],int w[],int capacity)
{
int i=0;
float price=0;
float load=0;
while(i<n && load<=capacity)
{
if(w[i]<=capacity-load)
{
printf("item %d fully taken\n",i);
load=load+w[i];
price=price+p[i];
}
else
{
printf("item %d %f kg taken\n",i,float((capacity-load)/w[i]));
price=price+float((capacity-load)/w[i]*p[i]);
}
i++;
}
return price;
getch();
}
int main()
{
int n,i;
int profit, count = 0;
printf("\nEnter the number of elements : ");
scanf("%d", &n);
printf("\nEnter the profit and weights of the elements\n");
for (i = 0; i <= n-1; i++) {
printf("Item no : %d\n", i);
scanf("%d %d", &p[i], &w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d", &capacity);
float val=greedyknapsack(p,w,capacity);
printf(" %f \n ",val);
getchar();
return 0;
getch();
}
<file_sep>Ques:Find frequency of an element in an array
#include<stdio.h>
#include<conio.h>
int x,count=0;
int frequency(int c[])
{
for(int i=0;c[i]!='\0';i++)
{
if(x==c[i])
count++;
}
return count;
getch();
}
int main()
{
int c[100],i,n;
printf("enter size:");
scanf("%d",&n);
printf("enter elements:");
for(i=0;i<n;i++)
{
scanf("%d",&c[i]);
}
printf("enter a number to count it's frequency:");
scanf("%d",&x);
count=frequency(c);
printf("frequency of %d is: %d",x,count);
getch();
return 0;
}
<file_sep>#include<cstdio>
#include<vector>
#include<queue>
#include<iostream>
#include <list>
#include <utility>
using namespace std;
#define SIZE 102
#define INF 2147483647
bool visited[SIZE];
int D[SIZE]; // Distance array
int P[SIZE]; // Parent array
int L[SIZE]; // Component label array
vector<int> A[SIZE]; // Adjacency lists
int k; //initial value for counting the component length
int level_counter; //initial value for numbering the component as label
int n;
// Initialize the arrays with default values before graph traversals
void initialize_arrays(int n)
{
for(int i = 0; i < n; ++i)
visited[i] = false, D[i] = INF, P[i] = -1;
}
// Add the undirected edge (u, v) to the graph
void add_edge(int u, int v)
{
// Your code
A[u].push_back(v);
A[v].push_back(u);
}
// Breadth-First Search from source vertex 's'
void BFS(int s)
{
// Your code
queue<int> Q;
Q.push(s);
D[s] = 0, P[s] = -1, visited[s] = true;
while(Q.empty() == false)
{
int u = Q.front();
Q.pop();
L[u]=level_counter; //label numbering
for(int i = 0; i < A[u].size(); ++i)
{
int v = A[u][i];
if(visited[v] == false)
{
k=k+1;
Q.push(v);
D[v] = D[u] + 1;
P[v] = u;
visited[v] = true;
}
}
}
}
// Depth-First Search from vertex 'u'
bool flag=false;
void DFS(int u)
{
// Your code
visited[u] = true;
for(int i = 0; i < A[u].size(); ++i)
{
int v = A[u][i];
if(visited[v] == false)
{
P[v]=u;
DFS(v);
}
else
{
if(P[u] != v)
flag=true;
}
}
}
// Returns true or false accordingly to whether the vertex 'v' is reachable from the vertex 'u'
// through some path
bool is_reachable(int n, int u, int v)
{
// Your code
initialize_arrays(n);
BFS(u);
if(P[v]== -1 && v != u)
return false;
if(P[v]== P[u])
return true;
if(P[v]== u)
return true;
is_reachable(n,u,P[v]);
}
// Returns the shortest path distance from vertex 'u' to vertex 'v'.
int shortest_path(int n, int u, int v)
{
// Your code
initialize_arrays(n);
BFS(u);
return D[v];
}
// Prints the shortest path from vertex 'u' to vertex 'v'.
void print_path(int v)
{
// Your code
if(P[v]== -1)
{
printf("%d ",v);
return;
}
print_path(P[v]);
printf("%d ",v);
}
// Returns true or false according to whether the graph contains a cycle or not.
bool has_cycle(int n)
{
// Your code
initialize_arrays(n);
for(int j=0; j < n; j++)
{
if(visited[j]==false)
{
DFS(j);
}
}
return flag;
}
// Returns the count of the connected components at the graph.
int count_components(int n)
{
// Your code
initialize_arrays(n);
int count=0;
for(int j=0; j < n; j++)
{
if(visited[j]==false)
{
BFS(j);
count++;
}
}
return count;
}
// Prints the connected component sizes of the graph (in any order).
void component_sizes(int n)
{
// Your code
k=1;
printf("component size are: ");
initialize_arrays(n);
for(int j=0; j < n; j++)
{
if(visited[j]==false)
{
BFS(j);
printf(" %d",k);
k=1;
}
}
printf("\n\n");
}
// For each of the vertices, prints the component number of which it is part of.
void label_components(int n)
{
// Your code
printf("not done yet!!!");
}
int main()
{
int n, opCode, u, v;
printf("Enter vertex count = ");
scanf("%d", &n);
printf("\n");
printf("\nOperation Codes:\n");
printf("1: Add Edge\n");
printf("2: Reachability\n");
printf("3: Shortest Path\n");
printf("4: Cycle Detection\n");
printf("5: Count Connected Components\n");
printf("6: Component Sizes\n");
printf("7: Label Components\n");
printf("Anything else: Exit\n");
printf("\n");
while(true)
{
printf("Enter a choice:\n");
scanf("%d", &opCode);
if(opCode == 1)
{
printf("Enter u and v\n");
scanf("%d %d", &u, &v);
add_edge(u, v);
}
else if(opCode == 2)
{
printf("Enter u and v\n");
scanf("%d %d", &u, &v);
if(is_reachable(n, u, v))
printf("%d and %d are connected.\n", u, v);
else
printf("%d and %d are not connected.\n", u, v);
}
else if(opCode == 3)
{
printf("Enter u and v\n");
scanf("%d %d", &u, &v);
int d = shortest_path(n, u, v);
if(d == INF)
printf("There's no path between %d and %d.\n", u, v);
else
{
printf("Shortest path distance: %d\n", d);
printf("Shortest path: ");
print_path(v);
printf("\n");
}
}
else if(opCode == 4)
printf("%s\n", has_cycle(n) ? "The graph contains cycle(s)" :
"The graph do not contain any cycle.");
else if(opCode == 5)
printf("Number of connected components = %d\n", count_components(n));
else if(opCode == 6)
component_sizes(n);
else if(opCode == 7)
label_components(n);
else
break;
}
return 0;
}
<file_sep>Ques: Find the max element in an array(print in main function)
#include<stdio.h>
#include<conio.h>
int size;
int max_element(int arr[]){
int i=0,max =-9999;
if(i < size){
if(max<arr[i])
max=arr[i];
i++;
max_element(arr);
}
return max;
getch();
}
int main(){
int arr[1000],max,i,size;
printf("Enter the size of the array: ");
scanf("%d",&size);
printf("Enter %d elements of an array: ", size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
max=max_element(arr);
printf("Largest element of an array is: %d",max);
getch();
return 0;
}
<file_sep>#include <cstdio>
using namespace std;
int goshagu(int a, int b)
{
if(a>=b && a%b==0)
return b;
else
if(a>=b && a%b!=0)
return goshagu(b,a%b);
else
if(b>a && b%a==0)
return a;
else
if(b>a && b%a!=0)
return goshagu(a,b%a);
}
int main()
{
int a,b;
printf("Enter a:\n");
scanf("%d",&a);
printf("Enter b:\n");
scanf("%d",&b);
int f=goshagu(a,b);
printf("Goshagu of %d and %d is %d.",a,b,f);
return 0;
}
|
1f45e8f03e6b9c949bc125fe37052e5342adec18
|
[
"C++"
] | 19
|
C++
|
Anika-alam/Algorithm
|
b8dc935b73381100efa9a763b4de988c96f729a1
|
65d3a5c2b9f15ebaa13591901cb0a5b6eb608118
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import { withRouter } from "react-router";
import fileImage from '../images/file.png'
import folderImage from '../images/folder.png'
class TableRow extends Component {
convertBytes(size) {
const prefixes = ['B', 'KB', 'MB', 'GB'];
let power = 0;
while(size > 1024)
{
size = Math.floor(size/1024);
power++;
}
return size + ' ' + prefixes[power];
}
onClickFolder(folderName)
{
let path = this.props.location.pathname;
if (path === '/')
path = '';
console.log("Push: " + path + '/' + folderName);
this.props.history.push(path + '/' + folderName);
}
render()
{
let file = this.props.file;
let classNameRow = file.isDirectory ? 'folder' : 'file';
let onClickRow = file.isDirectory ? () => this.onClickFolder(file.name) : null;
return (
<tr
key = {this.props.name}
className={classNameRow}
onClick = {onClickRow}
onContextMenu = {(e) => this.props.contextmenuHandler(e, file)}
>
<td className="type">
<img className="type-image" alt="" src = {file.isDirectory ? folderImage : fileImage}/>
</td>
<td className="name">
{file.name}
</td>
<td className="size">
{file.isDirectory ? <p></p>: <p>{this.convertBytes(file.size)}</p>}
</td>
<td className="mtime">
{new Date(file.mtime).toLocaleString()}
</td>
</tr>
)
}
}
export default withRouter(TableRow);<file_sep>import React, { Component } from 'react';
import FileTable from './FileTable/FileTable';
export class FileExplorer extends Component {
constructor(props) {
super(props);
this.state = {
sortKey: 'name',
sortDirection: 1
}
this.onHeaderClick = this.onHeaderClick.bind(this);
}
onHeaderClick(e) {
e.preventDefault();
if (e.target.className === this.state.sortKey)
{
let factor = this.state.sortDirection;
factor *= -1;
this.setState({sortDirection: factor});
}
else
{
this.setState({sortKey: e.target.className, sortDirection: 1});
}
}
render() {
return (
<div>
<FileTable
onHeaderClick = {this.onHeaderClick}
sortKey = {this.state.sortKey}
sortDirection = {this.state.sortDirection}
/>
</div>
)
}
}
export default FileExplorer;<file_sep>class FileInfo {
constructor(filename, size, ctime, mtime, isDirectory) {
this.name = filename;
this.size = size;
this.ctime = ctime;
this.mtime = mtime;
this.isDirectory = isDirectory;
}
}
module.exports = FileInfo;<file_sep>import React, { useState } from 'react';
import './Dialog.css';
function Dialog(props) {
const {setDialogState} = props;
if (!props.type)
{
return null;
}
const onSubmit = async (e, path, method, param = null) => {
e.preventDefault();
try {
const response = await fetch(path, {
method:method
});
if (response.ok)
{
console.log('Done');
props.fetchStorage();
}
else
{
console.log("Response.Code != 200");
}
} catch(err) {
console.log(err.message);
} finally {
setDialogState(null);
}
}
const ConfirmDialog = (props) => {
let { cancelText, okText, labelText } = props;
return (
<form
onSubmit={(e) => {onSubmit(e, path, method)}}
id="dialog"
>
<label>
<b>{labelText}</b>
</label>
<p>
<input id="ok" className="dialog-button" type="submit" value={okText} />
<button onClick={() => setDialogState(null)} id="cancel" className="dialog-button">{cancelText}</button>
</p>
</form>
);
}
const CreateFolderDialog = (props) => {
const [textValue, setTextValue] = useState(null);
const handleChange = (e) => {
setTextValue(e.target.value);
}
let { cancelText, okText, labelText, placeholderText } = props;
return (
<form
onSubmit={(e) => {onSubmit(e, path + '/' + textValue, method)}}
id="dialog"
>
<label>
<b>{labelText}</b>
</label>
<p><input type="text" placeholder={placeholderText} onChange={handleChange}/></p>
<p>
<input id="ok" className="dialog-button" type="submit" value={okText} />
<button onClick={() => setDialogState(null)} id="cancel" className="dialog-button">{cancelText}</button>
</p>
</form>
);
}
const RenameDialog = (props) => {
const [textValue, setTextValue] = useState(null);
const handleChange = (e) => {
setTextValue(e.target.value);
}
let { cancelText, okText, labelText, placeholderText } = props;
return (
<form
onSubmit={(e) => {onSubmit(e, path + '/' + textValue, method)}}
id="dialog"
>
<label>
<b>{labelText}</b>
</label>
<p><input type="text" placeholder={placeholderText} onChange={handleChange}/></p>
<p>
<input id="ok" className="dialog-button" type="submit" value={okText} />
<button onClick={() => setDialogState(null)} id="cancel" className="dialog-button">{cancelText}</button>
</p>
</form>
);
}
let path, method;
let content = null;
switch (props.type)
{
case 'delete':
path = '/api/delete' + props.data;
method = 'DELETE';
content = <ConfirmDialog okText={'Ок'} cancelText={'Отмена'} labelText={'Удалить ' + props.data + '?'}/>;
break;
case 'folder':
path = '/api/create' + props.data; // + folderName
method = 'POST';
content = <CreateFolderDialog okText={'Создать'} cancelText={'Отмена'} labelText={'Новая папка'} placeholderText={'Имя папки...'}/>;
break;
case 'rename':
path = '/api/rename' + props.data; // + folderName
method = 'PATCH';
content = <RenameDialog okText={'Ок'} cancelText={'Отмена'} labelText={'Переименовать ' + props.data} placeholderText={'Новое имя...'}/>;
break;
default:
break;
}
return (
<div id="dialog-wrapper" onClick={(e) => {if (e.target.id === "dialog-wrapper") setDialogState(null)}}>
{content}
</div>
);
}
export default Dialog;
<file_sep>import React, { Component } from 'react';
import { withRouter } from "react-router";
import './ContextMenu.css';
class ContextMenu extends Component {
async onDownload() {
this.props.toggleVisibility();
try {
const { location, target } = this.props;
const response = await fetch('api/download' + location.pathname + '/' + target.name);
if (response.ok)
{
let blob = await response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', target.name);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
console.log('Downloaded');
}
else
{
console.log("Response.Code != 200");
}
} catch(err) {
console.log(err.message);
}
}
onCreateFolder() {
this.props.toggleVisibility();
const { location, setDialogState } = this.props;
let path = location.pathname;
setDialogState('folder', path);
}
onDelete() {
this.props.toggleVisibility();
const { location, target, setDialogState } = this.props;
let path = location.pathname + '/' + target.name;
setDialogState('delete', path);
}
onPrint() {
this.props.toggleVisibility();
const { location, target, setDialogState } = this.props;
let path = location.pathname + '/' + target.name;
setDialogState('print', path);
}
onRename() {
this.props.toggleVisibility();
const { location, target, setDialogState } = this.props;
let path = location.pathname + '/' + target.name;
setDialogState('rename', path);
}
render() {
const { x, y, target } = this.props;
let targetType;
if (target.name === 'header')
{
targetType = 0; // HEADER
}
else
{
targetType = target.isDirectory
? 1 // DIRECTORY
: 2; // FILE
}
let styles = {
'position': 'absolute',
'top': y + 'px',
'left': x + 'px'
}
return (
<div className="context-menu noselect" style = {styles} ref={this.props.setContextMenuRef}>
<ul>
<li onClick = {() => this.onCreateFolder()}>Новая папка</li>
{ targetType === 2 && <li onClick = {() => this.onDownload()}>Скачать</li>}
{ targetType > 0 && <li onClick = {() => this.onRename()}>Переименовать</li> }
{ targetType === 2 && <li onClick = {() => this.onPrint()}>Печать</li> }
{ targetType > 0 && <li onClick = {() => this.onDelete()}>Удалить</li> }
</ul>
</div>
);
}
}
export default withRouter(ContextMenu);<file_sep>import React, { Component } from 'react';
import './FileTable.css';
import TableRow from './TableRow';
import ContextMenu from '../ContextMenu/ContextMenu';
import { withRouter } from "react-router";
import Dialog from '../Dialog/Dialog';
class FileTable extends Component {
constructor(props) {
super(props);
this.state = {
storage: [],
isDragOver: false,
EnterCounter: 0,
loading: true,
showMenu: false,
contextProps: {},
dialogState: null,
dialogData: null
}
this.table = React.createRef(); // Для отслеживания размера
this.contextMenuRef = null; // Реф для закрытия контекстного меню по клику на пустое место
this.fetchStorage = this.fetchStorage.bind(this);
this.sortFunc = this.sortFunc.bind(this);
this.contextmenuHandler = this.contextmenuHandler.bind(this);
this.clickOutsideHandler = this.clickOutsideHandler.bind(this);
this.contextmenuCloseHandler = this.contextmenuCloseHandler.bind(this);
this.setDialogState = this.setDialogState.bind(this);
}
componentDidMount() {
document.addEventListener('contextmenu', (e) => e.preventDefault());
document.addEventListener('click', this.clickOutsideHandler);
this.fetchStorage();
}
componentDidUpdate(prevProps) {
if (prevProps.location.pathname !== this.props.location.pathname)
this.fetchStorage();
}
async fetchStorage() {
this.setState({loading: true})
let path = this.props.location.pathname;
try {
const response = await fetch('/api/storage' + path);
if (response.ok)
{
let data = await response.json();
let storage = data.reduce((prev, curr) => {
if (curr.isDirectory)
prev.folders.push(curr);
else
prev.files.push(curr);
return {
files:prev.files,
folders:prev.folders
};
}, {files:[],folders:[]});
this.setState({loading:false, storage: storage});
}
else
{
console.log("Response.Code != 200");
}
} catch(error) {
console.log(error.message);
}
}
/*
Drag and drop
*/
async dropHandler(e) {
e.preventDefault();
try {
if (e.dataTransfer.items) {
const payload = new FormData();
let path = this.props.location.pathname;
for (let i = 0; i < e.dataTransfer.files.length; i++) {
payload.append("payload", e.dataTransfer.files[i]);
}
await fetch(`/api/upload${path}`, {
method:'POST',
body: payload
});
await this.fetchStorage();
}
} catch(error) {
console.log(error.message);
}
this.setState({isDragOver: false, EnterCounter: 0});
}
dragoverHandler(e) {
e.preventDefault();
}
dragleaveHandler(e) {
e.preventDefault();
let counter = this.state.EnterCounter;
counter--;
this.setState({EnterCounter: counter});
if (counter === 0)
this.setState({isDragOver: false});
}
dragenterHandler(e) {
e.preventDefault();
this.setState({isDragOver: true});
let counter = this.state.EnterCounter;
counter++;
this.setState({EnterCounter: counter});
}
/* -------------- */
/*
Контекстное меню
*/
contextmenuHandler(e, target) {
e.preventDefault();
let leftOffset = this.table.current.getBoundingClientRect().left;
this.setState({
showMenu: true,
contextProps: {
x: e.pageX - leftOffset,
y: e.pageY,
target: target
}
});
}
setContextMenuRef = element => {
this.contextMenuRef = element;
};
clickOutsideHandler(e){
if (this.state.showMenu)
{
if (this.contextMenuRef && !this.contextMenuRef.contains(e.target))
{
this.setState({showMenu: false});
}
}
}
contextmenuCloseHandler() {
this.setState({showMenu: !this.state.showMenu});
}
setDialogState(type, data = null) {
this.setState({dialogState: type, dialogData: data});
}
/* ----------------- */
sortFunc(a, b) {
let factor = this.props.sortDirection;
let result = 0;
switch(this.props.sortKey)
{
case 'name':
if (a.name < b.name)
result = -1;
if (a.name > b.name)
result = 1;
break;
case 'size':
if (a.size < b.size)
result = -1;
if (a.size > b.size)
result = 1;
break;
case 'mtime':
if (a.mtime < b.mtime)
result = -1;
if (a.mtime > b.mtime)
result = 1;
break;
default:
break;
}
return result * factor;
}
renderTable() {
let storage = this.state.storage;
return (
<tbody>
{storage.folders
.sort(this.sortFunc)
.map(f =>
<TableRow
key = {f.name}
file = {f}
contextmenuHandler = {this.contextmenuHandler}
/>
)}
{storage.files
.sort(this.sortFunc)
.map(f =>
<TableRow
key = {f.name}
file = {f}
contextmenuHandler = {this.contextmenuHandler}
/>
)}
</tbody>
);
}
render() {
let {
loading,
dialogState,
dialogData,
} = this.state;
let contents = loading
? <tbody><tr><td colSpan='4' align="center">Loading</td></tr></tbody>
: this.renderTable();
const sortKey = this.props.sortKey;
const sortDirection = this.props.sortDirection === 1 ? "⇑" : "⇓";
let tableClassNames = "noselect drop-zone";
if (this.state.isDragOver)
{
tableClassNames+=" dragging";
}
return (
<div className="table-wrapper">
{this.state.showMenu && <ContextMenu
toggleVisibility = {this.contextmenuCloseHandler}
setContextMenuRef = {this.setContextMenuRef}
setDialogState = {this.setDialogState}
{...this.state.contextProps}
/>}
<Dialog
type = {dialogState}
data = {dialogData}
setDialogState = {this.setDialogState}
fetchStorage = {this.fetchStorage}
/>
<table className= {tableClassNames}
ref={this.table}
onDrop = {(e) => this.dropHandler(e)}
onDragOver = {(e) => this.dragoverHandler(e)}
onDragLeave = {(e) => this.dragleaveHandler(e)}
onDragEnter = {(e) => this.dragenterHandler(e)}
>
<thead>
<tr onContextMenu = {(e) => this.contextmenuHandler(e, {name:'header'})}>
<th className="type"/>
<th className="name" onClick={(e) => this.props.onHeaderClick(e)}>
Имя { sortKey === 'name' && sortDirection }
</th>
<th className="size" onClick={(e) => this.props.onHeaderClick(e)}>
Размер { sortKey === 'size' && sortDirection }
</th>
<th className="mtime" onClick={(e) => this.props.onHeaderClick(e)}>
Дата изменения { sortKey === 'mtime' && sortDirection }
</th>
</tr>
</thead>
{contents}
</table>
</div>
)
}
}
export default withRouter(FileTable);<file_sep>import React from 'react';
import './App.css';
import {
BrowserRouter as Router,
Route,
} from "react-router-dom";
import FileExplorer from './FileExplorer';
import BackButton from './BackButton/BackButton';
function App() {
return (
<div className="wrapper">
<Router>
<BackButton/>
<div className="App">
<Route path="/:path?" component = {FileExplorer}/>
</div>
</Router>
</div>
);
}
export default App;
|
f16a26eef72a510ed51e1fe7814d3d96aeaa1483
|
[
"JavaScript"
] | 7
|
JavaScript
|
MeetYourRuiner/Pi-File-Explorer
|
08b264428034f17c53667fd454ef76ed3386f225
|
416270a793f3c312a1022635168ed452c6eee136
|
refs/heads/master
|
<repo_name>jlucangelio/matasano-crypto-challenges<file_sep>/challenge19.py
import utils
CIPHERTEXTS = []
NONCE = 0
KEY = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
with open("challenge19.txt") as f:
for i, line in enumerate(f.readlines()):
# print line.strip()
plaintext = utils.ByteArray.fromBase64(line.strip())
CIPHERTEXTS.append(utils.aes_ctr_encrypt(plaintext, KEY, NONCE))
# print CIPHERTEXTS
byte_count = {}
max_count = 0
max_byte = None
for c in CIPHERTEXTS:
for byte in c:
if byte not in byte_count:
byte_count[byte] = 0
byte_count[byte] += 1
if byte_count[byte] > max_count:
max_count = byte_count[byte]
max_byte = byte
byte_counts = byte_count.items()
print sorted(byte_counts, key=lambda p: p[1])
print len(byte_counts)
print
# print byte_count
print max_byte
substitutions = {}
substitutions[max_byte] = 'e'
print substitutions
<file_sep>/README.md
# matasano-crypto-challenges
http://cryptopals.com/
<file_sep>/aes_ecb.py
import utils
from Crypto.Cipher import AES
# obj = AES.new("YELLOW SUBMARINE", AES.MODE_ECB, "")
with open("7.txt") as f:
ba = utils.ByteArray.fromBase64(f.read())
print utils.aes_ecb_decrypt(ba, utils.ByteArray.fromString("YELLOW SUBMARINE"))
with open("8.txt") as f:
for line_index, line in enumerate(f.readlines()):
line = line.strip()
blocks = {}
for i in range(len(line) / 2 / 8):
block = line[16*i:16*(i+1)]
if block not in blocks:
blocks[block] = 0
blocks[block] += 1
if blocks[block] > 1:
print line_index, block
# print blocks
<file_sep>/ecb_cbc_detection.py
import utils
import Crypto.Random.random as random
def random_key(nbytes):
return utils.ByteArray.random(nbytes)
def encryption_oracle(input_data):
key = random_key(16)
prefixlen = random.randint(5, 10)
suffixlen = random.randint(5, 10)
prefix = utils.ByteArray.random(prefixlen)
suffix = utils.ByteArray.random(suffixlen)
input_ba = utils.ByteArray.fromString(input_data)
input_ba.prepend(prefix)
input_ba.extend(suffix)
input_ba.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
iv = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
if random.randint(0, 1) == 0:
print "using ECB"
ret = utils.aes_ecb_encrypt(input_ba, key)
else:
print "using CBC"
ret = utils.aes_cbc_encrypt(input_ba, key, iv)
return ret
def detect_ecb_cbc(oracle):
hexstring = "00" * utils.AES_BLOCKSIZE_BYTES * 6
ciphertext = oracle(hexstring)
block_count = {}
for block_index in range(ciphertext.nblocks(utils.AES_BLOCKSIZE_BYTES)):
block = ciphertext.block(utils.AES_BLOCKSIZE_BYTES, block_index).asHexString()
if block in block_count:
block_count[block] += 1
else:
block_count[block] = 1
for v in block_count.values():
if v > 1:
return "ECB"
return "CBC"
if __name__ == "__main__":
key = random_key(16).asHexString()
print len(key) / 2, key
print encryption_oracle("subidubisubidubi")
print
for i in range(10):
print detect_ecb_cbc(encryption_oracle)
print
<file_sep>/ecb_decryption.py
import utils
import ecb_cbc_detection
UNKNOWN_STRING = """<KEY>"""
KEY = utils.ByteArray.random(16)
def oracle(input_data):
input_ba = utils.ByteArray.fromString(input_data)
input_ba.extend(utils.ByteArray.fromBase64(UNKNOWN_STRING))
input_ba.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
ret = utils.aes_ecb_encrypt(input_ba, KEY)
return ret
if __name__ == "__main__":
bs = None
padding = None
l = len(oracle(""))
for i in range(64):
ctext = oracle("A" * (i+1))
if len(ctext) != l:
bs = len(ctext) - l
padding = i
break
print "block size", bs
print "padding", padding
if ecb_cbc_detection.detect_ecb_cbc(oracle) != "ECB":
print "Not ECB"
unknown_string = ""
blocks = {}
for unknown_block in range(l / bs):
print unknown_block
for i in range(bs):
blocks.clear()
for c in range(256):
attempt = "A" * (bs - i - 1) + unknown_string + chr(c)
ctext = oracle(attempt)
block = ctext.block(bs, unknown_block).asHexString()
blocks[block] = attempt
input_data = "A" * (bs - i - 1)
ctext = oracle(input_data).block(bs, unknown_block).asHexString()
block = blocks[ctext]
unknown_string += block[-1]
if len(unknown_string) == l - padding:
break
print unknown_string
<file_sep>/aes_cbc.py
import utils
with open("10.txt") as f:
ciphertext = utils.ByteArray.fromBase64(f.read())
print utils.aes_cbc_decrypt(ciphertext, utils.ByteArray.fromString("YELLOW SUBMARINE"),
iv=utils.ByteArray.fromHexString("00" * 16))
<file_sep>/ctr.py
import utils
b64 = "<KEY>
CIPHERTEXT = utils.ByteArray.fromBase64(b64)
plaintext = utils.aes_ctr_decrypt(CIPHERTEXT, "YELLOW SUBMARINE", 0)
print plaintext
print utils.aes_ctr_decrypt(utils.aes_ctr_decrypt(plaintext, "YELLOW SUBMARINE", 0),
"YELLOW SUBMARINE", 0)
<file_sep>/cbc_padding_oracle.py
import utils
import random
import sys
from collections import deque
STRINGS = """<KEY>""".splitlines()
KEY = utils.ByteArray.random_key()
def encrypt():
s = random.choice(STRINGS)
p = utils.ByteArray.fromBase64(s)
# q = utils.ByteArray.fromBase64(s)
# q.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
# print q.blocksAsHexStrings(utils.AES_BLOCKSIZE_BYTES)
iv = utils.ByteArray.random_block()
c = utils.aes_cbc_encrypt(p, KEY, iv)
return c, iv
def decrypt(ciphertext, iv):
plaintext = utils.aes_cbc_decrypt(ciphertext, KEY, iv)
# print "plaintext", plaintext.blocksAsHexStrings(utils.AES_BLOCKSIZE_BYTES)
try:
utils.pkcs7validate(plaintext)
except:
return False
# print "valid plaintext", plaintext.blocksAsHexStrings(utils.AES_BLOCKSIZE_BYTES)
return True
c, iv = encrypt()
all_decrypted_bytes = []
nblocks = c.nblocks(utils.AES_BLOCKSIZE_BYTES)
if nblocks < 3:
print "short ciphertext"
sys.exit(1)
for nblock in range(0, nblocks):
if nblock == 0:
previous_cblock = iv
else:
previous_cblock = c.block(utils.AES_BLOCKSIZE_BYTES, nblock - 1)
corrupted = utils.ByteArray.fromHexString("00" * utils.AES_BLOCKSIZE_BYTES)
corrupted.extend(c.block(utils.AES_BLOCKSIZE_BYTES, nblock))
# print "len(corrupted)", len(corrupted)
decrypted_bytes = [None for _ in range(16)]
for count in range(1, utils.AES_BLOCKSIZE_BYTES + 1):
# print "count", count
byte_idx = utils.AES_BLOCKSIZE_BYTES - count
# print "byte_idx", byte_idx
padding_value = count
# Set previous bytes.
for prev_idx in range(utils.AES_BLOCKSIZE_BYTES - count + 1, utils.AES_BLOCKSIZE_BYTES):
# print "prev_idx", prev_idx
ri = corrupted.get_byte(prev_idx)
corrupted.set_byte(prev_idx, decrypted_bytes[prev_idx] ^
previous_cblock.get_byte(prev_idx) ^
padding_value)
# Try current byte.
for i in range(256):
rb = corrupted.get_byte(byte_idx)
corrupted.set_byte(byte_idx, i)
if decrypt(corrupted, iv):
decrypted_bytes[byte_idx] = (previous_cblock.get_byte(byte_idx) ^
i ^ padding_value)
corrupted.set_byte(byte_idx, rb)
break
all_decrypted_bytes.extend(decrypted_bytes)
plaintext = utils.ByteArray.fromHexString("".join(["%02x" % h for h in all_decrypted_bytes]))
print utils.pkcs7validate(plaintext)
<file_sep>/utils.py
import base64
import binascii
from Crypto.Cipher import AES
from Crypto.Random import random
AES_BLOCKSIZE_BYTES = 16
SET_BITS = {
0x0: 0, # 0000
0x1: 1, # 0001
0x2: 1, # 0010
0x3: 2, # 0011
0x4: 1, # 0100
0x5: 2, # 0101
0x6: 2, # 0110
0x7: 3, # 0111
0x8: 1, # 1000
0x9: 2, # 1001
0xa: 2, # 1010
0xb: 3, # 1011
0xc: 2, # 1100
0xd: 3, # 1101
0xe: 3, # 1110
0xf: 4, # 1111
}
class Error(Exception):
pass
class PaddingError(Error):
pass
class ByteArray(object):
@classmethod
def fromInt(cls, integer):
return cls.fromHexString("%032x" % integer)
@classmethod
def fromHexString(cls, hexstring):
return cls(bytearray.fromhex(hexstring))
@classmethod
def fromBase64(cls, b64string):
return cls(bytearray(base64.b64decode(b64string)))
@classmethod
def fromString(cls, string):
return cls(bytearray(string))
@classmethod
def random(cls, nbytes):
hexstring = "".join(["%02x" % random.randrange(256) for _ in range(nbytes)])
return cls.fromHexString(hexstring)
@classmethod
def random_key(cls):
return cls.random(AES_BLOCKSIZE_BYTES)
@classmethod
def random_block(cls):
return cls.random(AES_BLOCKSIZE_BYTES)
def __init__(self, ba=None):
if ba is not None:
self.ba = ba
else:
self.ba = bytearray()
def __eq__(self, other):
return self.ba == other.ba
def __ne__(self, other):
return self.ba != other.ba
def __str__(self):
return str(self.ba)
def asHexString(self):
return "".join(["%02x" % b for b in self.ba])
def asBase64(self):
return base64.b64encode("".join(str(self)))
def asString(self):
return self.ba.decode()
def __len__(self):
return len(self.ba)
def __getitem__(self, key):
return self.ba[key]
def __setitem__(self, key, value):
self.ba[key] = value
def __iter__(self):
return self.ba.__iter__()
def iterkeys(self):
return self.__iter__()
def append(self, e):
self.ba.append(e)
def extend(self, other):
self.ba.extend(other)
def prepend(self, other):
self.ba = other.ba + self.ba
def nblocks(self, blocksize):
return len(self) // blocksize
def block(self, blocksize, i):
if i < 0:
i = i + self.nblocks(blocksize)
return self.__class__(self[blocksize*i:blocksize*(i+1)])
def blocks(self, blocksize):
res = []
for i in range(self.nblocks(blocksize)):
res.append(self.block(blocksize, i))
return res
def blocksAsHexStrings(self, blocksize):
return [b.asHexString() for b in self.blocks(blocksize)]
def pkcs7pad(self, blocksize):
self.extend(pkcs7(self, blocksize).ba)
def bitwise_and(self, byte_idx, byte):
self.ba[byte_idx] = self.ba[byte_idx] & byte
def bitwise_or(self, byte_idx, byte):
self.ba[byte_idx] = self.ba[byte_idx] | byte
def get_byte(self, byte_idx):
return self.ba[byte_idx]
def set_byte(self, byte_idx, byte):
self.ba[byte_idx] = byte
def fixed_xor(plaintext, key):
res = ByteArray()
for i, byte in enumerate(plaintext):
res.append(byte ^ key[i])
return res
def repeating_xor(bplaintext, bkey):
q = len(bplaintext) // len(bkey)
r = len(bplaintext) % len(bkey)
full_key = ByteArray()
for _ in range(q):
full_key.extend(bkey.ba)
full_key.extend(bkey[:r])
return fixed_xor(bplaintext, full_key)
def freq_analysis(ba):
max_count = 0
candidate_string = None
candidate_key = None
for char in range(256):
skey = ("%02x" % char) * len(ba)
key = ByteArray.fromHexString(skey)
plaintext = fixed_xor(ba, key)
count = 0
for b in plaintext:
c = chr(b)
if "a" <= c <= "z" or "A" <= c <= "Z":
count += 1
if c in "etaoinshrETAOINSHR":
count += 1
elif c == " " or c == "'":
pass
else:
count -= 2
if count > max_count:
max_count = count
candidate_string = plaintext
candidate_key = char
return candidate_string, candidate_key, max_count
def set_bits(b):
return SET_BITS[b & 0xF] + SET_BITS[(b & 0xF0) >> 4]
def hamming_distance(string1, string2):
count = 0
ba1 = ByteArray.fromString(string1)
ba2 = ByteArray.fromString(string2)
xored = fixed_xor(ba1, ba2)
for b in xored:
count += set_bits(b)
return count
def pkcs7(ba, blocksize):
num_bytes = blocksize - (len(ba) % blocksize)
if num_bytes == 0:
num_bytes = block_size
padding = ("%02x" % num_bytes) * num_bytes
return ByteArray.fromHexString(padding)
def aes_ecb_decrypt(ciphertext, key):
obj = AES.new(str(key), AES.MODE_ECB, "")
return ByteArray.fromString(obj.decrypt(str(ciphertext)))
def aes_ecb_encrypt(plaintext, key):
obj = AES.new(str(key), AES.MODE_ECB, "")
return ByteArray.fromString(obj.encrypt(str(plaintext)))
def aes_cbc_decrypt(ciphertext, key, iv):
# P_i = D_k(C_i) ^ C_{i-1}, C_{-1} = IV
plaintext = ByteArray()
last_cblock = iv
for i in range(ciphertext.nblocks(AES_BLOCKSIZE_BYTES)):
cblock = ciphertext.block(AES_BLOCKSIZE_BYTES, i)
pblock = fixed_xor(aes_ecb_decrypt(cblock, key), last_cblock)
last_cblock = cblock
plaintext.extend(pblock)
return plaintext
def aes_cbc_encrypt(plaintext, key, iv):
# C_i = D_k(P_i ^ C_{i-1}), C_{-1} = IV
ciphertext = ByteArray()
last_cblock = iv
plaintext.pkcs7pad(AES_BLOCKSIZE_BYTES)
for i in range(plaintext.nblocks(AES_BLOCKSIZE_BYTES)):
pblock = plaintext.block(AES_BLOCKSIZE_BYTES, i)
cblock = aes_ecb_encrypt(fixed_xor(pblock, last_cblock), key)
last_cblock = cblock
ciphertext.extend(cblock)
return ciphertext
def aes_ctr_encrypt(plaintext, key, nonce):
counter = 0
ciphertext = ByteArray()
banonce = bytearray.fromhex("%016x" % nonce)
banonce.reverse()
for i in range(plaintext.nblocks(AES_BLOCKSIZE_BYTES)):
bacounter = bytearray.fromhex("%016x" % counter)
bacounter.reverse()
source = ByteArray(banonce + bacounter)
pblock = plaintext.block(AES_BLOCKSIZE_BYTES, i)
keystream = aes_ecb_encrypt(source, key)
cblock = fixed_xor(pblock, keystream)
ciphertext.extend(cblock)
counter += 1
return ciphertext
def aes_ctr_encrypt(plaintext, key, nonce):
return aes_ctr_decrypt(plaintext, key, nonce)
def pkcs7validate(plaintext):
last_block = plaintext.block(AES_BLOCKSIZE_BYTES, -1)
num = last_block[AES_BLOCKSIZE_BYTES - 1]
if num > AES_BLOCKSIZE_BYTES:
raise PaddingError()
if num < AES_BLOCKSIZE_BYTES:
padding = last_block[-num:]
else:
padding = last_block
if all([b == num for b in padding]):
return ByteArray(plaintext[:-num])
else:
raise PaddingError()
if __name__ == "__main__":
hexstr = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
b64str = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
print ByteArray.fromHexString(hexstr).asBase64()
b64res = ByteArray.fromHexString(hexstr).asBase64()
print "hex2base64", b64res == b64str
hexres = ByteArray.fromBase64(b64str).asHexString()
print "base642hex", hexres == hexstr
plaintext = ByteArray.fromHexString("1c0111001f010100061a024b53535009181c")
key = ByteArray.fromHexString("686974207468652062756c6c277320657965")
fixed_xor_result = ByteArray.fromHexString("746865206b696420646f6e277420706c6179")
print "fixed_xor", fixed_xor(plaintext, key) == fixed_xor_result
print freq_analysis(ByteArray.fromHexString("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"))
print freq_analysis(ByteArray.fromHexString("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"))[0]
line = ByteArray.fromString("Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal")
res = repeating_xor(line, ByteArray.fromString("ICE")).asHexString()
print "repeating_xor", res == "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
print set_bits(0), set_bits(0x1), set_bits(0x0A), set_bits(0x78), set_bits(0xF8)
print "hamming_distance", hamming_distance("this is a test", "wokka wokka!!!") == 37
print "pkcs7", pkcs7(ByteArray.fromString("YELLOW SUBMARINE"), 20).asHexString()
print "16", pkcs7(ByteArray.fromString("A" * 16), 16)[-1]
ys = ByteArray.fromString("YELLOW SUBMARINE")
key = ByteArray.fromString("YELLOW SUBMARINE")
ys.pkcs7pad(20)
print "pkcs7pad", ys.asHexString()
print "aes_ecb_encrypt", aes_ecb_encrypt(key, key)
print "aes_ecb_decrypt", aes_ecb_decrypt(aes_ecb_encrypt(key, key), key)
yss = ByteArray.fromString("YELLOW SUBMARINES")
iv = ByteArray.fromHexString("00" * AES_BLOCKSIZE_BYTES)
print "aes_cbc_decrypt", aes_cbc_decrypt(aes_cbc_encrypt(key, key, iv), key, iv)
print "aes_cbc_decrypt", aes_cbc_decrypt(aes_cbc_encrypt(yss, key, iv), key, iv)
print "24", len(pkcs7validate(ByteArray.fromHexString("AA" * 24 + "08" * 8)))
try:
print "Should raise PaddingError..."
pkcs7validate(ByteArray.fromHexString("AA" * 24 + "09" * 8))
print "... did not raise PaddingError"
except PaddingError as pe:
print "... raised PaddingError"
try:
print "Should raise PaddingError..."
pkcs7validate(ByteArray.fromHexString("AA" * 32))
print "... did not raise PaddingError"
except PaddingError as pe:
print "... raised PaddingError"
<file_sep>/detect_single-char_xor.py
import utils
with open("4.txt") as f:
candidate = None
max_count = 0
for line in f.readlines():
decrypted, key, count = utils.freq_analysis(utils.ByteArray.fromHexString(line.strip()))
if count > max_count:
max_count = count
candidate = decrypted
print candidate
<file_sep>/19-break_fixed-nonce_ctr.py
import utils
ciphertexts = []
with open("19.txt") as f:
for line in f.readlines():
line.strip()
<file_sep>/cbc_bitflipping.py
import utils
PREFIX = "comment1=cooking%20MCs;userdata="
SUFFIX = ";comment2=%20like%20a%20pound%20of%20bacon"
KEY = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
IV = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
def encrypt(data):
plaintext = utils.ByteArray.fromString(PREFIX)
escaped = data.split(";")[0].split("=")[0]
if len(escaped) > 0:
plaintext.extend(utils.ByteArray.fromString(escaped))
plaintext.extend(utils.ByteArray.fromString(SUFFIX))
plaintext.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
return utils.aes_cbc_encrypt(plaintext, KEY, IV)
def decrypt(ciphertext):
plaintext = utils.aes_cbc_decrypt(ciphertext, KEY, IV)
print plaintext
items = str(plaintext).split(";")
for item in items:
k, v = item.split("=")
if k == "admin" and v == "true":
return True
return False
# Byte 5
# Bit 0
print len(PREFIX)
print "from %x to %x" % (ord(":"), ord(";"))
print "from %x to %x" % (ord("<"), ord("="))
ciphertext = encrypt("aaaaa:admin<true")
ciphertext.bitwise_or(16 + 5, 0x1)
ciphertext.bitwise_or(16 + 11, 0x1)
print decrypt(ciphertext)
<file_sep>/break_fixed-nonce_ctr.py
import utils
STRINGS = """<KEY>""
KEY = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
lines = [utils.aes_ctr_encrypt(utils.ByteArray.fromBase64(string.strip()), KEY, 0) for string in STRINGS.splitlines()]
print lines
<file_sep>/break_repeating-key_xor.py
import utils
with open("6.txt") as f:
contents = utils.ByteArray.fromBase64(f.read())
# print contents.asBase64()
normalized_edit_dists = {}
min_edit_dist = 40 * 8
for keysize in range(2, 41):
edit_dist = utils.hamming_distance(contents[:keysize],
contents[2*keysize:3*keysize]) / float(keysize)
edit_dist2 = utils.hamming_distance(contents[keysize:2*keysize],
contents[3*keysize:4*keysize]) / float(keysize)
normalized_edit_dists[keysize] = (edit_dist + edit_dist2) / 2
keysizes = sorted(normalized_edit_dists.iteritems(), key=lambda v: v[1])
possible_keysizes = keysizes[:3]
print "key sizes", possible_keysizes
for possible_keysize, _ in possible_keysizes:
transposed_blocks = [utils.ByteArray() for _ in range(possible_keysize)]
for i, e in enumerate(contents):
transposed_blocks[i % possible_keysize].append(e)
possible_key = [utils.freq_analysis(block) for block in transposed_blocks]
key = utils.ByteArray()
for r in possible_key:
if r[1] is None:
break
key.append(r[1])
if len(key) < possible_keysize:
continue
print utils.repeating_xor(contents, key)
break
<file_sep>/ecb_cut-n-paste.py
import utils
from collections import OrderedDict
KEY = utils.ByteArray.random(16)
def parse(s):
res = OrderedDict()
fields = s.split("&")
for field in fields:
k, v = field.split("=")
res[k] = v
return res
def unparse(d):
res = []
for k in d:
v = d[k]
if type(v) == str and ("=" in v or "&" in v):
continue
res.append("%s=%s" % (k, v))
return "&".join(res)
def profile_for(email):
return unparse(OrderedDict([("email", email), ("uid", 10), ("role", "user")]))
def encrypt_profile(email):
ptext = utils.ByteArray.fromString(profile_for(email))
ptext.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
return utils.aes_ecb_encrypt(ptext, KEY)
def decrypt_profile(p):
ptext = utils.aes_ecb_decrypt(p, KEY).asString()
last_byte = ord(ptext[-1])
if last_byte >= 1 and last_byte <= 15:
ptext = ptext[:-last_byte]
return parse(ptext)
if __name__ == "__main__":
s = "foo=bar&baz=qux&zap=zazzle"
print parse(s)
print s == unparse(parse(s))
print "profile_for", profile_for("<EMAIL>") == "email=<EMAIL>&uid=10&role=user"
print decrypt_profile(encrypt_profile("<EMAIL>"))
# len("email=<EMAIL>") == 16
first_block = "<EMAIL>"
role = "admin"
nbytes = 16 - len(role)
ptext = role + (chr(nbytes) * nbytes)
print repr(ptext), len(ptext)
admin_block = encrypt_profile(first_block + ptext).blocksAsHexStrings(16)[1]
# "email=<EMAIL>&uid=10&role=" + "admin" + padding
ptext = "<EMAIL>&uid=10&role="
s = "A" * (16 - (len(ptext) % 16))
print s, len(s + ptext)
blocks = encrypt_profile(s + "@bar.com").blocksAsHexStrings(16)
p = blocks[:-1] + [admin_block]
print decrypt_profile(utils.ByteArray.fromHexString("".join(p)))
<file_sep>/ecb_decryption_hard.py
import utils
# import Crypto.Random.random as random
import random
import ecb_cbc_detection
UNKNOWN_STRING = """<KEY>"""
KEY = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
PREFIX = utils.ByteArray.random(random.randrange(1, utils.AES_BLOCKSIZE_BYTES))
def oracle(input_data):
plaintext = utils.ByteArray()
plaintext.extend(PREFIX)
plaintext.extend(utils.ByteArray.fromString(input_data))
plaintext.extend(utils.ByteArray.fromBase64(UNKNOWN_STRING))
plaintext.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)
ret = utils.aes_ecb_encrypt(plaintext, KEY)
return ret
def find_prefix_length(bs):
zeros = "0" * bs * 2
for i in range(bs):
prefix = "0" * i + zeros
print prefix
ctext = oracle(prefix)
blocks = ctext.blocksAsHexStrings(bs)
last_block = blocks[0]
for bindex, block in enumerate(blocks):
if bindex == 0:
continue
if block == last_block:
return bs - i
last_block = block
print "Can't find prefix length"
if __name__ == "__main__":
print oracle("subidubisubidubi").asHexString()
bs = None
padding = None
l = min([len(oracle("")) for _ in range(8)])
print l
for i in range(32):
ctext = oracle("A" * (i+1))
if len(ctext) != l:
bs = abs(len(ctext) - l)
padding = i
break
print "block size", bs
print "padding", padding
if ecb_cbc_detection.detect_ecb_cbc(oracle) != "ECB":
print "Not ECB"
unknown_string = ""
blocks = {}
prefix_length = find_prefix_length(bs)
print "prefix_length", prefix_length
l = l - prefix_length
print "l", l
rest = bs - prefix_length
for unknown_block in range(l / bs):
print unknown_block
for i in range(bs):
blocks.clear()
for c in range(256):
attempt = "A" * rest + "A" * (bs - i - 1) + unknown_string + chr(c)
ctext = oracle(attempt)
block = ctext.block(bs, unknown_block + 1).asHexString()
blocks[block] = attempt
input_data = "A" * rest + "A" * (bs - i - 1)
ctext = oracle(input_data).block(bs, unknown_block + 1).asHexString()
block = blocks[ctext]
unknown_string += block[-1]
if len(unknown_string) == l - padding:
break
print unknown_string
|
2c1e4715664c448fe5db7eb70d6993b78a41b7f0
|
[
"Markdown",
"Python"
] | 16
|
Python
|
jlucangelio/matasano-crypto-challenges
|
76695eb946055c4b36363e90a667741649b8c0b6
|
3265397645b30d25bdf4d38ecd6dc142fb6ce2a4
|
refs/heads/main
|
<repo_name>Fanger53/init_rails<file_sep>/app/views/costumers/_costumer.json.jbuilder
json.extract! costumer, :id, :name, :last, :customer_id, :created_at, :updated_at
json.url costumer_url(costumer, format: :json)
<file_sep>/test/controllers/costumers_controller_test.rb
require 'test_helper'
class CostumersControllerTest < ActionDispatch::IntegrationTest
setup do
@costumer = costumers(:one)
end
test "should get index" do
get costumers_url
assert_response :success
end
test "should get new" do
get new_costumer_url
assert_response :success
end
test "should create costumer" do
assert_difference('Costumer.count') do
post costumers_url, params: { costumer: { customer_id: @costumer.customer_id, last: @costumer.last, name: @costumer.name } }
end
assert_redirected_to costumer_url(Costumer.last)
end
test "should show costumer" do
get costumer_url(@costumer)
assert_response :success
end
test "should get edit" do
get edit_costumer_url(@costumer)
assert_response :success
end
test "should update costumer" do
patch costumer_url(@costumer), params: { costumer: { customer_id: @costumer.customer_id, last: @costumer.last, name: @costumer.name } }
assert_redirected_to costumer_url(@costumer)
end
test "should destroy costumer" do
assert_difference('Costumer.count', -1) do
delete costumer_url(@costumer)
end
assert_redirected_to costumers_url
end
end
<file_sep>/app/models/costumer.rb
class Costumer < ApplicationRecord
end
<file_sep>/test/system/costumers_test.rb
require "application_system_test_case"
class CostumersTest < ApplicationSystemTestCase
setup do
@costumer = costumers(:one)
end
test "visiting the index" do
visit costumers_url
assert_selector "h1", text: "Costumers"
end
test "creating a Costumer" do
visit costumers_url
click_on "New Costumer"
fill_in "Customer", with: @costumer.customer_id
fill_in "Last", with: @costumer.last
fill_in "Name", with: @costumer.name
click_on "Create Costumer"
assert_text "Costumer was successfully created"
click_on "Back"
end
test "updating a Costumer" do
visit costumers_url
click_on "Edit", match: :first
fill_in "Customer", with: @costumer.customer_id
fill_in "Last", with: @costumer.last
fill_in "Name", with: @costumer.name
click_on "Update Costumer"
assert_text "Costumer was successfully updated"
click_on "Back"
end
test "destroying a Costumer" do
visit costumers_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Costumer was successfully destroyed"
end
end
<file_sep>/app/controllers/costumers_controller.rb
class CostumersController < ApplicationController
before_action :set_costumer, only: [:show, :edit, :update, :destroy]
# GET /costumers
# GET /costumers.json
def index
@costumers = Costumer.all
end
# GET /costumers/1
# GET /costumers/1.json
def show
end
# GET /costumers/new
def new
@costumer = Costumer.new
end
# GET /costumers/1/edit
def edit
end
# POST /costumers
# POST /costumers.json
def create
@costumer = Costumer.new(costumer_params)
respond_to do |format|
if @costumer.save
format.html { redirect_to @costumer, notice: 'Costumer was successfully created.' }
format.json { render :show, status: :created, location: @costumer }
else
format.html { render :new }
format.json { render json: @costumer.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /costumers/1
# PATCH/PUT /costumers/1.json
def update
respond_to do |format|
if @costumer.update(costumer_params)
format.html { redirect_to @costumer, notice: 'Costumer was successfully updated.' }
format.json { render :show, status: :ok, location: @costumer }
else
format.html { render :edit }
format.json { render json: @costumer.errors, status: :unprocessable_entity }
end
end
end
# DELETE /costumers/1
# DELETE /costumers/1.json
def destroy
@costumer.destroy
respond_to do |format|
format.html { redirect_to costumers_url, notice: 'Costumer was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_costumer
@costumer = Costumer.find(params[:id])
end
# Only allow a list of trusted parameters through.
def costumer_params
params.require(:costumer).permit(:name, :last, :customer_id)
end
end
<file_sep>/app/views/costumers/index.json.jbuilder
json.array! @costumers, partial: "costumers/costumer", as: :costumer
<file_sep>/app/views/costumers/show.json.jbuilder
json.partial! "costumers/costumer", costumer: @costumer
|
2181e72fca830f97b3fd56c02af240263f76d948
|
[
"Ruby"
] | 7
|
Ruby
|
Fanger53/init_rails
|
c39ea6a79ca4a8d67cfd822ea1d704f8627421e1
|
a332f9cf3bd85624d7b1360cd4aeeb8f92cc94af
|
refs/heads/master
|
<repo_name>jdobner/gradle-experiments<file_sep>/creating-multi-project-builds/greeting-library/build.gradle
plugins {
id 'groovy'
id 'java-library'
}
dependencies {
api 'org.codehaus.groovy:groovy:2.4.10'
testImplementation 'org.spockframework:spock-core:1.0-groovy-2.4', {
exclude module: 'groovy-all'
}
}
<file_sep>/lifecycle/settings.gradle
println '[settings] This is executed during the initialization phase.'<file_sep>/creating-multi-project-builds/build.gradle
plugins {
id 'org.asciidoctor.convert' version '1.5.6' apply true
}
allprojects {
repositories {
jcenter()
}
}
subprojects {
version = '1.0'
}
//see https://github.com/tkruse/gradle-groovysh-plugin/tree/master/doc for running groovysh<file_sep>/lifecycle/src/main/java/Demo.java
public class Demo {
public static void main(String [] args) {
System.out.println(">>>> RAN OK <<<<<");
}
}<file_sep>/lifecycle/build.gradle
plugins {
id 'java'
}
println '[.] This is executed during the configuration phase.'
task configured {
println '[configured] This is also executed during the configuration phase.'
}
task testBoth {
doFirst {
println '[testBoth.doFirst] This is executed first during the execution phase.'
}
doLast {
println '[testBoth.doLast] This is executed last during the execution phase.'
}
println '[testBoth] This is executed during the configuration phase as well.'
dependsOn {
println 'dependsOn called'
'test'
}
description 'Super Important task that JayDee invented'
group 'g1'
// dependsOn('foo')
}
task testMe {
doLast {
println '[test.doLast] This is executed during the execution phase.'
}
group 'g1'
println "delegate=$delegate"
}
testMe {
doFirst {
println '[test.doFirst] This is executed during the execution phase.'
}
}
testMe {
doFirst {
println '[test.doFirstFirst] This is executed during the execution phase.'
}
}
testMe {
doLast {
println '[test.doLastLast] This is executed during the execution phase.'
}
}
task ignoreMe {
println "Configuring $delegate"
doFirst {
println "[$delegate] executing"
}
}
testMe.dependsOn(ignoreMe)
test {
println "[$delegate] configuring test"
}
compileJava {
doLast {
def t = project.getTasks().findByPath "Demo.main()"
t.configure {
doFirst {
println "<><><><><><><><><><><"
}
}
}
}
|
1ef3b689e4b4bcf102b0c51f61d88a9ef1349296
|
[
"Java",
"Gradle"
] | 5
|
Gradle
|
jdobner/gradle-experiments
|
0cf35adf674efcdbce974921f632b2114911d381
|
3a8a242e0561246b4f53fa3c1e53120bf6133dbb
|
refs/heads/master
|
<repo_name>isokar/gladys-serial<file_sep>/lib/setup.js
var SerialPort = require('serialport');
var Promise = require('bluebird');
var connect = require('./connect.js');
module.exports = function() {
// first, we list all connected USB devices
return listUsbDevices()
.then(function(ports) {
sails.log.info(`List of available connected Arduinos(pick the name of the one with RFLink and put it -as it is- in the Serial_tty variable on Gladys):`);
// we keep only the arduinos
return filterArduino(ports);
})
};
function filterArduino(ports) {
var arduinos = [];
// foreach port we test if it is an arduino
ports.forEach(function(port) {
if (port.manufacturer && port.manufacturer.toLowerCase().search("arduino") != -1) {
sails.log.info(`-` + port.comName);
arduinos.push(port);
}
});
return Promise.resolve(arduinos);
}
function listUsbDevices() {
return new Promise(function(resolve, reject) {
SerialPort.list(function(err, ports) {
if (err) return reject(new Error(err));
return resolve(ports);
});
});
}
|
cf2e25421b3c7a4ec4b21245a6d09369243e30cb
|
[
"JavaScript"
] | 1
|
JavaScript
|
isokar/gladys-serial
|
15c6cc6770d47906e470542e997620e05801f5a5
|
a4642c7a88a1aa4e5072fd2a228156e5d97c480d
|
refs/heads/master
|
<repo_name>careeryumi/Game<file_sep>/FinalProjectShell/Components/HighScoreComponent.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;
namespace FinalProjectShell
{
public class HighScoreComponent : DrawableGameComponent
{
Texture2D texture;
private Vector2 picturePosition;
string fileName = "highScore.txt";
string scoreFromFile;
SpriteFont font;
string comment = "High score is : ";
string currentHighScoreToString = "";
public HighScoreComponent(Game game) : base(game)
{
}
public override void Draw(GameTime gameTime)
{
SpriteBatch spriteBatch = Game.Services.GetService<SpriteBatch>();
spriteBatch.Begin();
spriteBatch.DrawString(font, comment, new Vector2(400, 160), Color.White);
spriteBatch.DrawString(font, currentHighScoreToString, new Vector2(400, 200), Color.White);
spriteBatch.End();
base.Draw(gameTime);
currentHighScoreToString = "";
}
public override void Initialize()
{
base.Initialize();
}
public override void Update(GameTime gameTime)
{
if (File.Exists(fileName))
{
using (StreamReader reader = new StreamReader(fileName))
{
scoreFromFile = reader.ReadLine();
currentHighScoreToString = currentHighScoreToString + scoreFromFile;
}
}
base.Update(gameTime);
}
protected override void LoadContent()
{
picturePosition = new Vector2(30, 20);
font = Game.Content.Load<SpriteFont>("fonts\\regularFont");
texture = Game.Content.Load<Texture2D>("Images/backgroundLargeSize");
base.LoadContent();
}
}
}
<file_sep>/FinalProjectShell/Background.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
namespace FinalProjectShell
{
class Background : DrawableGameComponent
{
Texture2D bgdFull;
public Background(Game game) : base(game)
{
}
public override void Draw(GameTime gameTime)
{
SpriteBatch sb = Game.Services.GetService<SpriteBatch>();
sb.Begin();
sb.Draw(bgdFull, new Rectangle(0, 0, Game.GraphicsDevice.Viewport.Width,
Game.GraphicsDevice.Viewport.Height),
Color.White);
sb.End();
base.Draw(gameTime);
}
protected override void LoadContent()
{
bgdFull = Game.Content.Load<Texture2D>("Images/witchsBackground");
base.LoadContent();
}
}
}
<file_sep>/FinalProjectShell/ScoreDisplay/ScoreString.cs
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FinalProjectShell
{
class ScoreString : DrawableGameComponent
{
protected string displayString;
string fontName;
SpriteFont font;
public ScoreString(Game game, string fontName) : base(game)
{
this.fontName = fontName;
displayString = "";
}
public override void Draw(GameTime gameTime)
{
SpriteBatch sb = Game.Services.GetService<SpriteBatch>();
sb.Begin();
sb.DrawString(font, displayString, GetScoreStringPosition(), Color.White);
sb.End();
base.Draw(gameTime);
}
/// <summary>
/// Get score position that is located
/// </summary>
/// <returns></returns>
private Vector2 GetScoreStringPosition()
{
Vector2 location = Vector2.Zero;
float stringWidth = font.MeasureString(displayString).X;
int displayWidth = Game.GraphicsDevice.Viewport.Width;
location.X = displayWidth - stringWidth;
location.Y = 0;
return location;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
protected override void LoadContent()
{
font = Game.Content.Load<SpriteFont>(fontName);
base.LoadContent();
}
}
}
<file_sep>/FinalProjectShell/PumpkinManager.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Threading;
namespace FinalProjectShell
{
class PumpkinManager : GameComponent
{
double secondsSinceLast = 0.0;
const double PUMPKIN_INTERVAL = 0.8;
Random random;
public PumpkinManager(Game game) : base(game)
{
random = new Random();
//this.parent = parent;
}
public override void Update(GameTime gameTime)
{
secondsSinceLast += gameTime.ElapsedGameTime.TotalSeconds;
if (secondsSinceLast > PUMPKIN_INTERVAL)
{
Vector2 location = new Vector2(random.Next(Game.GraphicsDevice.Viewport.Width),
random.Next(Game.GraphicsDevice.Viewport.Height));
Game.Components.Add(new Pumpkin(Game, GetRandomPumpkinType(), location));
secondsSinceLast = 0.0;
}
base.Update(gameTime);
}
/// <summary>
/// Get random pumpkin's type
/// </summary>
/// <returns></returns>
private PumpkinType GetRandomPumpkinType()
{
int pumpkinMax = Enum.GetNames(typeof(PumpkinType)).Length;
int randomPumpkin = random.Next(0, pumpkinMax);
return (PumpkinType)randomPumpkin;
}
}
}
<file_sep>/FinalProjectShell/PumpkinValue.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
namespace FinalProjectShell
{
enum PumpkinValue
{
orangePumpkin = 10,
doubleScorePumpkin = 20,
TripleScorePumpkin = 30,
ghost = -50
}
}
<file_sep>/FinalProjectShell/ScoreDisplay/Score.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace FinalProjectShell
{
class Score : ScoreString
{
int score = 0;
public Score(Game game, string fontName) : base(game, fontName)
{
if (Game.Services.GetService<Score>() == null)
{
Game.Services.AddService<Score>(this);
}
}
public override void Update(GameTime gameTime)
{
displayString = $"Score: {score}";
base.Update(gameTime);
}
/// <summary>
/// Add score
/// </summary>
/// <param name="value">value</param>
public void AddScore(int value)
{
score += value;
}
/// <summary>
/// Make score to zero
/// </summary>
public void SetScoreToZero()
{
score = 0;
}
/// <summary>
/// Return final score
/// </summary>
/// <returns></returns>
public int ReturnFinalScore()
{
return score;
}
}
}
<file_sep>/FinalProjectShell/ScoreDisplay/DisplayControl.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Text;
using System;
namespace FinalProjectShell
{
class DisplayControl : ScoreString
{
public DisplayControl(Game game, string fontName) : base(game, fontName)
{
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
private int GetLives()
{
throw new NotImplementedException();
}
private int GetScore()
{
throw new NotImplementedException();
}
}
}
<file_sep>/FinalProjectShell/Scenes/ActionScene.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
/* Name: <NAME>
Assignment: Final Assignment
This program is a game for catching pumpkins
Course Code: PROG-2370-4 Game Programming with Data Structures
Professor: <NAME>
Date: December 7, 2019 */
namespace FinalProjectShell
{
public class ActionScene : GameScene
{
double gameStartTime = 0;
double gameRunningTime = 20;
SoundEffect gameEndFx;
bool gameEnd = false;
string fileName = "highScore.txt";
int scoreFromFile;
public ActionScene (Game game): base(game)
{
}
public override void Initialize()
{
gameStartTime = 0;
// create and add any components that belong to this scene
this.SceneComponents.Add(new Background(Game));
this.SceneComponents.Add(new Basket(Game));
this.SceneComponents.Add(new PumpkinManager(Game));
this.SceneComponents.Add(new Score(Game, "fonts\\regularFont"));
this.SceneComponents.Add(new DisplayControl(Game, "fonts\\regularFont"));
base.Initialize();
}
public void AddComponent(GameComponent component)
{
this.SceneComponents.Add(component);
Game.Components.Add(component);
}
public override void Update(GameTime gameTime)
{
gameEnd = false;
gameStartTime += gameTime.ElapsedGameTime.TotalSeconds;
//check if game time passed, end game
if (gameStartTime > gameRunningTime)
{
gameEndFx = Game.Content.Load<SoundEffect>("Sounds/gameOverSound");
gameEndFx.Play();
((Game1)Game).HideAllScenes();
Game.Services.GetService<GameEndScene>().Show();
if (File.Exists(fileName))
{
using (StreamReader reader = new StreamReader(fileName))
{
scoreFromFile = int.Parse(reader.ReadLine());
}
if (scoreFromFile < Game.Services.GetService<Score>().ReturnFinalScore())
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(Game.Services.GetService<Score>().ReturnFinalScore().ToString());
}
}
}
gameStartTime = 0;
Game.Services.GetService<Score>().SetScoreToZero();
gameEnd = true;
SetGameEndFlag(gameEnd);
}
if (Enabled)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
gameStartTime = 0;
((Game1)Game).HideAllScenes();
Game.Services.GetService<StartScene>().Show();
}
}
base.Update(gameTime);
}
/// <summary>
/// store if the game ended or not
/// </summary>
/// <param name="gameEnd">gameEnd</param>
public void SetGameEndFlag(bool gameEnd)
{
this.gameEnd = gameEnd;
}
/// <summary>
/// return gameEnd value
/// </summary>
/// <returns></returns>
public bool GetGameEndFlag()
{
return gameEnd;
}
}
}
<file_sep>/FinalProjectShell/Pumpkin.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
/* Name: <NAME>
Date: December 7, 2019 */
namespace FinalProjectShell
{
class Pumpkin : DrawableGameComponent
{
private Texture2D randomPumpkin;
private Vector2 randomPumpkinPosition;
float scale = 1f;
PumpkinType pumpkinType = PumpkinType.orangePumpkin;
SoundEffect collisionFx;
List<Texture2D> pumpkins;
public Pumpkin(Game game) : base(game)
{
}
public Pumpkin(Game game, PumpkinType pumpkinType, Vector2 location) : base(game)
{
this.pumpkinType = pumpkinType;
}
public override void Draw(GameTime gameTime)
{
SpriteBatch sb = Game.Services.GetService<SpriteBatch>();
sb.Begin();
sb.Draw(randomPumpkin,
randomPumpkinPosition,
null,
Color.AntiqueWhite,
0.0f,
Vector2.Zero,
scale,
SpriteEffects.None,
0f);
sb.End();
base.Draw(gameTime);
}
public override void Initialize()
{
pumpkins = new List<Texture2D>();
base.Initialize();
}
public override void Update(GameTime gameTime)
{
randomPumpkinPosition.Y += 0.5f;
CheckCollisionWithPumpkin();
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
((Game1)Game).HideAllScenes();
Game.Services.GetService<StartScene>().Show();
Game.Components.Remove(this);
}
if (Game.Services.GetService<ActionScene>().GetGameEndFlag() == true)
{
Game.Components.Remove(this);
}
base.Update(gameTime);
}
/// <summary>
/// check if pumpkin and basket has a collision,
/// if true, make a sound
/// </summary>
private void CheckCollisionWithPumpkin()
{
Basket getbasket = Game.Services.GetService<Basket>();
Rectangle pumpkinRect = randomPumpkin.Bounds;
pumpkinRect.Location = randomPumpkinPosition.ToPoint();
if (pumpkinRect.Intersects(getbasket.GetBasketRectangle()))
{
if (GetPumpkinValue() == 10)
{
collisionFx = Game.Content.Load<SoundEffect>("Sounds/OrangePumpkinSound");
collisionFx.Play();
}
else if (GetPumpkinValue() == 20)
{
collisionFx = Game.Content.Load<SoundEffect>("Sounds/OrangePumpkinSound");
collisionFx.Play();
}
else if (GetPumpkinValue() == 30)
{
collisionFx = Game.Content.Load<SoundEffect>("Sounds/whitePumpkinSound");
collisionFx.Play();
}
else if (GetPumpkinValue() == -50)
{
collisionFx = Game.Content.Load<SoundEffect>("Sounds/ghostSound");
collisionFx.Play();
}
CollectPumpkin();
Game.Components.Remove(this);
}
}
/// <summary>
/// Collect collided pumkin and add to the score
/// </summary>
private void CollectPumpkin()
{
Game.Services.GetService<Score>().AddScore(GetPumpkinValue());
}
/// <summary>
/// get each pumpkins value to add to the score
/// </summary>
/// <returns></returns>
private int GetPumpkinValue()
{
switch (pumpkinType)
{
case PumpkinType.doubleScorePumpkin:
return (int)PumpkinValue.doubleScorePumpkin;
case PumpkinType.ghost:
return (int)PumpkinValue.ghost;
case PumpkinType.orangePumpkin:
return (int)PumpkinValue.orangePumpkin;
case PumpkinType.tripleCorePumpkin:
return (int)PumpkinValue.TripleScorePumpkin;
default:
return 0;
}
}
protected override void LoadContent()
{
randomPumpkin = Game.Content.Load<Texture2D>($"Images/{pumpkinType.ToString()}");
Random random = new Random();
randomPumpkinPosition = new Vector2(random.Next(0, GraphicsDevice.Viewport.Width), 0);
base.LoadContent();
}
}
}
<file_sep>/FinalProjectShell/Basket.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
/* Name: <NAME>
Date: December 7, 2019 */
namespace FinalProjectShell
{
class Basket : DrawableGameComponent
{
float scale = 1f;
private Vector2 basketPosition;
private Vector2 speed;
// animation state
List<Texture2D> baskets;
int currentFrame = 0;
const double FRAME_DURATION = 1;
double frameTimer = 0.0;
bool forwardFrame = true;
const int MAX_FRAME = 2;
Song backgroundMusic;
public Basket(Game game) : base(game)
{
speed = new Vector2(4, 0);
backgroundMusic = Game.Content.Load<Song>("Sounds/gameBackgroundMusic");
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(backgroundMusic);
}
/// <summary>
/// get basket's rectangle
/// </summary>
/// <returns></returns>
public Rectangle GetBasketRectangle()
{
Rectangle basketRect = baskets[currentFrame].Bounds;
basketRect.Location = basketPosition.ToPoint();
return basketRect;
}
public override void Draw(GameTime gameTime)
{
SpriteBatch sb = Game.Services.GetService<SpriteBatch>();
sb.Begin();
sb.Draw(baskets[currentFrame],
basketPosition,
null,
Color.AntiqueWhite,
0.0f,
Vector2.Zero,
scale,
SpriteEffects.None,
0f);
sb.End();
base.Draw(gameTime);
}
public override void Update(GameTime gameTime)
{
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Right))
{
basketPosition += speed;
}
else if (ks.IsKeyDown(Keys.Left))
{
basketPosition -= speed;
}
// here we make sure that we are not off screen, we
// clap the value to between 0 and width of screen - texture width
//position.X = MathHelper.Clamp(position.X, 0, GraphicsDevice.Viewport.Width - texture.Width);
basketPosition.X = MathHelper.Clamp(basketPosition.X, 0, GraphicsDevice.Viewport.Width - 70);
UpdateFrameInfo(gameTime);
base.Update(gameTime);
}
/// <summary>
/// Update animation info
/// </summary>
/// <param name="gameTime"></param>
private void UpdateFrameInfo(GameTime gameTime)
{
frameTimer += gameTime.ElapsedGameTime.TotalSeconds;
if (frameTimer >= FRAME_DURATION)
{
if (forwardFrame)
{
currentFrame++;
if (currentFrame == MAX_FRAME - 1)
{
forwardFrame = !forwardFrame;
}
}
else //backwards
{
currentFrame--;
if (currentFrame <= 0)
{
forwardFrame = !forwardFrame;
}
}
frameTimer = 0;
}
}
protected override void LoadContent()
{
baskets.Add(Game.Content.Load<Texture2D>("Images/basket"));
baskets.Add(Game.Content.Load<Texture2D>("Images/basket2"));
basketPosition = new Vector2(GraphicsDevice.Viewport.Width / 2,
GraphicsDevice.Viewport.Height - 60);
base.LoadContent();
}
public override void Initialize()
{
baskets = new List<Texture2D>();
base.Initialize();
}
}
}
<file_sep>/FinalProjectShell/ScoreDisplay/StringLocation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FinalProjectShell
{
public enum StringLocation
{
TopRight
}
}
<file_sep>/FinalProjectShell/Scenes/HighScoreScene.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FinalProjectShell
{
class HighScoreScene : GameScene
{
public HighScoreScene(Game game) : base(game)
{
}
public override void Initialize()
{
this.SceneComponents.Add(new HighScoreComponent(Game));
this.Hide();
base.Initialize();
}
public override void Update(GameTime gameTime)
{
if (Enabled)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
((Game1)Game).HideAllScenes();
Game.Services.GetService<StartScene>().Show();
}
}
base.Update(gameTime);
}
}
}
<file_sep>/FinalProjectShell/PumpkinType.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
namespace FinalProjectShell
{
enum PumpkinType
{
orangePumpkin,
doubleScorePumpkin,
tripleCorePumpkin,
ghost
}
}
|
ab7b70efe37552023184e8ce6f270ee3a56a817f
|
[
"C#"
] | 13
|
C#
|
careeryumi/Game
|
3dfc75a1dbaedcd0f00a089b133f1250b5b17c9d
|
1ef1329ab2d198b3846bf253b9ec7f7713f67e3c
|
refs/heads/master
|
<file_sep>#!/bin/sh
curl -s -H "X-CLIENT-TYPE: android-phone" -H "X-CLIENT-VERSION: 2.9.4-rc2" -H "X-Pipejump-Auth: $1" -H "X-Futuresimple-Token: $1" -H "X-Futuresimple-Api-Token: $1" $2 | python -mjson.tool
<file_sep>function init_rvmrc(){
current_dir=$(basename `pwd`)
ruby_version=$(rvm use $1> /dev/null && ~/.rvm/bin/rvm-prompt 2> /dev/null) || return
#rvm --rvmrc --create ${ruby_version}@${current_dir}
rvm use ${ruby_version}
rvm gemset create ${current_dir}
rvm use ${ruby_version}@${current_dir}
echo rvm ${ruby_version}@${current_dir} > ./.rvmrc
}
<file_sep>#! /usr/bin/ruby
# This script is based on the one found in the Powder gem,
# but without Thor dependency. I also removed install and
# uninstall commands, since they aren't part of the workflow.
# Check https://github.com/Rodreegez/powder/blob/master/bin/pow
# for the original script.
#
# ====== Installation ======
# Save this gist in your scripts folder.
# $ chmod +x /<SCRIPT_FOLDER>/pow
# In your .bashrc or equivalent:
# alias pow='/<SCRIPT_FOLDER>/pow'
# ==========================
require 'fileutils'
POWPATH = "/Users/#{`whoami`.chomp}/.pow"
def main
options = %w(link list remove restart help)
if ARGV.empty?
link
else
cmd = options.grep(/^#{ARGV.first}/)
if cmd.empty?
$stdout.puts "Command #{ARGV.first} not found."
help
elsif cmd.count > 1
$stdout.puts "Command #{ARGV.first} is ambiguous [#{cmd.join(', ')}]"
else
begin
send(cmd.first, *ARGV[1..-1])
rescue ArgumentError => ae
$stdout.puts ae.message.capitalize
end
end
end
end
def link(name=nil)
return unless is_powable?
current_path = %x{pwd}.chomp
symink_path = "#{POWPATH}/#{name || File.basename(current_path)}"
FileUtils.ln_s(current_path, symink_path) unless File.exists?(symink_path)
end
def restart
return unless is_powable?
FileUtils.mkdir_p('tmp')
%x{touch tmp/restart.txt}
end
def list
Dir[POWPATH + "/*"].map { |a| $stdout.puts File.basename(a) }
end
def remove(name=nil)
return unless is_powable?
FileUtils.rm POWPATH + '/' + (name || File.basename(%x{pwd}.chomp))
end
def help
$stdout.puts <<-EOS
Pow is a zero-config Rack server for Mac OS X.
Usage:
pow link link the current dir_name to ~/.pow/dir_name
pow link bacon link the current dir to ~/.pow/bacon
pow list list all the current apps linked in ~/.pow
pow remove unlink current_dir
pow remove bacon unlink bacon
pow restart restart the current app
pow help show this help
EOS
end
private
def is_powable?
if File.exists?('config.ru') || File.exists?('public/index.html')
true
else
$stdout.puts "This does not appear to be a rack app as there is no config.ru."
$stdout.puts "If you are in a Rails 2 application, try https://gist.github.com/909308"
$stdout.puts "Pow can also host static apps if there is an index.html in public/"
false
end
end
main #Start
<file_sep># Path to your oh-my-zsh configuration.
export ZSH=$HOME/.oh-my-zsh
# Set to the name theme to load.
# Look in ~/.oh-my-zsh/themes/
export ZSH_THEME="eastwood" # "robbyrussell"
# Set to this to use case-sensitive completion
# export CASE_SENSITIVE="true"
# Comment this out to disable weekly auto-update checks
# export DISABLE_AUTO_UPDATE="true"
# Uncomment following line if you want to disable colors in ls
# export DISABLE_LS_COLORS="true"
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Example format: plugins=(rails git textmate ruby lighthouse)
plugins=(git github gem brew bundler osx)
source $ZSH/oh-my-zsh.sh
# Customize to your needs...
# Load all of your custom configurations from zsh-custom
for config_file ($HOME/.zsh-custom/*.zsh) source $config_file
export PATH=$HOME/bin:/usr/local/bin:/usr/local/sbin:/usr/local/share/npm/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session.
PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting
### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
export NODE_PATH=/usr/local/lib/node_modules/
unsetopt auto_name_dirs
unsetopt correct_all
__rvm_project_rvmrc
<file_sep>alias f='cd ~/code/fs'
alias fst='cd ~/code/github/fstech'
alias faut='cd ~/code/fs/automator'
alias fcom='cd ~/code/fs/common'
alias fcor='cd ~/code/fs/core'
alias fcrm='cd ~/code/fs/crm'
alias ffee='cd ~/code/fs/feeder'
alias fint='cd ~/code/fs/integrator'
alias flea='cd ~/code/fs/leads'
alias fmai='cd ~/code/fs/mailman'
alias fpay='cd ~/code/fs/payments'
alias fsal='cd ~/code/fs/sales'
alias fsee='cd ~/code/fs/seeker'
alias fsle='cd ~/code/fs/sleipnir'
alias ftag='cd ~/code/fs/tags'
alias fupl='cd ~/code/fs/uploader'
alias fvoi='cd ~/code/fs/voice'
alias fapi='cd ~/code/fs/fs-api'
alias fappf='cd ~/code/fs/app-frontend'
alias fcrmf='cd ~/code/fs/crm-frontend'
alias fperf='cd ~/code/fs/permissions-frontend'
alias fsalf='cd ~/code/fs/sales-frontend'
alias fsetf='cd ~/code/fs/settings-frontend'
alias fvoif='cd ~/code/fs/voice-frontend'
alias fleaf='cd ~/code/fs/leads-frontend'
alias cdp='cd ~/code/private'
alias cds='cd ~/code/spikes'
alias cdg='cd ~/code/github'
alias cdm='cd ~/code/github/mehowte'
alias cdd='cd ~/code/github/mehowte/dotfiles'
alias mvd='cdd && mvim'
setopt auto_cd
cdpath=(~/code/fs ~/code/private ~/code/spikes)
alias pw='cd ~/code/private/programmingworkout'
alias kp='cd ~/code/private/kanapress'
<file_sep>function mkd {
mkdir -p $1
cd $1
}
<file_sep>source /Users/mehowte/.rvm/scripts/rvm
<file_sep>EDITOR=(mvim -f -c "au VimLeave * !open -a iTerm")
export EDITOR
export GIT_EDITOR='mvim -f -c"au VimLeave * !open -a iTerm"'
export BUNDLER_EDITOR='mvim -f -c"au VimLeave * !open -a iTerm"'
alias v='mvim -c"au VimLeave * !open -a iTerm"'
alias vd='v -c "cd ~/code/github/mehowte/dotfiles"'
alias rz='source ~/.zshrc'
<file_sep>alias r='bundle exec rails'
alias rsp='bundle exec rake spec'
alias rcuc='bundle exec rake cucumber'
alias rdbm='bundle exec rake db:migrate db:test:clone'
alias rdbr='bundle exec rake db:migrate:rollback db:test:clone'
alias rdbmr='bundle exec rake db:migrate db:migrate:redo db:test:clone'
alias devlog='tail -f log/development.log'
alias testlog='tail -f log/test.log'
<file_sep>#function git(){hub "$@"}
alias g='git'
alias gst='git status'
alias gci='git commit'
alias gam='git commit -am'
alias gco='git checkout'
alias gl='git pull --rebase'
alias gp='git push'
alias gmt='git mergetool -t vimdiff'
alias grhh='git reset --hard HEAD'
alias gcfd='git clean -fd'
alias gcp='git cherry-pick'
alias glo='gl origin'
alias gpo='gp origin'
alias glom='glo master'
alias gpom='gpo master'
alias gloc='glo $(current_branch)'
alias gpoc='gpo $(current_branch)'
alias glog='git log --oneline --decorate --all'
alias glogg='git log --oneline --decorate --all --graph'
alias glogs='git log --decorate --all --stat'
|
fb30757f8996f397fc3690103251f8288fcc98f2
|
[
"Ruby",
"Shell"
] | 10
|
Shell
|
mehowte/dotfiles
|
04dfd5ca51c6ab1d10e237fd2544195b8cd2d96f
|
91dd378cd3cc11ee8d0ea2fcf10cda272d295e66
|
refs/heads/master
|
<repo_name>OpenNuvoton/N32901-3_NonOS_BSP<file_sep>/SIC_SECC/Src/fmi.h
#include <stdio.h>
#include "wbio.h"
//#define _SIC_USE_INT_
//#define DEBUG
#define TIMER0 0
//#define printf sysprintf
//#define _USE_DAT3_DETECT_
//-- function return value
#define Successful 0
#define Fail 1
#ifdef ECOS
#define sysGetTicks(TIMER0) cyg_current_time()
//#define printf diag_printf
#endif
// extern global variables
extern UINT32 _fmi_uFMIReferenceClock;
extern BOOL volatile _fmi_bIsSDDataReady;
#define STOR_STRING_LEN 32
/* we allocate one of these for every device that we remember */
typedef struct disk_data_t
{
struct disk_data_t *next; /* next device */
/* information about the device -- always good */
unsigned int totalSectorN;
unsigned int diskSize; /* disk size in Kbytes */
int sectorSize;
char vendor[STOR_STRING_LEN];
char product[STOR_STRING_LEN];
char serial[STOR_STRING_LEN];
} DISK_DATA_T;
// function declaration
// SD functions
INT fmiSDCommand(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg);
INT fmiSDCmdAndRsp(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg, INT nCount);
INT fmiSDCmdAndRsp2(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg, UINT *puR2ptr);
INT fmiSDCmdAndRspDataIn(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg);
INT fmiSD_Init(FMI_SD_INFO_T *pSD);
INT fmiSelectCard(FMI_SD_INFO_T *pSD);
VOID fmiGet_SD_info(FMI_SD_INFO_T *pSD, DISK_DATA_T *_info);
INT fmiSD_Read_in(FMI_SD_INFO_T *pSD, UINT32 uSector, UINT32 uBufcnt, UINT32 uDAddr);
INT fmiSD_Write_in(FMI_SD_INFO_T *pSD, UINT32 uSector, UINT32 uBufcnt, UINT32 uSAddr);
<file_sep>/I2S/example/Src/nau8822.h
void NAU8822_DACSetup(void);
void NAU8822_ADCSetup(void);
void NAU8822_ADC_DAC_Setup(void);
void NAU8822_Init(void);
int NAU8822_SetPlayVolume(unsigned int ucVolL, unsigned int ucVolR);
int NAU8822_SetRecVolume(unsigned int ucVolL, unsigned int ucVolR);
void NAU8822_SetSampleFreq(int uSample_Rate);
<file_sep>/KPI/lib/w55fa93_kpi.h
/****************************************************************************
* *
* Copyright (c) 2009 Nuvoton Tech. Corp. All rights reserved. *
* *
*****************************************************************************/
/****************************************************************************
* FILENAME
* nuc930_kpi.h
*
* VERSION
* 1.0
*
* DESCRIPTION
* KPI library header file
*
* DATA STRUCTURES
* None
*
* FUNCTIONS
*
* HISTORY
*
* REMARK
* None
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_reg.h"
#define KPI_NONBLOCK 0
#define KPI_BLOCK 1
extern void kpi_init(void);
extern int kpi_open(unsigned int src);
extern void kpi_close(void);
extern int kpi_read(unsigned char mode);
<file_sep>/BLT/lib/blt.h
#define E_SUCCESS 0
#define DRVBLT_VERSION_NUM 1
#ifndef _W55FA92_BLT_REG_H_
#define _W55FA92_BLT_REG_H_
#define E_SUCCESS 0
#define DRVBLT_VERSION_NUM 1
#define ELEMENTA REG_ELEMENTA
#define ELEMENTB REG_ELEMENTB
#define ELEMENTC REG_ELEMENTC
#define ELEMENTD REG_ELEMENTD
#define SFMT REG_SFMT
#define DFMT REG_DFMT
#define BLTINTCR REG_BLTINTCR
#define MLTB REG_MLTB
#define MLTG REG_MLTG
#define MLTR REG_MLTR
#define MLTA REG_MLTA
#define SADDR REG_SADDR
#define SSTRIDE REG_SSTRIDE
#define OFFSETSX REG_OFFSETSX
#define OFFSETSY REG_OFFSETSY
#define SWIDTH REG_SWIDTH
#define SHEIGHT REG_SHEIGHT
#define DADDR REG_DADDR
#define DSTRIDE REG_DSTRIDE
#define DWIDTH REG_DWIDTH
#define DHEIGHT REG_DHEIGHT
#define FILLARGB REG_FILLARGB
#define SET2DA REG_SET2DA
#define PALETTE REG_PALETTE
#define TR_RGB565 0xFFFF
#define TRCOLOR_R REG_TRCOLOR
#endif<file_sep>/SIC/example/Include/alone.h
#define FALSE 0
#define TRUE 1
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
#define _DWORD_(a) *((volatile DWORD *)(a))
#define _WORD_(a) *((volatile WORD *)(a))
#define _BYTE_(a) *((volatile BYTE *)(a))
<file_sep>/SIC_SECC/Src/Ecc4DecoderSyndromeFxLookup.h
#ifndef __ECC4DECODERRIBMLOOKUP_H__
#define __ECC4DECODERSYNDROMEFXLOOKUP_H__
unsigned char g_ucSyndromeF1Lookup[1024] =
{
0x00, 0x12, 0x09, 0x1b, 0x84, 0x96, 0x8d, 0x9f,
0x42, 0x50, 0x4b, 0x59, 0xc6, 0xd4, 0xcf, 0xdd,
0x21, 0x33, 0x28, 0x3a, 0xa5, 0xb7, 0xac, 0xbe,
0x63, 0x71, 0x6a, 0x78, 0xe7, 0xf5, 0xee, 0xfc,
0x10, 0x02, 0x19, 0x0b, 0x94, 0x86, 0x9d, 0x8f,
0x52, 0x40, 0x5b, 0x49, 0xd6, 0xc4, 0xdf, 0xcd,
0x31, 0x23, 0x38, 0x2a, 0xb5, 0xa7, 0xbc, 0xae,
0x73, 0x61, 0x7a, 0x68, 0xf7, 0xe5, 0xfe, 0xec,
0x08, 0x1a, 0x01, 0x13, 0x8c, 0x9e, 0x85, 0x97,
0x4a, 0x58, 0x43, 0x51, 0xce, 0xdc, 0xc7, 0xd5,
0x29, 0x3b, 0x20, 0x32, 0xad, 0xbf, 0xa4, 0xb6,
0x6b, 0x79, 0x62, 0x70, 0xef, 0xfd, 0xe6, 0xf4,
0x18, 0x0a, 0x11, 0x03, 0x9c, 0x8e, 0x95, 0x87,
0x5a, 0x48, 0x53, 0x41, 0xde, 0xcc, 0xd7, 0xc5,
0x39, 0x2b, 0x30, 0x22, 0xbd, 0xaf, 0xb4, 0xa6,
0x7b, 0x69, 0x72, 0x60, 0xff, 0xed, 0xf6, 0xe4,
0x96, 0x84, 0x9f, 0x8d, 0x12, 0x00, 0x1b, 0x09,
0xd4, 0xc6, 0xdd, 0xcf, 0x50, 0x42, 0x59, 0x4b,
0xb7, 0xa5, 0xbe, 0xac, 0x33, 0x21, 0x3a, 0x28,
0xf5, 0xe7, 0xfc, 0xee, 0x71, 0x63, 0x78, 0x6a,
0x86, 0x94, 0x8f, 0x9d, 0x02, 0x10, 0x0b, 0x19,
0xc4, 0xd6, 0xcd, 0xdf, 0x40, 0x52, 0x49, 0x5b,
0xa7, 0xb5, 0xae, 0xbc, 0x23, 0x31, 0x2a, 0x38,
0xe5, 0xf7, 0xec, 0xfe, 0x61, 0x73, 0x68, 0x7a,
0x9e, 0x8c, 0x97, 0x85, 0x1a, 0x08, 0x13, 0x01,
0xdc, 0xce, 0xd5, 0xc7, 0x58, 0x4a, 0x51, 0x43,
0xbf, 0xad, 0xb6, 0xa4, 0x3b, 0x29, 0x32, 0x20,
0xfd, 0xef, 0xf4, 0xe6, 0x79, 0x6b, 0x70, 0x62,
0x8e, 0x9c, 0x87, 0x95, 0x0a, 0x18, 0x03, 0x11,
0xcc, 0xde, 0xc5, 0xd7, 0x48, 0x5a, 0x41, 0x53,
0xaf, 0xbd, 0xa6, 0xb4, 0x2b, 0x39, 0x22, 0x30,
0xed, 0xff, 0xe4, 0xf6, 0x69, 0x7b, 0x60, 0x72,
0x4b, 0x59, 0x42, 0x50, 0xcf, 0xdd, 0xc6, 0xd4,
0x09, 0x1b, 0x00, 0x12, 0x8d, 0x9f, 0x84, 0x96,
0x6a, 0x78, 0x63, 0x71, 0xee, 0xfc, 0xe7, 0xf5,
0x28, 0x3a, 0x21, 0x33, 0xac, 0xbe, 0xa5, 0xb7,
0x5b, 0x49, 0x52, 0x40, 0xdf, 0xcd, 0xd6, 0xc4,
0x19, 0x0b, 0x10, 0x02, 0x9d, 0x8f, 0x94, 0x86,
0x7a, 0x68, 0x73, 0x61, 0xfe, 0xec, 0xf7, 0xe5,
0x38, 0x2a, 0x31, 0x23, 0xbc, 0xae, 0xb5, 0xa7,
0x43, 0x51, 0x4a, 0x58, 0xc7, 0xd5, 0xce, 0xdc,
0x01, 0x13, 0x08, 0x1a, 0x85, 0x97, 0x8c, 0x9e,
0x62, 0x70, 0x6b, 0x79, 0xe6, 0xf4, 0xef, 0xfd,
0x20, 0x32, 0x29, 0x3b, 0xa4, 0xb6, 0xad, 0xbf,
0x53, 0x41, 0x5a, 0x48, 0xd7, 0xc5, 0xde, 0xcc,
0x11, 0x03, 0x18, 0x0a, 0x95, 0x87, 0x9c, 0x8e,
0x72, 0x60, 0x7b, 0x69, 0xf6, 0xe4, 0xff, 0xed,
0x30, 0x22, 0x39, 0x2b, 0xb4, 0xa6, 0xbd, 0xaf,
0xdd, 0xcf, 0xd4, 0xc6, 0x59, 0x4b, 0x50, 0x42,
0x9f, 0x8d, 0x96, 0x84, 0x1b, 0x09, 0x12, 0x00,
0xfc, 0xee, 0xf5, 0xe7, 0x78, 0x6a, 0x71, 0x63,
0xbe, 0xac, 0xb7, 0xa5, 0x3a, 0x28, 0x33, 0x21,
0xcd, 0xdf, 0xc4, 0xd6, 0x49, 0x5b, 0x40, 0x52,
0x8f, 0x9d, 0x86, 0x94, 0x0b, 0x19, 0x02, 0x10,
0xec, 0xfe, 0xe5, 0xf7, 0x68, 0x7a, 0x61, 0x73,
0xae, 0xbc, 0xa7, 0xb5, 0x2a, 0x38, 0x23, 0x31,
0xd5, 0xc7, 0xdc, 0xce, 0x51, 0x43, 0x58, 0x4a,
0x97, 0x85, 0x9e, 0x8c, 0x13, 0x01, 0x1a, 0x08,
0xf4, 0xe6, 0xfd, 0xef, 0x70, 0x62, 0x79, 0x6b,
0xb6, 0xa4, 0xbf, 0xad, 0x32, 0x20, 0x3b, 0x29,
0xc5, 0xd7, 0xcc, 0xde, 0x41, 0x53, 0x48, 0x5a,
0x87, 0x95, 0x8e, 0x9c, 0x03, 0x11, 0x0a, 0x18,
0xe4, 0xf6, 0xed, 0xff, 0x60, 0x72, 0x69, 0x7b,
0xa6, 0xb4, 0xaf, 0xbd, 0x22, 0x30, 0x2b, 0x39,
0x25, 0x37, 0x2c, 0x3e, 0xa1, 0xb3, 0xa8, 0xba,
0x67, 0x75, 0x6e, 0x7c, 0xe3, 0xf1, 0xea, 0xf8,
0x04, 0x16, 0x0d, 0x1f, 0x80, 0x92, 0x89, 0x9b,
0x46, 0x54, 0x4f, 0x5d, 0xc2, 0xd0, 0xcb, 0xd9,
0x35, 0x27, 0x3c, 0x2e, 0xb1, 0xa3, 0xb8, 0xaa,
0x77, 0x65, 0x7e, 0x6c, 0xf3, 0xe1, 0xfa, 0xe8,
0x14, 0x06, 0x1d, 0x0f, 0x90, 0x82, 0x99, 0x8b,
0x56, 0x44, 0x5f, 0x4d, 0xd2, 0xc0, 0xdb, 0xc9,
0x2d, 0x3f, 0x24, 0x36, 0xa9, 0xbb, 0xa0, 0xb2,
0x6f, 0x7d, 0x66, 0x74, 0xeb, 0xf9, 0xe2, 0xf0,
0x0c, 0x1e, 0x05, 0x17, 0x88, 0x9a, 0x81, 0x93,
0x4e, 0x5c, 0x47, 0x55, 0xca, 0xd8, 0xc3, 0xd1,
0x3d, 0x2f, 0x34, 0x26, 0xb9, 0xab, 0xb0, 0xa2,
0x7f, 0x6d, 0x76, 0x64, 0xfb, 0xe9, 0xf2, 0xe0,
0x1c, 0x0e, 0x15, 0x07, 0x98, 0x8a, 0x91, 0x83,
0x5e, 0x4c, 0x57, 0x45, 0xda, 0xc8, 0xd3, 0xc1,
0xb3, 0xa1, 0xba, 0xa8, 0x37, 0x25, 0x3e, 0x2c,
0xf1, 0xe3, 0xf8, 0xea, 0x75, 0x67, 0x7c, 0x6e,
0x92, 0x80, 0x9b, 0x89, 0x16, 0x04, 0x1f, 0x0d,
0xd0, 0xc2, 0xd9, 0xcb, 0x54, 0x46, 0x5d, 0x4f,
0xa3, 0xb1, 0xaa, 0xb8, 0x27, 0x35, 0x2e, 0x3c,
0xe1, 0xf3, 0xe8, 0xfa, 0x65, 0x77, 0x6c, 0x7e,
0x82, 0x90, 0x8b, 0x99, 0x06, 0x14, 0x0f, 0x1d,
0xc0, 0xd2, 0xc9, 0xdb, 0x44, 0x56, 0x4d, 0x5f,
0xbb, 0xa9, 0xb2, 0xa0, 0x3f, 0x2d, 0x36, 0x24,
0xf9, 0xeb, 0xf0, 0xe2, 0x7d, 0x6f, 0x74, 0x66,
0x9a, 0x88, 0x93, 0x81, 0x1e, 0x0c, 0x17, 0x05,
0xd8, 0xca, 0xd1, 0xc3, 0x5c, 0x4e, 0x55, 0x47,
0xab, 0xb9, 0xa2, 0xb0, 0x2f, 0x3d, 0x26, 0x34,
0xe9, 0xfb, 0xe0, 0xf2, 0x6d, 0x7f, 0x64, 0x76,
0x8a, 0x98, 0x83, 0x91, 0x0e, 0x1c, 0x07, 0x15,
0xc8, 0xda, 0xc1, 0xd3, 0x4c, 0x5e, 0x45, 0x57,
0x6e, 0x7c, 0x67, 0x75, 0xea, 0xf8, 0xe3, 0xf1,
0x2c, 0x3e, 0x25, 0x37, 0xa8, 0xba, 0xa1, 0xb3,
0x4f, 0x5d, 0x46, 0x54, 0xcb, 0xd9, 0xc2, 0xd0,
0x0d, 0x1f, 0x04, 0x16, 0x89, 0x9b, 0x80, 0x92,
0x7e, 0x6c, 0x77, 0x65, 0xfa, 0xe8, 0xf3, 0xe1,
0x3c, 0x2e, 0x35, 0x27, 0xb8, 0xaa, 0xb1, 0xa3,
0x5f, 0x4d, 0x56, 0x44, 0xdb, 0xc9, 0xd2, 0xc0,
0x1d, 0x0f, 0x14, 0x06, 0x99, 0x8b, 0x90, 0x82,
0x66, 0x74, 0x6f, 0x7d, 0xe2, 0xf0, 0xeb, 0xf9,
0x24, 0x36, 0x2d, 0x3f, 0xa0, 0xb2, 0xa9, 0xbb,
0x47, 0x55, 0x4e, 0x5c, 0xc3, 0xd1, 0xca, 0xd8,
0x05, 0x17, 0x0c, 0x1e, 0x81, 0x93, 0x88, 0x9a,
0x76, 0x64, 0x7f, 0x6d, 0xf2, 0xe0, 0xfb, 0xe9,
0x34, 0x26, 0x3d, 0x2f, 0xb0, 0xa2, 0xb9, 0xab,
0x57, 0x45, 0x5e, 0x4c, 0xd3, 0xc1, 0xda, 0xc8,
0x15, 0x07, 0x1c, 0x0e, 0x91, 0x83, 0x98, 0x8a,
0xf8, 0xea, 0xf1, 0xe3, 0x7c, 0x6e, 0x75, 0x67,
0xba, 0xa8, 0xb3, 0xa1, 0x3e, 0x2c, 0x37, 0x25,
0xd9, 0xcb, 0xd0, 0xc2, 0x5d, 0x4f, 0x54, 0x46,
0x9b, 0x89, 0x92, 0x80, 0x1f, 0x0d, 0x16, 0x04,
0xe8, 0xfa, 0xe1, 0xf3, 0x6c, 0x7e, 0x65, 0x77,
0xaa, 0xb8, 0xa3, 0xb1, 0x2e, 0x3c, 0x27, 0x35,
0xc9, 0xdb, 0xc0, 0xd2, 0x4d, 0x5f, 0x44, 0x56,
0x8b, 0x99, 0x82, 0x90, 0x0f, 0x1d, 0x06, 0x14,
0xf0, 0xe2, 0xf9, 0xeb, 0x74, 0x66, 0x7d, 0x6f,
0xb2, 0xa0, 0xbb, 0xa9, 0x36, 0x24, 0x3f, 0x2d,
0xd1, 0xc3, 0xd8, 0xca, 0x55, 0x47, 0x5c, 0x4e,
0x93, 0x81, 0x9a, 0x88, 0x17, 0x05, 0x1e, 0x0c,
0xe0, 0xf2, 0xe9, 0xfb, 0x64, 0x76, 0x6d, 0x7f,
0xa2, 0xb0, 0xab, 0xb9, 0x26, 0x34, 0x2f, 0x3d,
0xc1, 0xd3, 0xc8, 0xda, 0x45, 0x57, 0x4c, 0x5e,
0x83, 0x91, 0x8a, 0x98, 0x07, 0x15, 0x0e, 0x1c
};
unsigned char g_ucSyndromeF2Lookup[1024] =
{
0x00, 0x09, 0x02, 0x0b, 0x84, 0x8d, 0x86, 0x8f,
0x01, 0x08, 0x03, 0x0a, 0x85, 0x8c, 0x87, 0x8e,
0x42, 0x4b, 0x40, 0x49, 0xc6, 0xcf, 0xc4, 0xcd,
0x43, 0x4a, 0x41, 0x48, 0xc7, 0xce, 0xc5, 0xcc,
0x00, 0x09, 0x02, 0x0b, 0x84, 0x8d, 0x86, 0x8f,
0x01, 0x08, 0x03, 0x0a, 0x85, 0x8c, 0x87, 0x8e,
0x42, 0x4b, 0x40, 0x49, 0xc6, 0xcf, 0xc4, 0xcd,
0x43, 0x4a, 0x41, 0x48, 0xc7, 0xce, 0xc5, 0xcc,
0x21, 0x28, 0x23, 0x2a, 0xa5, 0xac, 0xa7, 0xae,
0x20, 0x29, 0x22, 0x2b, 0xa4, 0xad, 0xa6, 0xaf,
0x63, 0x6a, 0x61, 0x68, 0xe7, 0xee, 0xe5, 0xec,
0x62, 0x6b, 0x60, 0x69, 0xe6, 0xef, 0xe4, 0xed,
0x21, 0x28, 0x23, 0x2a, 0xa5, 0xac, 0xa7, 0xae,
0x20, 0x29, 0x22, 0x2b, 0xa4, 0xad, 0xa6, 0xaf,
0x63, 0x6a, 0x61, 0x68, 0xe7, 0xee, 0xe5, 0xec,
0x62, 0x6b, 0x60, 0x69, 0xe6, 0xef, 0xe4, 0xed,
0x09, 0x00, 0x0b, 0x02, 0x8d, 0x84, 0x8f, 0x86,
0x08, 0x01, 0x0a, 0x03, 0x8c, 0x85, 0x8e, 0x87,
0x4b, 0x42, 0x49, 0x40, 0xcf, 0xc6, 0xcd, 0xc4,
0x4a, 0x43, 0x48, 0x41, 0xce, 0xc7, 0xcc, 0xc5,
0x09, 0x00, 0x0b, 0x02, 0x8d, 0x84, 0x8f, 0x86,
0x08, 0x01, 0x0a, 0x03, 0x8c, 0x85, 0x8e, 0x87,
0x4b, 0x42, 0x49, 0x40, 0xcf, 0xc6, 0xcd, 0xc4,
0x4a, 0x43, 0x48, 0x41, 0xce, 0xc7, 0xcc, 0xc5,
0x28, 0x21, 0x2a, 0x23, 0xac, 0xa5, 0xae, 0xa7,
0x29, 0x20, 0x2b, 0x22, 0xad, 0xa4, 0xaf, 0xa6,
0x6a, 0x63, 0x68, 0x61, 0xee, 0xe7, 0xec, 0xe5,
0x6b, 0x62, 0x69, 0x60, 0xef, 0xe6, 0xed, 0xe4,
0x28, 0x21, 0x2a, 0x23, 0xac, 0xa5, 0xae, 0xa7,
0x29, 0x20, 0x2b, 0x22, 0xad, 0xa4, 0xaf, 0xa6,
0x6a, 0x63, 0x68, 0x61, 0xee, 0xe7, 0xec, 0xe5,
0x6b, 0x62, 0x69, 0x60, 0xef, 0xe6, 0xed, 0xe4,
0x12, 0x1b, 0x10, 0x19, 0x96, 0x9f, 0x94, 0x9d,
0x13, 0x1a, 0x11, 0x18, 0x97, 0x9e, 0x95, 0x9c,
0x50, 0x59, 0x52, 0x5b, 0xd4, 0xdd, 0xd6, 0xdf,
0x51, 0x58, 0x53, 0x5a, 0xd5, 0xdc, 0xd7, 0xde,
0x12, 0x1b, 0x10, 0x19, 0x96, 0x9f, 0x94, 0x9d,
0x13, 0x1a, 0x11, 0x18, 0x97, 0x9e, 0x95, 0x9c,
0x50, 0x59, 0x52, 0x5b, 0xd4, 0xdd, 0xd6, 0xdf,
0x51, 0x58, 0x53, 0x5a, 0xd5, 0xdc, 0xd7, 0xde,
0x33, 0x3a, 0x31, 0x38, 0xb7, 0xbe, 0xb5, 0xbc,
0x32, 0x3b, 0x30, 0x39, 0xb6, 0xbf, 0xb4, 0xbd,
0x71, 0x78, 0x73, 0x7a, 0xf5, 0xfc, 0xf7, 0xfe,
0x70, 0x79, 0x72, 0x7b, 0xf4, 0xfd, 0xf6, 0xff,
0x33, 0x3a, 0x31, 0x38, 0xb7, 0xbe, 0xb5, 0xbc,
0x32, 0x3b, 0x30, 0x39, 0xb6, 0xbf, 0xb4, 0xbd,
0x71, 0x78, 0x73, 0x7a, 0xf5, 0xfc, 0xf7, 0xfe,
0x70, 0x79, 0x72, 0x7b, 0xf4, 0xfd, 0xf6, 0xff,
0x1b, 0x12, 0x19, 0x10, 0x9f, 0x96, 0x9d, 0x94,
0x1a, 0x13, 0x18, 0x11, 0x9e, 0x97, 0x9c, 0x95,
0x59, 0x50, 0x5b, 0x52, 0xdd, 0xd4, 0xdf, 0xd6,
0x58, 0x51, 0x5a, 0x53, 0xdc, 0xd5, 0xde, 0xd7,
0x1b, 0x12, 0x19, 0x10, 0x9f, 0x96, 0x9d, 0x94,
0x1a, 0x13, 0x18, 0x11, 0x9e, 0x97, 0x9c, 0x95,
0x59, 0x50, 0x5b, 0x52, 0xdd, 0xd4, 0xdf, 0xd6,
0x58, 0x51, 0x5a, 0x53, 0xdc, 0xd5, 0xde, 0xd7,
0x3a, 0x33, 0x38, 0x31, 0xbe, 0xb7, 0xbc, 0xb5,
0x3b, 0x32, 0x39, 0x30, 0xbf, 0xb6, 0xbd, 0xb4,
0x78, 0x71, 0x7a, 0x73, 0xfc, 0xf5, 0xfe, 0xf7,
0x79, 0x70, 0x7b, 0x72, 0xfd, 0xf4, 0xff, 0xf6,
0x3a, 0x33, 0x38, 0x31, 0xbe, 0xb7, 0xbc, 0xb5,
0x3b, 0x32, 0x39, 0x30, 0xbf, 0xb6, 0xbd, 0xb4,
0x78, 0x71, 0x7a, 0x73, 0xfc, 0xf5, 0xfe, 0xf7,
0x79, 0x70, 0x7b, 0x72, 0xfd, 0xf4, 0xff, 0xf6,
0x04, 0x0d, 0x06, 0x0f, 0x80, 0x89, 0x82, 0x8b,
0x05, 0x0c, 0x07, 0x0e, 0x81, 0x88, 0x83, 0x8a,
0x46, 0x4f, 0x44, 0x4d, 0xc2, 0xcb, 0xc0, 0xc9,
0x47, 0x4e, 0x45, 0x4c, 0xc3, 0xca, 0xc1, 0xc8,
0x04, 0x0d, 0x06, 0x0f, 0x80, 0x89, 0x82, 0x8b,
0x05, 0x0c, 0x07, 0x0e, 0x81, 0x88, 0x83, 0x8a,
0x46, 0x4f, 0x44, 0x4d, 0xc2, 0xcb, 0xc0, 0xc9,
0x47, 0x4e, 0x45, 0x4c, 0xc3, 0xca, 0xc1, 0xc8,
0x25, 0x2c, 0x27, 0x2e, 0xa1, 0xa8, 0xa3, 0xaa,
0x24, 0x2d, 0x26, 0x2f, 0xa0, 0xa9, 0xa2, 0xab,
0x67, 0x6e, 0x65, 0x6c, 0xe3, 0xea, 0xe1, 0xe8,
0x66, 0x6f, 0x64, 0x6d, 0xe2, 0xeb, 0xe0, 0xe9,
0x25, 0x2c, 0x27, 0x2e, 0xa1, 0xa8, 0xa3, 0xaa,
0x24, 0x2d, 0x26, 0x2f, 0xa0, 0xa9, 0xa2, 0xab,
0x67, 0x6e, 0x65, 0x6c, 0xe3, 0xea, 0xe1, 0xe8,
0x66, 0x6f, 0x64, 0x6d, 0xe2, 0xeb, 0xe0, 0xe9,
0x0d, 0x04, 0x0f, 0x06, 0x89, 0x80, 0x8b, 0x82,
0x0c, 0x05, 0x0e, 0x07, 0x88, 0x81, 0x8a, 0x83,
0x4f, 0x46, 0x4d, 0x44, 0xcb, 0xc2, 0xc9, 0xc0,
0x4e, 0x47, 0x4c, 0x45, 0xca, 0xc3, 0xc8, 0xc1,
0x0d, 0x04, 0x0f, 0x06, 0x89, 0x80, 0x8b, 0x82,
0x0c, 0x05, 0x0e, 0x07, 0x88, 0x81, 0x8a, 0x83,
0x4f, 0x46, 0x4d, 0x44, 0xcb, 0xc2, 0xc9, 0xc0,
0x4e, 0x47, 0x4c, 0x45, 0xca, 0xc3, 0xc8, 0xc1,
0x2c, 0x25, 0x2e, 0x27, 0xa8, 0xa1, 0xaa, 0xa3,
0x2d, 0x24, 0x2f, 0x26, 0xa9, 0xa0, 0xab, 0xa2,
0x6e, 0x67, 0x6c, 0x65, 0xea, 0xe3, 0xe8, 0xe1,
0x6f, 0x66, 0x6d, 0x64, 0xeb, 0xe2, 0xe9, 0xe0,
0x2c, 0x25, 0x2e, 0x27, 0xa8, 0xa1, 0xaa, 0xa3,
0x2d, 0x24, 0x2f, 0x26, 0xa9, 0xa0, 0xab, 0xa2,
0x6e, 0x67, 0x6c, 0x65, 0xea, 0xe3, 0xe8, 0xe1,
0x6f, 0x66, 0x6d, 0x64, 0xeb, 0xe2, 0xe9, 0xe0,
0x16, 0x1f, 0x14, 0x1d, 0x92, 0x9b, 0x90, 0x99,
0x17, 0x1e, 0x15, 0x1c, 0x93, 0x9a, 0x91, 0x98,
0x54, 0x5d, 0x56, 0x5f, 0xd0, 0xd9, 0xd2, 0xdb,
0x55, 0x5c, 0x57, 0x5e, 0xd1, 0xd8, 0xd3, 0xda,
0x16, 0x1f, 0x14, 0x1d, 0x92, 0x9b, 0x90, 0x99,
0x17, 0x1e, 0x15, 0x1c, 0x93, 0x9a, 0x91, 0x98,
0x54, 0x5d, 0x56, 0x5f, 0xd0, 0xd9, 0xd2, 0xdb,
0x55, 0x5c, 0x57, 0x5e, 0xd1, 0xd8, 0xd3, 0xda,
0x37, 0x3e, 0x35, 0x3c, 0xb3, 0xba, 0xb1, 0xb8,
0x36, 0x3f, 0x34, 0x3d, 0xb2, 0xbb, 0xb0, 0xb9,
0x75, 0x7c, 0x77, 0x7e, 0xf1, 0xf8, 0xf3, 0xfa,
0x74, 0x7d, 0x76, 0x7f, 0xf0, 0xf9, 0xf2, 0xfb,
0x37, 0x3e, 0x35, 0x3c, 0xb3, 0xba, 0xb1, 0xb8,
0x36, 0x3f, 0x34, 0x3d, 0xb2, 0xbb, 0xb0, 0xb9,
0x75, 0x7c, 0x77, 0x7e, 0xf1, 0xf8, 0xf3, 0xfa,
0x74, 0x7d, 0x76, 0x7f, 0xf0, 0xf9, 0xf2, 0xfb,
0x1f, 0x16, 0x1d, 0x14, 0x9b, 0x92, 0x99, 0x90,
0x1e, 0x17, 0x1c, 0x15, 0x9a, 0x93, 0x98, 0x91,
0x5d, 0x54, 0x5f, 0x56, 0xd9, 0xd0, 0xdb, 0xd2,
0x5c, 0x55, 0x5e, 0x57, 0xd8, 0xd1, 0xda, 0xd3,
0x1f, 0x16, 0x1d, 0x14, 0x9b, 0x92, 0x99, 0x90,
0x1e, 0x17, 0x1c, 0x15, 0x9a, 0x93, 0x98, 0x91,
0x5d, 0x54, 0x5f, 0x56, 0xd9, 0xd0, 0xdb, 0xd2,
0x5c, 0x55, 0x5e, 0x57, 0xd8, 0xd1, 0xda, 0xd3,
0x3e, 0x37, 0x3c, 0x35, 0xba, 0xb3, 0xb8, 0xb1,
0x3f, 0x36, 0x3d, 0x34, 0xbb, 0xb2, 0xb9, 0xb0,
0x7c, 0x75, 0x7e, 0x77, 0xf8, 0xf1, 0xfa, 0xf3,
0x7d, 0x74, 0x7f, 0x76, 0xf9, 0xf0, 0xfb, 0xf2,
0x3e, 0x37, 0x3c, 0x35, 0xba, 0xb3, 0xb8, 0xb1,
0x3f, 0x36, 0x3d, 0x34, 0xbb, 0xb2, 0xb9, 0xb0,
0x7c, 0x75, 0x7e, 0x77, 0xf8, 0xf1, 0xfa, 0xf3,
0x7d, 0x74, 0x7f, 0x76, 0xf9, 0xf0, 0xfb, 0xf2
};
unsigned char g_ucSyndromeF3Lookup[1024] =
{
0x00, 0x87, 0x21, 0xa6, 0x8f, 0x08, 0xae, 0x29,
0x43, 0xc4, 0x62, 0xe5, 0xcc, 0x4b, 0xed, 0x6a,
0x10, 0x97, 0x31, 0xb6, 0x9f, 0x18, 0xbe, 0x39,
0x53, 0xd4, 0x72, 0xf5, 0xdc, 0x5b, 0xfd, 0x7a,
0xc7, 0x40, 0xe6, 0x61, 0x48, 0xcf, 0x69, 0xee,
0x84, 0x03, 0xa5, 0x22, 0x0b, 0x8c, 0x2a, 0xad,
0xd7, 0x50, 0xf6, 0x71, 0x58, 0xdf, 0x79, 0xfe,
0x94, 0x13, 0xb5, 0x32, 0x1b, 0x9c, 0x3a, 0xbd,
0x21, 0xa6, 0x00, 0x87, 0xae, 0x29, 0x8f, 0x08,
0x62, 0xe5, 0x43, 0xc4, 0xed, 0x6a, 0xcc, 0x4b,
0x31, 0xb6, 0x10, 0x97, 0xbe, 0x39, 0x9f, 0x18,
0x72, 0xf5, 0x53, 0xd4, 0xfd, 0x7a, 0xdc, 0x5b,
0xe6, 0x61, 0xc7, 0x40, 0x69, 0xee, 0x48, 0xcf,
0xa5, 0x22, 0x84, 0x03, 0x2a, 0xad, 0x0b, 0x8c,
0xf6, 0x71, 0xd7, 0x50, 0x79, 0xfe, 0x58, 0xdf,
0xb5, 0x32, 0x94, 0x13, 0x3a, 0xbd, 0x1b, 0x9c,
0x0f, 0x88, 0x2e, 0xa9, 0x80, 0x07, 0xa1, 0x26,
0x4c, 0xcb, 0x6d, 0xea, 0xc3, 0x44, 0xe2, 0x65,
0x1f, 0x98, 0x3e, 0xb9, 0x90, 0x17, 0xb1, 0x36,
0x5c, 0xdb, 0x7d, 0xfa, 0xd3, 0x54, 0xf2, 0x75,
0xc8, 0x4f, 0xe9, 0x6e, 0x47, 0xc0, 0x66, 0xe1,
0x8b, 0x0c, 0xaa, 0x2d, 0x04, 0x83, 0x25, 0xa2,
0xd8, 0x5f, 0xf9, 0x7e, 0x57, 0xd0, 0x76, 0xf1,
0x9b, 0x1c, 0xba, 0x3d, 0x14, 0x93, 0x35, 0xb2,
0x2e, 0xa9, 0x0f, 0x88, 0xa1, 0x26, 0x80, 0x07,
0x6d, 0xea, 0x4c, 0xcb, 0xe2, 0x65, 0xc3, 0x44,
0x3e, 0xb9, 0x1f, 0x98, 0xb1, 0x36, 0x90, 0x17,
0x7d, 0xfa, 0x5c, 0xdb, 0xf2, 0x75, 0xd3, 0x54,
0xe9, 0x6e, 0xc8, 0x4f, 0x66, 0xe1, 0x47, 0xc0,
0xaa, 0x2d, 0x8b, 0x0c, 0x25, 0xa2, 0x04, 0x83,
0xf9, 0x7e, 0xd8, 0x5f, 0x76, 0xf1, 0x57, 0xd0,
0xba, 0x3d, 0x9b, 0x1c, 0x35, 0xb2, 0x14, 0x93,
0x42, 0xc5, 0x63, 0xe4, 0xcd, 0x4a, 0xec, 0x6b,
0x01, 0x86, 0x20, 0xa7, 0x8e, 0x09, 0xaf, 0x28,
0x52, 0xd5, 0x73, 0xf4, 0xdd, 0x5a, 0xfc, 0x7b,
0x11, 0x96, 0x30, 0xb7, 0x9e, 0x19, 0xbf, 0x38,
0x85, 0x02, 0xa4, 0x23, 0x0a, 0x8d, 0x2b, 0xac,
0xc6, 0x41, 0xe7, 0x60, 0x49, 0xce, 0x68, 0xef,
0x95, 0x12, 0xb4, 0x33, 0x1a, 0x9d, 0x3b, 0xbc,
0xd6, 0x51, 0xf7, 0x70, 0x59, 0xde, 0x78, 0xff,
0x63, 0xe4, 0x42, 0xc5, 0xec, 0x6b, 0xcd, 0x4a,
0x20, 0xa7, 0x01, 0x86, 0xaf, 0x28, 0x8e, 0x09,
0x73, 0xf4, 0x52, 0xd5, 0xfc, 0x7b, 0xdd, 0x5a,
0x30, 0xb7, 0x11, 0x96, 0xbf, 0x38, 0x9e, 0x19,
0xa4, 0x23, 0x85, 0x02, 0x2b, 0xac, 0x0a, 0x8d,
0xe7, 0x60, 0xc6, 0x41, 0x68, 0xef, 0x49, 0xce,
0xb4, 0x33, 0x95, 0x12, 0x3b, 0xbc, 0x1a, 0x9d,
0xf7, 0x70, 0xd6, 0x51, 0x78, 0xff, 0x59, 0xde,
0x4d, 0xca, 0x6c, 0xeb, 0xc2, 0x45, 0xe3, 0x64,
0x0e, 0x89, 0x2f, 0xa8, 0x81, 0x06, 0xa0, 0x27,
0x5d, 0xda, 0x7c, 0xfb, 0xd2, 0x55, 0xf3, 0x74,
0x1e, 0x99, 0x3f, 0xb8, 0x91, 0x16, 0xb0, 0x37,
0x8a, 0x0d, 0xab, 0x2c, 0x05, 0x82, 0x24, 0xa3,
0xc9, 0x4e, 0xe8, 0x6f, 0x46, 0xc1, 0x67, 0xe0,
0x9a, 0x1d, 0xbb, 0x3c, 0x15, 0x92, 0x34, 0xb3,
0xd9, 0x5e, 0xf8, 0x7f, 0x56, 0xd1, 0x77, 0xf0,
0x6c, 0xeb, 0x4d, 0xca, 0xe3, 0x64, 0xc2, 0x45,
0x2f, 0xa8, 0x0e, 0x89, 0xa0, 0x27, 0x81, 0x06,
0x7c, 0xfb, 0x5d, 0xda, 0xf3, 0x74, 0xd2, 0x55,
0x3f, 0xb8, 0x1e, 0x99, 0xb0, 0x37, 0x91, 0x16,
0xab, 0x2c, 0x8a, 0x0d, 0x24, 0xa3, 0x05, 0x82,
0xe8, 0x6f, 0xc9, 0x4e, 0x67, 0xe0, 0x46, 0xc1,
0xbb, 0x3c, 0x9a, 0x1d, 0x34, 0xb3, 0x15, 0x92,
0xf8, 0x7f, 0xd9, 0x5e, 0x77, 0xf0, 0x56, 0xd1,
0x1f, 0x98, 0x3e, 0xb9, 0x90, 0x17, 0xb1, 0x36,
0x5c, 0xdb, 0x7d, 0xfa, 0xd3, 0x54, 0xf2, 0x75,
0x0f, 0x88, 0x2e, 0xa9, 0x80, 0x07, 0xa1, 0x26,
0x4c, 0xcb, 0x6d, 0xea, 0xc3, 0x44, 0xe2, 0x65,
0xd8, 0x5f, 0xf9, 0x7e, 0x57, 0xd0, 0x76, 0xf1,
0x9b, 0x1c, 0xba, 0x3d, 0x14, 0x93, 0x35, 0xb2,
0xc8, 0x4f, 0xe9, 0x6e, 0x47, 0xc0, 0x66, 0xe1,
0x8b, 0x0c, 0xaa, 0x2d, 0x04, 0x83, 0x25, 0xa2,
0x3e, 0xb9, 0x1f, 0x98, 0xb1, 0x36, 0x90, 0x17,
0x7d, 0xfa, 0x5c, 0xdb, 0xf2, 0x75, 0xd3, 0x54,
0x2e, 0xa9, 0x0f, 0x88, 0xa1, 0x26, 0x80, 0x07,
0x6d, 0xea, 0x4c, 0xcb, 0xe2, 0x65, 0xc3, 0x44,
0xf9, 0x7e, 0xd8, 0x5f, 0x76, 0xf1, 0x57, 0xd0,
0xba, 0x3d, 0x9b, 0x1c, 0x35, 0xb2, 0x14, 0x93,
0xe9, 0x6e, 0xc8, 0x4f, 0x66, 0xe1, 0x47, 0xc0,
0xaa, 0x2d, 0x8b, 0x0c, 0x25, 0xa2, 0x04, 0x83,
0x10, 0x97, 0x31, 0xb6, 0x9f, 0x18, 0xbe, 0x39,
0x53, 0xd4, 0x72, 0xf5, 0xdc, 0x5b, 0xfd, 0x7a,
0x00, 0x87, 0x21, 0xa6, 0x8f, 0x08, 0xae, 0x29,
0x43, 0xc4, 0x62, 0xe5, 0xcc, 0x4b, 0xed, 0x6a,
0xd7, 0x50, 0xf6, 0x71, 0x58, 0xdf, 0x79, 0xfe,
0x94, 0x13, 0xb5, 0x32, 0x1b, 0x9c, 0x3a, 0xbd,
0xc7, 0x40, 0xe6, 0x61, 0x48, 0xcf, 0x69, 0xee,
0x84, 0x03, 0xa5, 0x22, 0x0b, 0x8c, 0x2a, 0xad,
0x31, 0xb6, 0x10, 0x97, 0xbe, 0x39, 0x9f, 0x18,
0x72, 0xf5, 0x53, 0xd4, 0xfd, 0x7a, 0xdc, 0x5b,
0x21, 0xa6, 0x00, 0x87, 0xae, 0x29, 0x8f, 0x08,
0x62, 0xe5, 0x43, 0xc4, 0xed, 0x6a, 0xcc, 0x4b,
0xf6, 0x71, 0xd7, 0x50, 0x79, 0xfe, 0x58, 0xdf,
0xb5, 0x32, 0x94, 0x13, 0x3a, 0xbd, 0x1b, 0x9c,
0xe6, 0x61, 0xc7, 0x40, 0x69, 0xee, 0x48, 0xcf,
0xa5, 0x22, 0x84, 0x03, 0x2a, 0xad, 0x0b, 0x8c,
0x5d, 0xda, 0x7c, 0xfb, 0xd2, 0x55, 0xf3, 0x74,
0x1e, 0x99, 0x3f, 0xb8, 0x91, 0x16, 0xb0, 0x37,
0x4d, 0xca, 0x6c, 0xeb, 0xc2, 0x45, 0xe3, 0x64,
0x0e, 0x89, 0x2f, 0xa8, 0x81, 0x06, 0xa0, 0x27,
0x9a, 0x1d, 0xbb, 0x3c, 0x15, 0x92, 0x34, 0xb3,
0xd9, 0x5e, 0xf8, 0x7f, 0x56, 0xd1, 0x77, 0xf0,
0x8a, 0x0d, 0xab, 0x2c, 0x05, 0x82, 0x24, 0xa3,
0xc9, 0x4e, 0xe8, 0x6f, 0x46, 0xc1, 0x67, 0xe0,
0x7c, 0xfb, 0x5d, 0xda, 0xf3, 0x74, 0xd2, 0x55,
0x3f, 0xb8, 0x1e, 0x99, 0xb0, 0x37, 0x91, 0x16,
0x6c, 0xeb, 0x4d, 0xca, 0xe3, 0x64, 0xc2, 0x45,
0x2f, 0xa8, 0x0e, 0x89, 0xa0, 0x27, 0x81, 0x06,
0xbb, 0x3c, 0x9a, 0x1d, 0x34, 0xb3, 0x15, 0x92,
0xf8, 0x7f, 0xd9, 0x5e, 0x77, 0xf0, 0x56, 0xd1,
0xab, 0x2c, 0x8a, 0x0d, 0x24, 0xa3, 0x05, 0x82,
0xe8, 0x6f, 0xc9, 0x4e, 0x67, 0xe0, 0x46, 0xc1,
0x52, 0xd5, 0x73, 0xf4, 0xdd, 0x5a, 0xfc, 0x7b,
0x11, 0x96, 0x30, 0xb7, 0x9e, 0x19, 0xbf, 0x38,
0x42, 0xc5, 0x63, 0xe4, 0xcd, 0x4a, 0xec, 0x6b,
0x01, 0x86, 0x20, 0xa7, 0x8e, 0x09, 0xaf, 0x28,
0x95, 0x12, 0xb4, 0x33, 0x1a, 0x9d, 0x3b, 0xbc,
0xd6, 0x51, 0xf7, 0x70, 0x59, 0xde, 0x78, 0xff,
0x85, 0x02, 0xa4, 0x23, 0x0a, 0x8d, 0x2b, 0xac,
0xc6, 0x41, 0xe7, 0x60, 0x49, 0xce, 0x68, 0xef,
0x73, 0xf4, 0x52, 0xd5, 0xfc, 0x7b, 0xdd, 0x5a,
0x30, 0xb7, 0x11, 0x96, 0xbf, 0x38, 0x9e, 0x19,
0x63, 0xe4, 0x42, 0xc5, 0xec, 0x6b, 0xcd, 0x4a,
0x20, 0xa7, 0x01, 0x86, 0xaf, 0x28, 0x8e, 0x09,
0xb4, 0x33, 0x95, 0x12, 0x3b, 0xbc, 0x1a, 0x9d,
0xf7, 0x70, 0xd6, 0x51, 0x78, 0xff, 0x59, 0xde,
0xa4, 0x23, 0x85, 0x02, 0x2b, 0xac, 0x0a, 0x8d,
0xe7, 0x60, 0xc6, 0x41, 0x68, 0xef, 0x49, 0xce
};
unsigned char g_ucSyndromeF4Lookup[1024] =
{
0x00, 0x02, 0x09, 0x0b, 0x84, 0x86, 0x8d, 0x8f,
0x23, 0x21, 0x2a, 0x28, 0xa7, 0xa5, 0xae, 0xac,
0x01, 0x03, 0x08, 0x0a, 0x85, 0x87, 0x8c, 0x8e,
0x22, 0x20, 0x2b, 0x29, 0xa6, 0xa4, 0xaf, 0xad,
0x84, 0x86, 0x8d, 0x8f, 0x00, 0x02, 0x09, 0x0b,
0xa7, 0xa5, 0xae, 0xac, 0x23, 0x21, 0x2a, 0x28,
0x85, 0x87, 0x8c, 0x8e, 0x01, 0x03, 0x08, 0x0a,
0xa6, 0xa4, 0xaf, 0xad, 0x22, 0x20, 0x2b, 0x29,
0x42, 0x40, 0x4b, 0x49, 0xc6, 0xc4, 0xcf, 0xcd,
0x61, 0x63, 0x68, 0x6a, 0xe5, 0xe7, 0xec, 0xee,
0x43, 0x41, 0x4a, 0x48, 0xc7, 0xc5, 0xce, 0xcc,
0x60, 0x62, 0x69, 0x6b, 0xe4, 0xe6, 0xed, 0xef,
0xc6, 0xc4, 0xcf, 0xcd, 0x42, 0x40, 0x4b, 0x49,
0xe5, 0xe7, 0xec, 0xee, 0x61, 0x63, 0x68, 0x6a,
0xc7, 0xc5, 0xce, 0xcc, 0x43, 0x41, 0x4a, 0x48,
0xe4, 0xe6, 0xed, 0xef, 0x60, 0x62, 0x69, 0x6b,
0x13, 0x11, 0x1a, 0x18, 0x97, 0x95, 0x9e, 0x9c,
0x30, 0x32, 0x39, 0x3b, 0xb4, 0xb6, 0xbd, 0xbf,
0x12, 0x10, 0x1b, 0x19, 0x96, 0x94, 0x9f, 0x9d,
0x31, 0x33, 0x38, 0x3a, 0xb5, 0xb7, 0xbc, 0xbe,
0x97, 0x95, 0x9e, 0x9c, 0x13, 0x11, 0x1a, 0x18,
0xb4, 0xb6, 0xbd, 0xbf, 0x30, 0x32, 0x39, 0x3b,
0x96, 0x94, 0x9f, 0x9d, 0x12, 0x10, 0x1b, 0x19,
0xb5, 0xb7, 0xbc, 0xbe, 0x31, 0x33, 0x38, 0x3a,
0x51, 0x53, 0x58, 0x5a, 0xd5, 0xd7, 0xdc, 0xde,
0x72, 0x70, 0x7b, 0x79, 0xf6, 0xf4, 0xff, 0xfd,
0x50, 0x52, 0x59, 0x5b, 0xd4, 0xd6, 0xdd, 0xdf,
0x73, 0x71, 0x7a, 0x78, 0xf7, 0xf5, 0xfe, 0xfc,
0xd5, 0xd7, 0xdc, 0xde, 0x51, 0x53, 0x58, 0x5a,
0xf6, 0xf4, 0xff, 0xfd, 0x72, 0x70, 0x7b, 0x79,
0xd4, 0xd6, 0xdd, 0xdf, 0x50, 0x52, 0x59, 0x5b,
0xf7, 0xf5, 0xfe, 0xfc, 0x73, 0x71, 0x7a, 0x78,
0x09, 0x0b, 0x00, 0x02, 0x8d, 0x8f, 0x84, 0x86,
0x2a, 0x28, 0x23, 0x21, 0xae, 0xac, 0xa7, 0xa5,
0x08, 0x0a, 0x01, 0x03, 0x8c, 0x8e, 0x85, 0x87,
0x2b, 0x29, 0x22, 0x20, 0xaf, 0xad, 0xa6, 0xa4,
0x8d, 0x8f, 0x84, 0x86, 0x09, 0x0b, 0x00, 0x02,
0xae, 0xac, 0xa7, 0xa5, 0x2a, 0x28, 0x23, 0x21,
0x8c, 0x8e, 0x85, 0x87, 0x08, 0x0a, 0x01, 0x03,
0xaf, 0xad, 0xa6, 0xa4, 0x2b, 0x29, 0x22, 0x20,
0x4b, 0x49, 0x42, 0x40, 0xcf, 0xcd, 0xc6, 0xc4,
0x68, 0x6a, 0x61, 0x63, 0xec, 0xee, 0xe5, 0xe7,
0x4a, 0x48, 0x43, 0x41, 0xce, 0xcc, 0xc7, 0xc5,
0x69, 0x6b, 0x60, 0x62, 0xed, 0xef, 0xe4, 0xe6,
0xcf, 0xcd, 0xc6, 0xc4, 0x4b, 0x49, 0x42, 0x40,
0xec, 0xee, 0xe5, 0xe7, 0x68, 0x6a, 0x61, 0x63,
0xce, 0xcc, 0xc7, 0xc5, 0x4a, 0x48, 0x43, 0x41,
0xed, 0xef, 0xe4, 0xe6, 0x69, 0x6b, 0x60, 0x62,
0x1a, 0x18, 0x13, 0x11, 0x9e, 0x9c, 0x97, 0x95,
0x39, 0x3b, 0x30, 0x32, 0xbd, 0xbf, 0xb4, 0xb6,
0x1b, 0x19, 0x12, 0x10, 0x9f, 0x9d, 0x96, 0x94,
0x38, 0x3a, 0x31, 0x33, 0xbc, 0xbe, 0xb5, 0xb7,
0x9e, 0x9c, 0x97, 0x95, 0x1a, 0x18, 0x13, 0x11,
0xbd, 0xbf, 0xb4, 0xb6, 0x39, 0x3b, 0x30, 0x32,
0x9f, 0x9d, 0x96, 0x94, 0x1b, 0x19, 0x12, 0x10,
0xbc, 0xbe, 0xb5, 0xb7, 0x38, 0x3a, 0x31, 0x33,
0x58, 0x5a, 0x51, 0x53, 0xdc, 0xde, 0xd5, 0xd7,
0x7b, 0x79, 0x72, 0x70, 0xff, 0xfd, 0xf6, 0xf4,
0x59, 0x5b, 0x50, 0x52, 0xdd, 0xdf, 0xd4, 0xd6,
0x7a, 0x78, 0x73, 0x71, 0xfe, 0xfc, 0xf7, 0xf5,
0xdc, 0xde, 0xd5, 0xd7, 0x58, 0x5a, 0x51, 0x53,
0xff, 0xfd, 0xf6, 0xf4, 0x7b, 0x79, 0x72, 0x70,
0xdd, 0xdf, 0xd4, 0xd6, 0x59, 0x5b, 0x50, 0x52,
0xfe, 0xfc, 0xf7, 0xf5, 0x7a, 0x78, 0x73, 0x71,
0x46, 0x44, 0x4f, 0x4d, 0xc2, 0xc0, 0xcb, 0xc9,
0x65, 0x67, 0x6c, 0x6e, 0xe1, 0xe3, 0xe8, 0xea,
0x47, 0x45, 0x4e, 0x4c, 0xc3, 0xc1, 0xca, 0xc8,
0x64, 0x66, 0x6d, 0x6f, 0xe0, 0xe2, 0xe9, 0xeb,
0xc2, 0xc0, 0xcb, 0xc9, 0x46, 0x44, 0x4f, 0x4d,
0xe1, 0xe3, 0xe8, 0xea, 0x65, 0x67, 0x6c, 0x6e,
0xc3, 0xc1, 0xca, 0xc8, 0x47, 0x45, 0x4e, 0x4c,
0xe0, 0xe2, 0xe9, 0xeb, 0x64, 0x66, 0x6d, 0x6f,
0x04, 0x06, 0x0d, 0x0f, 0x80, 0x82, 0x89, 0x8b,
0x27, 0x25, 0x2e, 0x2c, 0xa3, 0xa1, 0xaa, 0xa8,
0x05, 0x07, 0x0c, 0x0e, 0x81, 0x83, 0x88, 0x8a,
0x26, 0x24, 0x2f, 0x2d, 0xa2, 0xa0, 0xab, 0xa9,
0x80, 0x82, 0x89, 0x8b, 0x04, 0x06, 0x0d, 0x0f,
0xa3, 0xa1, 0xaa, 0xa8, 0x27, 0x25, 0x2e, 0x2c,
0x81, 0x83, 0x88, 0x8a, 0x05, 0x07, 0x0c, 0x0e,
0xa2, 0xa0, 0xab, 0xa9, 0x26, 0x24, 0x2f, 0x2d,
0x55, 0x57, 0x5c, 0x5e, 0xd1, 0xd3, 0xd8, 0xda,
0x76, 0x74, 0x7f, 0x7d, 0xf2, 0xf0, 0xfb, 0xf9,
0x54, 0x56, 0x5d, 0x5f, 0xd0, 0xd2, 0xd9, 0xdb,
0x77, 0x75, 0x7e, 0x7c, 0xf3, 0xf1, 0xfa, 0xf8,
0xd1, 0xd3, 0xd8, 0xda, 0x55, 0x57, 0x5c, 0x5e,
0xf2, 0xf0, 0xfb, 0xf9, 0x76, 0x74, 0x7f, 0x7d,
0xd0, 0xd2, 0xd9, 0xdb, 0x54, 0x56, 0x5d, 0x5f,
0xf3, 0xf1, 0xfa, 0xf8, 0x77, 0x75, 0x7e, 0x7c,
0x17, 0x15, 0x1e, 0x1c, 0x93, 0x91, 0x9a, 0x98,
0x34, 0x36, 0x3d, 0x3f, 0xb0, 0xb2, 0xb9, 0xbb,
0x16, 0x14, 0x1f, 0x1d, 0x92, 0x90, 0x9b, 0x99,
0x35, 0x37, 0x3c, 0x3e, 0xb1, 0xb3, 0xb8, 0xba,
0x93, 0x91, 0x9a, 0x98, 0x17, 0x15, 0x1e, 0x1c,
0xb0, 0xb2, 0xb9, 0xbb, 0x34, 0x36, 0x3d, 0x3f,
0x92, 0x90, 0x9b, 0x99, 0x16, 0x14, 0x1f, 0x1d,
0xb1, 0xb3, 0xb8, 0xba, 0x35, 0x37, 0x3c, 0x3e,
0x4f, 0x4d, 0x46, 0x44, 0xcb, 0xc9, 0xc2, 0xc0,
0x6c, 0x6e, 0x65, 0x67, 0xe8, 0xea, 0xe1, 0xe3,
0x4e, 0x4c, 0x47, 0x45, 0xca, 0xc8, 0xc3, 0xc1,
0x6d, 0x6f, 0x64, 0x66, 0xe9, 0xeb, 0xe0, 0xe2,
0xcb, 0xc9, 0xc2, 0xc0, 0x4f, 0x4d, 0x46, 0x44,
0xe8, 0xea, 0xe1, 0xe3, 0x6c, 0x6e, 0x65, 0x67,
0xca, 0xc8, 0xc3, 0xc1, 0x4e, 0x4c, 0x47, 0x45,
0xe9, 0xeb, 0xe0, 0xe2, 0x6d, 0x6f, 0x64, 0x66,
0x0d, 0x0f, 0x04, 0x06, 0x89, 0x8b, 0x80, 0x82,
0x2e, 0x2c, 0x27, 0x25, 0xaa, 0xa8, 0xa3, 0xa1,
0x0c, 0x0e, 0x05, 0x07, 0x88, 0x8a, 0x81, 0x83,
0x2f, 0x2d, 0x26, 0x24, 0xab, 0xa9, 0xa2, 0xa0,
0x89, 0x8b, 0x80, 0x82, 0x0d, 0x0f, 0x04, 0x06,
0xaa, 0xa8, 0xa3, 0xa1, 0x2e, 0x2c, 0x27, 0x25,
0x88, 0x8a, 0x81, 0x83, 0x0c, 0x0e, 0x05, 0x07,
0xab, 0xa9, 0xa2, 0xa0, 0x2f, 0x2d, 0x26, 0x24,
0x5c, 0x5e, 0x55, 0x57, 0xd8, 0xda, 0xd1, 0xd3,
0x7f, 0x7d, 0x76, 0x74, 0xfb, 0xf9, 0xf2, 0xf0,
0x5d, 0x5f, 0x54, 0x56, 0xd9, 0xdb, 0xd0, 0xd2,
0x7e, 0x7c, 0x77, 0x75, 0xfa, 0xf8, 0xf3, 0xf1,
0xd8, 0xda, 0xd1, 0xd3, 0x5c, 0x5e, 0x55, 0x57,
0xfb, 0xf9, 0xf2, 0xf0, 0x7f, 0x7d, 0x76, 0x74,
0xd9, 0xdb, 0xd0, 0xd2, 0x5d, 0x5f, 0x54, 0x56,
0xfa, 0xf8, 0xf3, 0xf1, 0x7e, 0x7c, 0x77, 0x75,
0x1e, 0x1c, 0x17, 0x15, 0x9a, 0x98, 0x93, 0x91,
0x3d, 0x3f, 0x34, 0x36, 0xb9, 0xbb, 0xb0, 0xb2,
0x1f, 0x1d, 0x16, 0x14, 0x9b, 0x99, 0x92, 0x90,
0x3c, 0x3e, 0x35, 0x37, 0xb8, 0xba, 0xb1, 0xb3,
0x9a, 0x98, 0x93, 0x91, 0x1e, 0x1c, 0x17, 0x15,
0xb9, 0xbb, 0xb0, 0xb2, 0x3d, 0x3f, 0x34, 0x36,
0x9b, 0x99, 0x92, 0x90, 0x1f, 0x1d, 0x16, 0x14,
0xb8, 0xba, 0xb1, 0xb3, 0x3c, 0x3e, 0x35, 0x37
};
unsigned char g_ucSyndromeF5Lookup[1024] =
{
0x00, 0xcd, 0x03, 0xce, 0x87, 0x4a, 0x84, 0x49,
0xfe, 0x33, 0xfd, 0x30, 0x79, 0xb4, 0x7a, 0xb7,
0x03, 0xce, 0x00, 0xcd, 0x84, 0x49, 0x87, 0x4a,
0xfd, 0x30, 0xfe, 0x33, 0x7a, 0xb7, 0x79, 0xb4,
0x66, 0xab, 0x65, 0xa8, 0xe1, 0x2c, 0xe2, 0x2f,
0x98, 0x55, 0x9b, 0x56, 0x1f, 0xd2, 0x1c, 0xd1,
0x65, 0xa8, 0x66, 0xab, 0xe2, 0x2f, 0xe1, 0x2c,
0x9b, 0x56, 0x98, 0x55, 0x1c, 0xd1, 0x1f, 0xd2,
0x01, 0xcc, 0x02, 0xcf, 0x86, 0x4b, 0x85, 0x48,
0xff, 0x32, 0xfc, 0x31, 0x78, 0xb5, 0x7b, 0xb6,
0x02, 0xcf, 0x01, 0xcc, 0x85, 0x48, 0x86, 0x4b,
0xfc, 0x31, 0xff, 0x32, 0x7b, 0xb6, 0x78, 0xb5,
0x67, 0xaa, 0x64, 0xa9, 0xe0, 0x2d, 0xe3, 0x2e,
0x99, 0x54, 0x9a, 0x57, 0x1e, 0xd3, 0x1d, 0xd0,
0x64, 0xa9, 0x67, 0xaa, 0xe3, 0x2e, 0xe0, 0x2d,
0x9a, 0x57, 0x99, 0x54, 0x1d, 0xd0, 0x1e, 0xd3,
0x0e, 0xc3, 0x0d, 0xc0, 0x89, 0x44, 0x8a, 0x47,
0xf0, 0x3d, 0xf3, 0x3e, 0x77, 0xba, 0x74, 0xb9,
0x0d, 0xc0, 0x0e, 0xc3, 0x8a, 0x47, 0x89, 0x44,
0xf3, 0x3e, 0xf0, 0x3d, 0x74, 0xb9, 0x77, 0xba,
0x68, 0xa5, 0x6b, 0xa6, 0xef, 0x22, 0xec, 0x21,
0x96, 0x5b, 0x95, 0x58, 0x11, 0xdc, 0x12, 0xdf,
0x6b, 0xa6, 0x68, 0xa5, 0xec, 0x21, 0xef, 0x22,
0x95, 0x58, 0x96, 0x5b, 0x12, 0xdf, 0x11, 0xdc,
0x0f, 0xc2, 0x0c, 0xc1, 0x88, 0x45, 0x8b, 0x46,
0xf1, 0x3c, 0xf2, 0x3f, 0x76, 0xbb, 0x75, 0xb8,
0x0c, 0xc1, 0x0f, 0xc2, 0x8b, 0x46, 0x88, 0x45,
0xf2, 0x3f, 0xf1, 0x3c, 0x75, 0xb8, 0x76, 0xbb,
0x69, 0xa4, 0x6a, 0xa7, 0xee, 0x23, 0xed, 0x20,
0x97, 0x5a, 0x94, 0x59, 0x10, 0xdd, 0x13, 0xde,
0x6a, 0xa7, 0x69, 0xa4, 0xed, 0x20, 0xee, 0x23,
0x94, 0x59, 0x97, 0x5a, 0x13, 0xde, 0x10, 0xdd,
0xfc, 0x31, 0xff, 0x32, 0x7b, 0xb6, 0x78, 0xb5,
0x02, 0xcf, 0x01, 0xcc, 0x85, 0x48, 0x86, 0x4b,
0xff, 0x32, 0xfc, 0x31, 0x78, 0xb5, 0x7b, 0xb6,
0x01, 0xcc, 0x02, 0xcf, 0x86, 0x4b, 0x85, 0x48,
0x9a, 0x57, 0x99, 0x54, 0x1d, 0xd0, 0x1e, 0xd3,
0x64, 0xa9, 0x67, 0xaa, 0xe3, 0x2e, 0xe0, 0x2d,
0x99, 0x54, 0x9a, 0x57, 0x1e, 0xd3, 0x1d, 0xd0,
0x67, 0xaa, 0x64, 0xa9, 0xe0, 0x2d, 0xe3, 0x2e,
0xfd, 0x30, 0xfe, 0x33, 0x7a, 0xb7, 0x79, 0xb4,
0x03, 0xce, 0x00, 0xcd, 0x84, 0x49, 0x87, 0x4a,
0xfe, 0x33, 0xfd, 0x30, 0x79, 0xb4, 0x7a, 0xb7,
0x00, 0xcd, 0x03, 0xce, 0x87, 0x4a, 0x84, 0x49,
0x9b, 0x56, 0x98, 0x55, 0x1c, 0xd1, 0x1f, 0xd2,
0x65, 0xa8, 0x66, 0xab, 0xe2, 0x2f, 0xe1, 0x2c,
0x98, 0x55, 0x9b, 0x56, 0x1f, 0xd2, 0x1c, 0xd1,
0x66, 0xab, 0x65, 0xa8, 0xe1, 0x2c, 0xe2, 0x2f,
0xf2, 0x3f, 0xf1, 0x3c, 0x75, 0xb8, 0x76, 0xbb,
0x0c, 0xc1, 0x0f, 0xc2, 0x8b, 0x46, 0x88, 0x45,
0xf1, 0x3c, 0xf2, 0x3f, 0x76, 0xbb, 0x75, 0xb8,
0x0f, 0xc2, 0x0c, 0xc1, 0x88, 0x45, 0x8b, 0x46,
0x94, 0x59, 0x97, 0x5a, 0x13, 0xde, 0x10, 0xdd,
0x6a, 0xa7, 0x69, 0xa4, 0xed, 0x20, 0xee, 0x23,
0x97, 0x5a, 0x94, 0x59, 0x10, 0xdd, 0x13, 0xde,
0x69, 0xa4, 0x6a, 0xa7, 0xee, 0x23, 0xed, 0x20,
0xf3, 0x3e, 0xf0, 0x3d, 0x74, 0xb9, 0x77, 0xba,
0x0d, 0xc0, 0x0e, 0xc3, 0x8a, 0x47, 0x89, 0x44,
0xf0, 0x3d, 0xf3, 0x3e, 0x77, 0xba, 0x74, 0xb9,
0x0e, 0xc3, 0x0d, 0xc0, 0x89, 0x44, 0x8a, 0x47,
0x95, 0x58, 0x96, 0x5b, 0x12, 0xdf, 0x11, 0xdc,
0x6b, 0xa6, 0x68, 0xa5, 0xec, 0x21, 0xef, 0x22,
0x96, 0x5b, 0x95, 0x58, 0x11, 0xdc, 0x12, 0xdf,
0x68, 0xa5, 0x6b, 0xa6, 0xef, 0x22, 0xec, 0x21,
0x06, 0xcb, 0x05, 0xc8, 0x81, 0x4c, 0x82, 0x4f,
0xf8, 0x35, 0xfb, 0x36, 0x7f, 0xb2, 0x7c, 0xb1,
0x05, 0xc8, 0x06, 0xcb, 0x82, 0x4f, 0x81, 0x4c,
0xfb, 0x36, 0xf8, 0x35, 0x7c, 0xb1, 0x7f, 0xb2,
0x60, 0xad, 0x63, 0xae, 0xe7, 0x2a, 0xe4, 0x29,
0x9e, 0x53, 0x9d, 0x50, 0x19, 0xd4, 0x1a, 0xd7,
0x63, 0xae, 0x60, 0xad, 0xe4, 0x29, 0xe7, 0x2a,
0x9d, 0x50, 0x9e, 0x53, 0x1a, 0xd7, 0x19, 0xd4,
0x07, 0xca, 0x04, 0xc9, 0x80, 0x4d, 0x83, 0x4e,
0xf9, 0x34, 0xfa, 0x37, 0x7e, 0xb3, 0x7d, 0xb0,
0x04, 0xc9, 0x07, 0xca, 0x83, 0x4e, 0x80, 0x4d,
0xfa, 0x37, 0xf9, 0x34, 0x7d, 0xb0, 0x7e, 0xb3,
0x61, 0xac, 0x62, 0xaf, 0xe6, 0x2b, 0xe5, 0x28,
0x9f, 0x52, 0x9c, 0x51, 0x18, 0xd5, 0x1b, 0xd6,
0x62, 0xaf, 0x61, 0xac, 0xe5, 0x28, 0xe6, 0x2b,
0x9c, 0x51, 0x9f, 0x52, 0x1b, 0xd6, 0x18, 0xd5,
0x08, 0xc5, 0x0b, 0xc6, 0x8f, 0x42, 0x8c, 0x41,
0xf6, 0x3b, 0xf5, 0x38, 0x71, 0xbc, 0x72, 0xbf,
0x0b, 0xc6, 0x08, 0xc5, 0x8c, 0x41, 0x8f, 0x42,
0xf5, 0x38, 0xf6, 0x3b, 0x72, 0xbf, 0x71, 0xbc,
0x6e, 0xa3, 0x6d, 0xa0, 0xe9, 0x24, 0xea, 0x27,
0x90, 0x5d, 0x93, 0x5e, 0x17, 0xda, 0x14, 0xd9,
0x6d, 0xa0, 0x6e, 0xa3, 0xea, 0x27, 0xe9, 0x24,
0x93, 0x5e, 0x90, 0x5d, 0x14, 0xd9, 0x17, 0xda,
0x09, 0xc4, 0x0a, 0xc7, 0x8e, 0x43, 0x8d, 0x40,
0xf7, 0x3a, 0xf4, 0x39, 0x70, 0xbd, 0x73, 0xbe,
0x0a, 0xc7, 0x09, 0xc4, 0x8d, 0x40, 0x8e, 0x43,
0xf4, 0x39, 0xf7, 0x3a, 0x73, 0xbe, 0x70, 0xbd,
0x6f, 0xa2, 0x6c, 0xa1, 0xe8, 0x25, 0xeb, 0x26,
0x91, 0x5c, 0x92, 0x5f, 0x16, 0xdb, 0x15, 0xd8,
0x6c, 0xa1, 0x6f, 0xa2, 0xeb, 0x26, 0xe8, 0x25,
0x92, 0x5f, 0x91, 0x5c, 0x15, 0xd8, 0x16, 0xdb,
0xfa, 0x37, 0xf9, 0x34, 0x7d, 0xb0, 0x7e, 0xb3,
0x04, 0xc9, 0x07, 0xca, 0x83, 0x4e, 0x80, 0x4d,
0xf9, 0x34, 0xfa, 0x37, 0x7e, 0xb3, 0x7d, 0xb0,
0x07, 0xca, 0x04, 0xc9, 0x80, 0x4d, 0x83, 0x4e,
0x9c, 0x51, 0x9f, 0x52, 0x1b, 0xd6, 0x18, 0xd5,
0x62, 0xaf, 0x61, 0xac, 0xe5, 0x28, 0xe6, 0x2b,
0x9f, 0x52, 0x9c, 0x51, 0x18, 0xd5, 0x1b, 0xd6,
0x61, 0xac, 0x62, 0xaf, 0xe6, 0x2b, 0xe5, 0x28,
0xfb, 0x36, 0xf8, 0x35, 0x7c, 0xb1, 0x7f, 0xb2,
0x05, 0xc8, 0x06, 0xcb, 0x82, 0x4f, 0x81, 0x4c,
0xf8, 0x35, 0xfb, 0x36, 0x7f, 0xb2, 0x7c, 0xb1,
0x06, 0xcb, 0x05, 0xc8, 0x81, 0x4c, 0x82, 0x4f,
0x9d, 0x50, 0x9e, 0x53, 0x1a, 0xd7, 0x19, 0xd4,
0x63, 0xae, 0x60, 0xad, 0xe4, 0x29, 0xe7, 0x2a,
0x9e, 0x53, 0x9d, 0x50, 0x19, 0xd4, 0x1a, 0xd7,
0x60, 0xad, 0x63, 0xae, 0xe7, 0x2a, 0xe4, 0x29,
0xf4, 0x39, 0xf7, 0x3a, 0x73, 0xbe, 0x70, 0xbd,
0x0a, 0xc7, 0x09, 0xc4, 0x8d, 0x40, 0x8e, 0x43,
0xf7, 0x3a, 0xf4, 0x39, 0x70, 0xbd, 0x73, 0xbe,
0x09, 0xc4, 0x0a, 0xc7, 0x8e, 0x43, 0x8d, 0x40,
0x92, 0x5f, 0x91, 0x5c, 0x15, 0xd8, 0x16, 0xdb,
0x6c, 0xa1, 0x6f, 0xa2, 0xeb, 0x26, 0xe8, 0x25,
0x91, 0x5c, 0x92, 0x5f, 0x16, 0xdb, 0x15, 0xd8,
0x6f, 0xa2, 0x6c, 0xa1, 0xe8, 0x25, 0xeb, 0x26,
0xf5, 0x38, 0xf6, 0x3b, 0x72, 0xbf, 0x71, 0xbc,
0x0b, 0xc6, 0x08, 0xc5, 0x8c, 0x41, 0x8f, 0x42,
0xf6, 0x3b, 0xf5, 0x38, 0x71, 0xbc, 0x72, 0xbf,
0x08, 0xc5, 0x0b, 0xc6, 0x8f, 0x42, 0x8c, 0x41,
0x93, 0x5e, 0x90, 0x5d, 0x14, 0xd9, 0x17, 0xda,
0x6d, 0xa0, 0x6e, 0xa3, 0xea, 0x27, 0xe9, 0x24,
0x90, 0x5d, 0x93, 0x5e, 0x17, 0xda, 0x14, 0xd9,
0x6e, 0xa3, 0x6d, 0xa0, 0xe9, 0x24, 0xea, 0x27
};
unsigned char g_ucSyndromeF6Lookup[1024] =
{
0x00, 0x21, 0x40, 0x61, 0x8f, 0xae, 0xcf, 0xee,
0x00, 0x21, 0x40, 0x61, 0x8f, 0xae, 0xcf, 0xee,
0x43, 0x62, 0x03, 0x22, 0xcc, 0xed, 0x8c, 0xad,
0x43, 0x62, 0x03, 0x22, 0xcc, 0xed, 0x8c, 0xad,
0x07, 0x26, 0x47, 0x66, 0x88, 0xa9, 0xc8, 0xe9,
0x07, 0x26, 0x47, 0x66, 0x88, 0xa9, 0xc8, 0xe9,
0x44, 0x65, 0x04, 0x25, 0xcb, 0xea, 0x8b, 0xaa,
0x44, 0x65, 0x04, 0x25, 0xcb, 0xea, 0x8b, 0xaa,
0x10, 0x31, 0x50, 0x71, 0x9f, 0xbe, 0xdf, 0xfe,
0x10, 0x31, 0x50, 0x71, 0x9f, 0xbe, 0xdf, 0xfe,
0x53, 0x72, 0x13, 0x32, 0xdc, 0xfd, 0x9c, 0xbd,
0x53, 0x72, 0x13, 0x32, 0xdc, 0xfd, 0x9c, 0xbd,
0x17, 0x36, 0x57, 0x76, 0x98, 0xb9, 0xd8, 0xf9,
0x17, 0x36, 0x57, 0x76, 0x98, 0xb9, 0xd8, 0xf9,
0x54, 0x75, 0x14, 0x35, 0xdb, 0xfa, 0x9b, 0xba,
0x54, 0x75, 0x14, 0x35, 0xdb, 0xfa, 0x9b, 0xba,
0x01, 0x20, 0x41, 0x60, 0x8e, 0xaf, 0xce, 0xef,
0x01, 0x20, 0x41, 0x60, 0x8e, 0xaf, 0xce, 0xef,
0x42, 0x63, 0x02, 0x23, 0xcd, 0xec, 0x8d, 0xac,
0x42, 0x63, 0x02, 0x23, 0xcd, 0xec, 0x8d, 0xac,
0x06, 0x27, 0x46, 0x67, 0x89, 0xa8, 0xc9, 0xe8,
0x06, 0x27, 0x46, 0x67, 0x89, 0xa8, 0xc9, 0xe8,
0x45, 0x64, 0x05, 0x24, 0xca, 0xeb, 0x8a, 0xab,
0x45, 0x64, 0x05, 0x24, 0xca, 0xeb, 0x8a, 0xab,
0x11, 0x30, 0x51, 0x70, 0x9e, 0xbf, 0xde, 0xff,
0x11, 0x30, 0x51, 0x70, 0x9e, 0xbf, 0xde, 0xff,
0x52, 0x73, 0x12, 0x33, 0xdd, 0xfc, 0x9d, 0xbc,
0x52, 0x73, 0x12, 0x33, 0xdd, 0xfc, 0x9d, 0xbc,
0x16, 0x37, 0x56, 0x77, 0x99, 0xb8, 0xd9, 0xf8,
0x16, 0x37, 0x56, 0x77, 0x99, 0xb8, 0xd9, 0xf8,
0x55, 0x74, 0x15, 0x34, 0xda, 0xfb, 0x9a, 0xbb,
0x55, 0x74, 0x15, 0x34, 0xda, 0xfb, 0x9a, 0xbb,
0x87, 0xa6, 0xc7, 0xe6, 0x08, 0x29, 0x48, 0x69,
0x87, 0xa6, 0xc7, 0xe6, 0x08, 0x29, 0x48, 0x69,
0xc4, 0xe5, 0x84, 0xa5, 0x4b, 0x6a, 0x0b, 0x2a,
0xc4, 0xe5, 0x84, 0xa5, 0x4b, 0x6a, 0x0b, 0x2a,
0x80, 0xa1, 0xc0, 0xe1, 0x0f, 0x2e, 0x4f, 0x6e,
0x80, 0xa1, 0xc0, 0xe1, 0x0f, 0x2e, 0x4f, 0x6e,
0xc3, 0xe2, 0x83, 0xa2, 0x4c, 0x6d, 0x0c, 0x2d,
0xc3, 0xe2, 0x83, 0xa2, 0x4c, 0x6d, 0x0c, 0x2d,
0x97, 0xb6, 0xd7, 0xf6, 0x18, 0x39, 0x58, 0x79,
0x97, 0xb6, 0xd7, 0xf6, 0x18, 0x39, 0x58, 0x79,
0xd4, 0xf5, 0x94, 0xb5, 0x5b, 0x7a, 0x1b, 0x3a,
0xd4, 0xf5, 0x94, 0xb5, 0x5b, 0x7a, 0x1b, 0x3a,
0x90, 0xb1, 0xd0, 0xf1, 0x1f, 0x3e, 0x5f, 0x7e,
0x90, 0xb1, 0xd0, 0xf1, 0x1f, 0x3e, 0x5f, 0x7e,
0xd3, 0xf2, 0x93, 0xb2, 0x5c, 0x7d, 0x1c, 0x3d,
0xd3, 0xf2, 0x93, 0xb2, 0x5c, 0x7d, 0x1c, 0x3d,
0x86, 0xa7, 0xc6, 0xe7, 0x09, 0x28, 0x49, 0x68,
0x86, 0xa7, 0xc6, 0xe7, 0x09, 0x28, 0x49, 0x68,
0xc5, 0xe4, 0x85, 0xa4, 0x4a, 0x6b, 0x0a, 0x2b,
0xc5, 0xe4, 0x85, 0xa4, 0x4a, 0x6b, 0x0a, 0x2b,
0x81, 0xa0, 0xc1, 0xe0, 0x0e, 0x2f, 0x4e, 0x6f,
0x81, 0xa0, 0xc1, 0xe0, 0x0e, 0x2f, 0x4e, 0x6f,
0xc2, 0xe3, 0x82, 0xa3, 0x4d, 0x6c, 0x0d, 0x2c,
0xc2, 0xe3, 0x82, 0xa3, 0x4d, 0x6c, 0x0d, 0x2c,
0x96, 0xb7, 0xd6, 0xf7, 0x19, 0x38, 0x59, 0x78,
0x96, 0xb7, 0xd6, 0xf7, 0x19, 0x38, 0x59, 0x78,
0xd5, 0xf4, 0x95, 0xb4, 0x5a, 0x7b, 0x1a, 0x3b,
0xd5, 0xf4, 0x95, 0xb4, 0x5a, 0x7b, 0x1a, 0x3b,
0x91, 0xb0, 0xd1, 0xf0, 0x1e, 0x3f, 0x5e, 0x7f,
0x91, 0xb0, 0xd1, 0xf0, 0x1e, 0x3f, 0x5e, 0x7f,
0xd2, 0xf3, 0x92, 0xb3, 0x5d, 0x7c, 0x1d, 0x3c,
0xd2, 0xf3, 0x92, 0xb3, 0x5d, 0x7c, 0x1d, 0x3c,
0x0f, 0x2e, 0x4f, 0x6e, 0x80, 0xa1, 0xc0, 0xe1,
0x0f, 0x2e, 0x4f, 0x6e, 0x80, 0xa1, 0xc0, 0xe1,
0x4c, 0x6d, 0x0c, 0x2d, 0xc3, 0xe2, 0x83, 0xa2,
0x4c, 0x6d, 0x0c, 0x2d, 0xc3, 0xe2, 0x83, 0xa2,
0x08, 0x29, 0x48, 0x69, 0x87, 0xa6, 0xc7, 0xe6,
0x08, 0x29, 0x48, 0x69, 0x87, 0xa6, 0xc7, 0xe6,
0x4b, 0x6a, 0x0b, 0x2a, 0xc4, 0xe5, 0x84, 0xa5,
0x4b, 0x6a, 0x0b, 0x2a, 0xc4, 0xe5, 0x84, 0xa5,
0x1f, 0x3e, 0x5f, 0x7e, 0x90, 0xb1, 0xd0, 0xf1,
0x1f, 0x3e, 0x5f, 0x7e, 0x90, 0xb1, 0xd0, 0xf1,
0x5c, 0x7d, 0x1c, 0x3d, 0xd3, 0xf2, 0x93, 0xb2,
0x5c, 0x7d, 0x1c, 0x3d, 0xd3, 0xf2, 0x93, 0xb2,
0x18, 0x39, 0x58, 0x79, 0x97, 0xb6, 0xd7, 0xf6,
0x18, 0x39, 0x58, 0x79, 0x97, 0xb6, 0xd7, 0xf6,
0x5b, 0x7a, 0x1b, 0x3a, 0xd4, 0xf5, 0x94, 0xb5,
0x5b, 0x7a, 0x1b, 0x3a, 0xd4, 0xf5, 0x94, 0xb5,
0x0e, 0x2f, 0x4e, 0x6f, 0x81, 0xa0, 0xc1, 0xe0,
0x0e, 0x2f, 0x4e, 0x6f, 0x81, 0xa0, 0xc1, 0xe0,
0x4d, 0x6c, 0x0d, 0x2c, 0xc2, 0xe3, 0x82, 0xa3,
0x4d, 0x6c, 0x0d, 0x2c, 0xc2, 0xe3, 0x82, 0xa3,
0x09, 0x28, 0x49, 0x68, 0x86, 0xa7, 0xc6, 0xe7,
0x09, 0x28, 0x49, 0x68, 0x86, 0xa7, 0xc6, 0xe7,
0x4a, 0x6b, 0x0a, 0x2b, 0xc5, 0xe4, 0x85, 0xa4,
0x4a, 0x6b, 0x0a, 0x2b, 0xc5, 0xe4, 0x85, 0xa4,
0x1e, 0x3f, 0x5e, 0x7f, 0x91, 0xb0, 0xd1, 0xf0,
0x1e, 0x3f, 0x5e, 0x7f, 0x91, 0xb0, 0xd1, 0xf0,
0x5d, 0x7c, 0x1d, 0x3c, 0xd2, 0xf3, 0x92, 0xb3,
0x5d, 0x7c, 0x1d, 0x3c, 0xd2, 0xf3, 0x92, 0xb3,
0x19, 0x38, 0x59, 0x78, 0x96, 0xb7, 0xd6, 0xf7,
0x19, 0x38, 0x59, 0x78, 0x96, 0xb7, 0xd6, 0xf7,
0x5a, 0x7b, 0x1a, 0x3b, 0xd5, 0xf4, 0x95, 0xb4,
0x5a, 0x7b, 0x1a, 0x3b, 0xd5, 0xf4, 0x95, 0xb4,
0x88, 0xa9, 0xc8, 0xe9, 0x07, 0x26, 0x47, 0x66,
0x88, 0xa9, 0xc8, 0xe9, 0x07, 0x26, 0x47, 0x66,
0xcb, 0xea, 0x8b, 0xaa, 0x44, 0x65, 0x04, 0x25,
0xcb, 0xea, 0x8b, 0xaa, 0x44, 0x65, 0x04, 0x25,
0x8f, 0xae, 0xcf, 0xee, 0x00, 0x21, 0x40, 0x61,
0x8f, 0xae, 0xcf, 0xee, 0x00, 0x21, 0x40, 0x61,
0xcc, 0xed, 0x8c, 0xad, 0x43, 0x62, 0x03, 0x22,
0xcc, 0xed, 0x8c, 0xad, 0x43, 0x62, 0x03, 0x22,
0x98, 0xb9, 0xd8, 0xf9, 0x17, 0x36, 0x57, 0x76,
0x98, 0xb9, 0xd8, 0xf9, 0x17, 0x36, 0x57, 0x76,
0xdb, 0xfa, 0x9b, 0xba, 0x54, 0x75, 0x14, 0x35,
0xdb, 0xfa, 0x9b, 0xba, 0x54, 0x75, 0x14, 0x35,
0x9f, 0xbe, 0xdf, 0xfe, 0x10, 0x31, 0x50, 0x71,
0x9f, 0xbe, 0xdf, 0xfe, 0x10, 0x31, 0x50, 0x71,
0xdc, 0xfd, 0x9c, 0xbd, 0x53, 0x72, 0x13, 0x32,
0xdc, 0xfd, 0x9c, 0xbd, 0x53, 0x72, 0x13, 0x32,
0x89, 0xa8, 0xc9, 0xe8, 0x06, 0x27, 0x46, 0x67,
0x89, 0xa8, 0xc9, 0xe8, 0x06, 0x27, 0x46, 0x67,
0xca, 0xeb, 0x8a, 0xab, 0x45, 0x64, 0x05, 0x24,
0xca, 0xeb, 0x8a, 0xab, 0x45, 0x64, 0x05, 0x24,
0x8e, 0xaf, 0xce, 0xef, 0x01, 0x20, 0x41, 0x60,
0x8e, 0xaf, 0xce, 0xef, 0x01, 0x20, 0x41, 0x60,
0xcd, 0xec, 0x8d, 0xac, 0x42, 0x63, 0x02, 0x23,
0xcd, 0xec, 0x8d, 0xac, 0x42, 0x63, 0x02, 0x23,
0x99, 0xb8, 0xd9, 0xf8, 0x16, 0x37, 0x56, 0x77,
0x99, 0xb8, 0xd9, 0xf8, 0x16, 0x37, 0x56, 0x77,
0xda, 0xfb, 0x9a, 0xbb, 0x55, 0x74, 0x15, 0x34,
0xda, 0xfb, 0x9a, 0xbb, 0x55, 0x74, 0x15, 0x34,
0x9e, 0xbf, 0xde, 0xff, 0x11, 0x30, 0x51, 0x70,
0x9e, 0xbf, 0xde, 0xff, 0x11, 0x30, 0x51, 0x70,
0xdd, 0xfc, 0x9d, 0xbc, 0x52, 0x73, 0x12, 0x33,
0xdd, 0xfc, 0x9d, 0xbc, 0x52, 0x73, 0x12, 0x33
};
unsigned char g_ucSyndromeF7Lookup[1024] =
{
0x00, 0xe7, 0x8f, 0x68, 0xf6, 0x11, 0x79, 0x9e,
0x45, 0xa2, 0xca, 0x2d, 0xb3, 0x54, 0x3c, 0xdb,
0x0a, 0xed, 0x85, 0x62, 0xfc, 0x1b, 0x73, 0x94,
0x4f, 0xa8, 0xc0, 0x27, 0xb9, 0x5e, 0x36, 0xd1,
0xa4, 0x43, 0x2b, 0xcc, 0x52, 0xb5, 0xdd, 0x3a,
0xe1, 0x06, 0x6e, 0x89, 0x17, 0xf0, 0x98, 0x7f,
0xae, 0x49, 0x21, 0xc6, 0x58, 0xbf, 0xd7, 0x30,
0xeb, 0x0c, 0x64, 0x83, 0x1d, 0xfa, 0x92, 0x75,
0x86, 0x61, 0x09, 0xee, 0x70, 0x97, 0xff, 0x18,
0xc3, 0x24, 0x4c, 0xab, 0x35, 0xd2, 0xba, 0x5d,
0x8c, 0x6b, 0x03, 0xe4, 0x7a, 0x9d, 0xf5, 0x12,
0xc9, 0x2e, 0x46, 0xa1, 0x3f, 0xd8, 0xb0, 0x57,
0x22, 0xc5, 0xad, 0x4a, 0xd4, 0x33, 0x5b, 0xbc,
0x67, 0x80, 0xe8, 0x0f, 0x91, 0x76, 0x1e, 0xf9,
0x28, 0xcf, 0xa7, 0x40, 0xde, 0x39, 0x51, 0xb6,
0x6d, 0x8a, 0xe2, 0x05, 0x9b, 0x7c, 0x14, 0xf3,
0x14, 0xf3, 0x9b, 0x7c, 0xe2, 0x05, 0x6d, 0x8a,
0x51, 0xb6, 0xde, 0x39, 0xa7, 0x40, 0x28, 0xcf,
0x1e, 0xf9, 0x91, 0x76, 0xe8, 0x0f, 0x67, 0x80,
0x5b, 0xbc, 0xd4, 0x33, 0xad, 0x4a, 0x22, 0xc5,
0xb0, 0x57, 0x3f, 0xd8, 0x46, 0xa1, 0xc9, 0x2e,
0xf5, 0x12, 0x7a, 0x9d, 0x03, 0xe4, 0x8c, 0x6b,
0xba, 0x5d, 0x35, 0xd2, 0x4c, 0xab, 0xc3, 0x24,
0xff, 0x18, 0x70, 0x97, 0x09, 0xee, 0x86, 0x61,
0x92, 0x75, 0x1d, 0xfa, 0x64, 0x83, 0xeb, 0x0c,
0xd7, 0x30, 0x58, 0xbf, 0x21, 0xc6, 0xae, 0x49,
0x98, 0x7f, 0x17, 0xf0, 0x6e, 0x89, 0xe1, 0x06,
0xdd, 0x3a, 0x52, 0xb5, 0x2b, 0xcc, 0xa4, 0x43,
0x36, 0xd1, 0xb9, 0x5e, 0xc0, 0x27, 0x4f, 0xa8,
0x73, 0x94, 0xfc, 0x1b, 0x85, 0x62, 0x0a, 0xed,
0x3c, 0xdb, 0xb3, 0x54, 0xca, 0x2d, 0x45, 0xa2,
0x79, 0x9e, 0xf6, 0x11, 0x8f, 0x68, 0x00, 0xe7,
0x48, 0xaf, 0xc7, 0x20, 0xbe, 0x59, 0x31, 0xd6,
0x0d, 0xea, 0x82, 0x65, 0xfb, 0x1c, 0x74, 0x93,
0x42, 0xa5, 0xcd, 0x2a, 0xb4, 0x53, 0x3b, 0xdc,
0x07, 0xe0, 0x88, 0x6f, 0xf1, 0x16, 0x7e, 0x99,
0xec, 0x0b, 0x63, 0x84, 0x1a, 0xfd, 0x95, 0x72,
0xa9, 0x4e, 0x26, 0xc1, 0x5f, 0xb8, 0xd0, 0x37,
0xe6, 0x01, 0x69, 0x8e, 0x10, 0xf7, 0x9f, 0x78,
0xa3, 0x44, 0x2c, 0xcb, 0x55, 0xb2, 0xda, 0x3d,
0xce, 0x29, 0x41, 0xa6, 0x38, 0xdf, 0xb7, 0x50,
0x8b, 0x6c, 0x04, 0xe3, 0x7d, 0x9a, 0xf2, 0x15,
0xc4, 0x23, 0x4b, 0xac, 0x32, 0xd5, 0xbd, 0x5a,
0x81, 0x66, 0x0e, 0xe9, 0x77, 0x90, 0xf8, 0x1f,
0x6a, 0x8d, 0xe5, 0x02, 0x9c, 0x7b, 0x13, 0xf4,
0x2f, 0xc8, 0xa0, 0x47, 0xd9, 0x3e, 0x56, 0xb1,
0x60, 0x87, 0xef, 0x08, 0x96, 0x71, 0x19, 0xfe,
0x25, 0xc2, 0xaa, 0x4d, 0xd3, 0x34, 0x5c, 0xbb,
0x5c, 0xbb, 0xd3, 0x34, 0xaa, 0x4d, 0x25, 0xc2,
0x19, 0xfe, 0x96, 0x71, 0xef, 0x08, 0x60, 0x87,
0x56, 0xb1, 0xd9, 0x3e, 0xa0, 0x47, 0x2f, 0xc8,
0x13, 0xf4, 0x9c, 0x7b, 0xe5, 0x02, 0x6a, 0x8d,
0xf8, 0x1f, 0x77, 0x90, 0x0e, 0xe9, 0x81, 0x66,
0xbd, 0x5a, 0x32, 0xd5, 0x4b, 0xac, 0xc4, 0x23,
0xf2, 0x15, 0x7d, 0x9a, 0x04, 0xe3, 0x8b, 0x6c,
0xb7, 0x50, 0x38, 0xdf, 0x41, 0xa6, 0xce, 0x29,
0xda, 0x3d, 0x55, 0xb2, 0x2c, 0xcb, 0xa3, 0x44,
0x9f, 0x78, 0x10, 0xf7, 0x69, 0x8e, 0xe6, 0x01,
0xd0, 0x37, 0x5f, 0xb8, 0x26, 0xc1, 0xa9, 0x4e,
0x95, 0x72, 0x1a, 0xfd, 0x63, 0x84, 0xec, 0x0b,
0x7e, 0x99, 0xf1, 0x16, 0x88, 0x6f, 0x07, 0xe0,
0x3b, 0xdc, 0xb4, 0x53, 0xcd, 0x2a, 0x42, 0xa5,
0x74, 0x93, 0xfb, 0x1c, 0x82, 0x65, 0x0d, 0xea,
0x31, 0xd6, 0xbe, 0x59, 0xc7, 0x20, 0x48, 0xaf,
0x0d, 0xea, 0x82, 0x65, 0xfb, 0x1c, 0x74, 0x93,
0x48, 0xaf, 0xc7, 0x20, 0xbe, 0x59, 0x31, 0xd6,
0x07, 0xe0, 0x88, 0x6f, 0xf1, 0x16, 0x7e, 0x99,
0x42, 0xa5, 0xcd, 0x2a, 0xb4, 0x53, 0x3b, 0xdc,
0xa9, 0x4e, 0x26, 0xc1, 0x5f, 0xb8, 0xd0, 0x37,
0xec, 0x0b, 0x63, 0x84, 0x1a, 0xfd, 0x95, 0x72,
0xa3, 0x44, 0x2c, 0xcb, 0x55, 0xb2, 0xda, 0x3d,
0xe6, 0x01, 0x69, 0x8e, 0x10, 0xf7, 0x9f, 0x78,
0x8b, 0x6c, 0x04, 0xe3, 0x7d, 0x9a, 0xf2, 0x15,
0xce, 0x29, 0x41, 0xa6, 0x38, 0xdf, 0xb7, 0x50,
0x81, 0x66, 0x0e, 0xe9, 0x77, 0x90, 0xf8, 0x1f,
0xc4, 0x23, 0x4b, 0xac, 0x32, 0xd5, 0xbd, 0x5a,
0x2f, 0xc8, 0xa0, 0x47, 0xd9, 0x3e, 0x56, 0xb1,
0x6a, 0x8d, 0xe5, 0x02, 0x9c, 0x7b, 0x13, 0xf4,
0x25, 0xc2, 0xaa, 0x4d, 0xd3, 0x34, 0x5c, 0xbb,
0x60, 0x87, 0xef, 0x08, 0x96, 0x71, 0x19, 0xfe,
0x19, 0xfe, 0x96, 0x71, 0xef, 0x08, 0x60, 0x87,
0x5c, 0xbb, 0xd3, 0x34, 0xaa, 0x4d, 0x25, 0xc2,
0x13, 0xf4, 0x9c, 0x7b, 0xe5, 0x02, 0x6a, 0x8d,
0x56, 0xb1, 0xd9, 0x3e, 0xa0, 0x47, 0x2f, 0xc8,
0xbd, 0x5a, 0x32, 0xd5, 0x4b, 0xac, 0xc4, 0x23,
0xf8, 0x1f, 0x77, 0x90, 0x0e, 0xe9, 0x81, 0x66,
0xb7, 0x50, 0x38, 0xdf, 0x41, 0xa6, 0xce, 0x29,
0xf2, 0x15, 0x7d, 0x9a, 0x04, 0xe3, 0x8b, 0x6c,
0x9f, 0x78, 0x10, 0xf7, 0x69, 0x8e, 0xe6, 0x01,
0xda, 0x3d, 0x55, 0xb2, 0x2c, 0xcb, 0xa3, 0x44,
0x95, 0x72, 0x1a, 0xfd, 0x63, 0x84, 0xec, 0x0b,
0xd0, 0x37, 0x5f, 0xb8, 0x26, 0xc1, 0xa9, 0x4e,
0x3b, 0xdc, 0xb4, 0x53, 0xcd, 0x2a, 0x42, 0xa5,
0x7e, 0x99, 0xf1, 0x16, 0x88, 0x6f, 0x07, 0xe0,
0x31, 0xd6, 0xbe, 0x59, 0xc7, 0x20, 0x48, 0xaf,
0x74, 0x93, 0xfb, 0x1c, 0x82, 0x65, 0x0d, 0xea,
0x45, 0xa2, 0xca, 0x2d, 0xb3, 0x54, 0x3c, 0xdb,
0x00, 0xe7, 0x8f, 0x68, 0xf6, 0x11, 0x79, 0x9e,
0x4f, 0xa8, 0xc0, 0x27, 0xb9, 0x5e, 0x36, 0xd1,
0x0a, 0xed, 0x85, 0x62, 0xfc, 0x1b, 0x73, 0x94,
0xe1, 0x06, 0x6e, 0x89, 0x17, 0xf0, 0x98, 0x7f,
0xa4, 0x43, 0x2b, 0xcc, 0x52, 0xb5, 0xdd, 0x3a,
0xeb, 0x0c, 0x64, 0x83, 0x1d, 0xfa, 0x92, 0x75,
0xae, 0x49, 0x21, 0xc6, 0x58, 0xbf, 0xd7, 0x30,
0xc3, 0x24, 0x4c, 0xab, 0x35, 0xd2, 0xba, 0x5d,
0x86, 0x61, 0x09, 0xee, 0x70, 0x97, 0xff, 0x18,
0xc9, 0x2e, 0x46, 0xa1, 0x3f, 0xd8, 0xb0, 0x57,
0x8c, 0x6b, 0x03, 0xe4, 0x7a, 0x9d, 0xf5, 0x12,
0x67, 0x80, 0xe8, 0x0f, 0x91, 0x76, 0x1e, 0xf9,
0x22, 0xc5, 0xad, 0x4a, 0xd4, 0x33, 0x5b, 0xbc,
0x6d, 0x8a, 0xe2, 0x05, 0x9b, 0x7c, 0x14, 0xf3,
0x28, 0xcf, 0xa7, 0x40, 0xde, 0x39, 0x51, 0xb6,
0x51, 0xb6, 0xde, 0x39, 0xa7, 0x40, 0x28, 0xcf,
0x14, 0xf3, 0x9b, 0x7c, 0xe2, 0x05, 0x6d, 0x8a,
0x5b, 0xbc, 0xd4, 0x33, 0xad, 0x4a, 0x22, 0xc5,
0x1e, 0xf9, 0x91, 0x76, 0xe8, 0x0f, 0x67, 0x80,
0xf5, 0x12, 0x7a, 0x9d, 0x03, 0xe4, 0x8c, 0x6b,
0xb0, 0x57, 0x3f, 0xd8, 0x46, 0xa1, 0xc9, 0x2e,
0xff, 0x18, 0x70, 0x97, 0x09, 0xee, 0x86, 0x61,
0xba, 0x5d, 0x35, 0xd2, 0x4c, 0xab, 0xc3, 0x24,
0xd7, 0x30, 0x58, 0xbf, 0x21, 0xc6, 0xae, 0x49,
0x92, 0x75, 0x1d, 0xfa, 0x64, 0x83, 0xeb, 0x0c,
0xdd, 0x3a, 0x52, 0xb5, 0x2b, 0xcc, 0xa4, 0x43,
0x98, 0x7f, 0x17, 0xf0, 0x6e, 0x89, 0xe1, 0x06,
0x73, 0x94, 0xfc, 0x1b, 0x85, 0x62, 0x0a, 0xed,
0x36, 0xd1, 0xb9, 0x5e, 0xc0, 0x27, 0x4f, 0xa8,
0x79, 0x9e, 0xf6, 0x11, 0x8f, 0x68, 0x00, 0xe7,
0x3c, 0xdb, 0xb3, 0x54, 0xca, 0x2d, 0x45, 0xa2
};
#endif<file_sep>/SIC_SECC/Src/NandDrv.c
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2008 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#include <stdlib.h>
#include <string.h>
#include "wbio.h"
#include "w55fa93_sic.h"
#include "wblib.h"
#include "fmi.h"
#include "gnand_global.h"
#include "w55fa93_gnand.h"
#include "w55fa93_reg.h"
#define OPT_SOFTWARE_WRITE_ECC
#define OPT_SOFTWARE_ECC
#define OPT_SOFTWARE_WRITE_2KNAND_ECC
#define OPT_SOFTWARE_2KNAND_ECC
#define OPT_BCH_PLUS_SECC_FOR_NAND512
#ifdef OPT_SW_WP
#define SW_WP_DELAY_LOOP 5000
#endif
#define DBG_PRINTF(...)
//#define DBG_PRINTF sysprintf
#define NAND_RESERVED_BLOCK 10
#define OPT_TWO_RB_PINS
#define OPT_FIRST_4BLOCKS_ECC4
BOOL volatile _fmi_bIsNandFirstAccess = TRUE;
extern BOOL volatile _fmi_bIsSMDataReady;
INT fmiSMCheckBootHeader(INT chipSel, FMI_SM_INFO_T *pSM);
static int _nand_init0 = 0, _nand_init1 = 0;
//UCHAR _fmi_ucSMBuffer[4096];
__align(4096) UCHAR _fmi_ucSMBuffer[4096];
UINT8 *_fmi_pSMBuffer;
/* functions */
INT fmiSMCheckRB(FMI_SM_INFO_T *pSM)
{
#if 0 // no timer in it
UINT32 ii;
for (ii=0; ii<100; ii++);
while(1)
{
if(pSM == pSM0)
{
if (inpw(REG_SMISR) & SMISR_RB0_IF)
{
while(! (inpw(REG_SMISR) & SMISR_RB0) );
outpw(REG_SMISR, SMISR_RB0_IF);
return 1;
}
}
else
{
if (inpw(REG_SMISR) & SMISR_RB1_IF)
{
while(! (inpw(REG_SMISR) & SMISR_RB1) );
outpw(REG_SMISR, SMISR_RB1_IF);
return 1;
}
}
}
return 0;
#else
unsigned int volatile tick;
tick = sysGetTicks(TIMER0);
while(1)
{
if(pSM == pSM0)
{
if (inpw(REG_SMISR) & SMISR_RB0_IF)
{
while(! (inpw(REG_SMISR) & SMISR_RB0) );
outpw(REG_SMISR, SMISR_RB0_IF);
return 1;
}
}
else
{
if (inpw(REG_SMISR) & SMISR_RB1_IF)
{
while(! (inpw(REG_SMISR) & SMISR_RB1) );
outpw(REG_SMISR, SMISR_RB1_IF);
return 1;
}
}
if ((sysGetTicks(TIMER0) - tick) > 1000)
break;
}
return 0;
#endif
}
// SM functions
INT fmiSM_Reset(FMI_SM_INFO_T *pSM)
{
#ifdef OPT_TWO_RB_PINS
UINT32 volatile i;
if(pSM == pSM0)
outpw(REG_SMISR, SMISR_RB0_IF);
else
outpw(REG_SMISR, SMISR_RB1_IF);
outpw(REG_SMCMD, 0xff);
for (i=100; i>0; i--);
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
#else
UINT32 volatile i;
outpw(REG_SMISR, SMISR_RB0_IF);
outpw(REG_SMCMD, 0xff);
for (i=100; i>0; i--);
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
#endif // OPT_TWO_RB_PINS
}
VOID fmiSM_Initial(FMI_SM_INFO_T *pSM)
{
if (pSM->nPageSize == NAND_PAGE_8KB)
{
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_8K); // psize:2048
#ifdef DEBUG
// printf("The Test NAND is 8KB page size\n");
#endif
}
else if (pSM->nPageSize == NAND_PAGE_4KB)
{
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_4K); // psize:2048
#ifdef DEBUG
// printf("The Test NAND is 4KB page size\n");
#endif
}
else if (pSM->nPageSize == NAND_PAGE_2KB)
{
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_2K); // psize:2048
#ifdef DEBUG
// printf("The Test NAND is 2KB page size\n");
#endif
}
else // pSM->nPageSize = NAND_PAGE_512B
{
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_512); // psize:512
#ifdef DEBUG
// printf("The Test NAND is 512B page size\n");
#endif
}
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_EN); // enable ECC
if (pSM->bIsCheckECC)
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_CHK); // enable ECC check
else
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_CHK); // disable ECC check
#ifdef _SIC_USE_INT_
if ((_nand_init0 == 0) && (_nand_init1 == 0))
outpw(REG_SMIER, SMIER_DMA_IE);
#endif //_SIC_USE_INT_
// set BCH_Tx and redundant area size
outpw(REG_SMREAREA_CTL, inpw(REG_SMREAREA_CTL) & ~SMRE_MECC); // Redundant area size
if (pSM->nPageSize == NAND_PAGE_8KB)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T12); // BCH_12 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 376); // Redundant area size
}
else if (pSM->nPageSize == NAND_PAGE_4KB)
{
if (pSM->bIsNandECC12 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T12); // BCH_12 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 216);; // Redundant area size
}
else if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 128); // Redundant area size
}
else
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 128); // Redundant area size
}
}
else if (pSM->nPageSize == NAND_PAGE_2KB)
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
else
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
else
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 16); // Redundant area size
}
}
INT fmiSM_ReadID(FMI_SM_INFO_T *pSM, NDISK_T *NDISK_info)
{
UINT32 tempID[5];
fmiSM_Reset(pSM);
outpw(REG_SMCMD, 0x90); // read ID command
outpw(REG_SMADDR, EOA_SM); // address 0x00
tempID[0] = inpw(REG_SMDATA);
tempID[1] = inpw(REG_SMDATA);
tempID[2] = inpw(REG_SMDATA);
tempID[3] = inpw(REG_SMDATA);
tempID[4] = inpw(REG_SMDATA);
NDISK_info->vendor_ID = tempID[0];
NDISK_info->device_ID = tempID[1];
if (tempID[0] == 0xC2)
pSM->bIsCheckECC = FALSE;
else
pSM->bIsCheckECC = TRUE;
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = FALSE;
pSM->bIsNandECC12 = FALSE;
pSM->bIsNandECC15 = FALSE;
switch (tempID[1])
{
/* page size 512B */
case 0x79: // 128M
pSM->uSectorPerFlash = 255744;
pSM->uBlockPerFlash = 8191;
pSM->uPagePerBlock = 32;
pSM->uSectorPerBlock = 32;
pSM->bIsMulticycle = TRUE;
pSM->nPageSize = NAND_PAGE_512B;
pSM->bIsNandECC4 = TRUE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nBlockPerZone = 8192; /* blocks per zone */
NDISK_info->nPagePerBlock = 32; /* pages per block */
NDISK_info->nLBPerZone = 8000; /* logical blocks per zone */
NDISK_info->nPageSize = 512;
break;
case 0x76: // 64M
case 0x5A: // 64M XtraROM
pSM->uSectorPerFlash = 127872;
pSM->uBlockPerFlash = 4095;
pSM->uPagePerBlock = 32;
pSM->uSectorPerBlock = 32;
pSM->bIsMulticycle = TRUE;
pSM->nPageSize = NAND_PAGE_512B;
pSM->bIsNandECC4 = TRUE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nBlockPerZone = 4096; /* blocks per zone */
NDISK_info->nPagePerBlock = 32; /* pages per block */
NDISK_info->nLBPerZone = 4000; /* logical blocks per zone */
NDISK_info->nPageSize = 512;
break;
case 0x75: // 32M
pSM->uSectorPerFlash = 63936;
pSM->uBlockPerFlash = 2047;
pSM->uPagePerBlock = 32;
pSM->uSectorPerBlock = 32;
pSM->bIsMulticycle = FALSE;
pSM->nPageSize = NAND_PAGE_512B;
pSM->bIsNandECC4 = TRUE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nBlockPerZone = 2048; /* blocks per zone */
NDISK_info->nPagePerBlock = 32; /* pages per block */
NDISK_info->nLBPerZone = 2000; /* logical blocks per zone */
NDISK_info->nPageSize = 512;
break;
case 0x73: // 16M
pSM->uSectorPerFlash = 31968; // max. sector no. = 999 * 32
pSM->uBlockPerFlash = 1023;
pSM->uPagePerBlock = 32;
pSM->uSectorPerBlock = 32;
pSM->bIsMulticycle = FALSE;
pSM->nPageSize = NAND_PAGE_512B;
pSM->bIsNandECC4 = TRUE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nBlockPerZone = 1024; /* blocks per zone */
NDISK_info->nPagePerBlock = 32; /* pages per block */
NDISK_info->nLBPerZone = 1000; /* logical blocks per zone */
NDISK_info->nPageSize = 512;
break;
/* page size 2KB */
case 0xf1: // 128M
case 0xd1: // 128M
pSM->uBlockPerFlash = 1023;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 256;
pSM->uSectorPerFlash = 255744;
pSM->bIsMulticycle = FALSE;
pSM->nPageSize = NAND_PAGE_2KB;
pSM->bIsNandECC4 = TRUE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nBlockPerZone = 1024; /* blocks per zone */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nLBPerZone = 1000; /* logical blocks per zone */
NDISK_info->nPageSize = 2048;
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
// pSM->bIsNandECC4 = TRUE; //(IBR uses ECC4)
// pSM->bIsNandECC8 = FALSE;
break;
case 0xda: // 256M
if ((tempID[3] & 0x33) == 0x11)
{
pSM->uBlockPerFlash = 2047;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 256;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nBlockPerZone = 2048; /* blocks per zone */
NDISK_info->nLBPerZone = 2000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x21)
{
pSM->uBlockPerFlash = 1023;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 512;
pSM->bIsMLCNand = TRUE;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nBlockPerZone = 1024; /* blocks per zone */
NDISK_info->nLBPerZone = 1000; /* logical blocks per zone */
}
if ((tempID[3] & 0x0C) == 0x04)
pSM->bIsNandECC4 = TRUE;
else if ((tempID[3] & 0x0C) == 0x08)
pSM->bIsNandECC4 = FALSE;
pSM->uSectorPerFlash = 511488;
pSM->bIsMulticycle = TRUE;
pSM->nPageSize = NAND_PAGE_2KB;
NDISK_info->nPageSize = 2048;
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
break;
case 0xdc: // 512M
if ((tempID[3] & 0x33) == 0x11)
{
pSM->uBlockPerFlash = 4095;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 256;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nBlockPerZone = 4096; /* blocks per zone */
NDISK_info->nLBPerZone = 4000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x21)
{
pSM->uBlockPerFlash = 2047;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 512;
pSM->bIsMLCNand = TRUE;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nBlockPerZone = 2048; /* blocks per zone */
NDISK_info->nLBPerZone = 2000; /* logical blocks per zone */
}
if ((tempID[3] & 0x0C) == 0x04)
pSM->bIsNandECC4 = TRUE;
else if ((tempID[3] & 0x0C) == 0x08)
pSM->bIsNandECC4 = FALSE;
pSM->uSectorPerFlash = 1022976;
pSM->bIsMulticycle = TRUE;
pSM->nPageSize = NAND_PAGE_2KB;
NDISK_info->nPageSize = 2048;
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
break;
case 0xd3: // 1024M
if ((tempID[3] & 0x33) == 0x32)
{
pSM->uBlockPerFlash = 2047;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 1024; /* 128x8 */
pSM->nPageSize = NAND_PAGE_4KB;
pSM->bIsMLCNand = TRUE;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nPageSize = 4096;
NDISK_info->nBlockPerZone = 2048; /* blocks per zone */
NDISK_info->nLBPerZone = 2000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x11)
{
pSM->uBlockPerFlash = 8191;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 256;
pSM->nPageSize = NAND_PAGE_2KB;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nPageSize = 2048;
NDISK_info->nBlockPerZone = 8192; /* blocks per zone */
NDISK_info->nLBPerZone = 8000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x21)
{
pSM->uBlockPerFlash = 4095;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 512;
pSM->bIsMLCNand = TRUE;
pSM->nPageSize = NAND_PAGE_2KB;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nPageSize = 2048;
NDISK_info->nBlockPerZone = 4096; /* blocks per zone */
NDISK_info->nLBPerZone = 4000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x22)
{
pSM->uBlockPerFlash = 4095;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 512; /* 64x8 */
pSM->nPageSize = NAND_PAGE_4KB;
pSM->bIsMLCNand = FALSE;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nPageSize = 4096;
NDISK_info->nBlockPerZone = 4096; /* blocks per zone */
NDISK_info->nLBPerZone = 4000; /* logical blocks per zone */
}
if ((tempID[3] & 0x0C) == 0x04)
pSM->bIsNandECC4 = TRUE;
else if ((tempID[3] & 0x0C) == 0x08)
pSM->bIsNandECC4 = FALSE;
pSM->uSectorPerFlash = 2045952;
pSM->bIsMulticycle = TRUE;
if ((pSM->nPageSize == NAND_PAGE_4KB) ||
(pSM->bIsNandECC4 == FALSE) )
{
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
pSM->bIsNandECC12 = FALSE;
// pSM->bIsNandECC8 = FALSE;
// pSM->bIsNandECC12 = TRUE;
}
else
{
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
}
break;
case 0xd5: // 2048M
if ((tempID[3] & 0x33) == 0x32)
{
pSM->uBlockPerFlash = 4095;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 1024; /* 128x8 */
pSM->nPageSize = NAND_PAGE_4KB;
pSM->bIsMLCNand = TRUE;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nPageSize = 4096;
NDISK_info->nBlockPerZone = 4096; /* blocks per zone */
NDISK_info->nLBPerZone = 4000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x11)
{
pSM->uBlockPerFlash = 16383;
pSM->uPagePerBlock = 64;
pSM->uSectorPerBlock = 256;
pSM->nPageSize = NAND_PAGE_2KB;
NDISK_info->NAND_type = NAND_TYPE_SLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 64; /* pages per block */
NDISK_info->nPageSize = 2048;
NDISK_info->nBlockPerZone = 16384; /* blocks per zone */
NDISK_info->nLBPerZone = 16000; /* logical blocks per zone */
}
else if ((tempID[3] & 0x33) == 0x21)
{
pSM->uBlockPerFlash = 8191;
pSM->uPagePerBlock = 128;
pSM->uSectorPerBlock = 512;
pSM->nPageSize = NAND_PAGE_2KB;
pSM->bIsMLCNand = TRUE;
NDISK_info->NAND_type = NAND_TYPE_MLC;
NDISK_info->nZone = 1; /* number of zones */
NDISK_info->nPagePerBlock = 128; /* pages per block */
NDISK_info->nPageSize = 2048;
NDISK_info->nBlockPerZone = 8192; /* blocks per zone */
NDISK_info->nLBPerZone = 8000; /* logical blocks per zone */
}
if ((tempID[3] & 0x0C) == 0x04)
pSM->bIsNandECC4 = TRUE;
else if ((tempID[3] & 0x0C) == 0x08)
pSM->bIsNandECC4 = FALSE;
pSM->uSectorPerFlash = 4091904;
pSM->bIsMulticycle = TRUE;
if ((pSM->nPageSize == NAND_PAGE_4KB) ||
(pSM->bIsNandECC4 == FALSE) )
{
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
pSM->bIsNandECC12 = FALSE;
}
else
{
pSM->bIsNandECC4 = FALSE;
pSM->bIsNandECC8 = TRUE;
}
break;
default:
#ifdef DEBUG
printf("SM ID not support!![%x][%x]\n", tempID[0], tempID[1]);
#endif
return FMI_SM_ID_ERR;
}
#ifdef DEBUG
printf("SM ID [%x][%x][%x][%x]\n", tempID[0], tempID[1], tempID[2], tempID[3]);
#endif
return 0;
}
INT fmiSM2BufferM(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT8 ucColAddr)
{
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCMD, 0x00); // read command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
}
INT fmiSM2BufferM_RA(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT8 ucColAddr)
{
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCMD, 0x50); // read command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
}
INT fmiSMECCErrCount(UINT32 ErrSt, BOOL bIsECC8)
{
unsigned int volatile errCount;
if ((ErrSt & 0x02) || (ErrSt & 0x200) || (ErrSt & 0x20000) || (ErrSt & 0x2000000))
{
#ifdef DEBUG
printf("uncorrectable!![0x%x]\n", ErrSt);
#endif
return FMI_SM_ECC_ERROR;
}
if (ErrSt & 0x01)
{
errCount = (ErrSt >> 2) & 0xf;
#ifdef DEBUG
if (bIsECC8)
printf("Field 5 have %d error!!\n", errCount);
else
printf("Field 1 have %d error!!\n", errCount);
#endif
}
if (ErrSt & 0x100)
{
errCount = (ErrSt >> 10) & 0xf;
#ifdef DEBUG
if (bIsECC8)
printf("Field 6 have %d error!!\n", errCount);
else
printf("Field 2 have %d error!!\n", errCount);
#endif
}
if (ErrSt & 0x10000)
{
errCount = (ErrSt >> 18) & 0xf;
#ifdef DEBUG
if (bIsECC8)
printf("Field 7 have %d error!!\n", errCount);
else
printf("Field 3 have %d error!!\n", errCount);
#endif
}
if (ErrSt & 0x1000000)
{
errCount = (ErrSt >> 26) & 0xf;
#ifdef DEBUG
if (bIsECC8)
printf("Field 8 have %d error!!\n", errCount);
else
printf("Field 4 have %d error!!\n", errCount);
#endif
}
return errCount;
}
static VOID fmiSM_CorrectData_BCH(UINT8 ucFieidIndex, UINT8 ucErrorCnt, UINT8* pDAddr)
{
UINT32 uaData[16], uaAddr[16];
UINT32 uaErrorData[4];
UINT8 ii, jj;
UINT32 uPageSize;
uPageSize = inpw(REG_SMCSR) & SMCR_PSIZE;
jj = ucErrorCnt/4;
jj ++;
if (jj > 4) jj = 4;
// for(ii=0; ii<4; ii++)
for(ii=0; ii<jj; ii++)
{
uaErrorData[ii] = inpw(REG_BCH_ECC_DATA0 + ii*4);
}
// for(ii=0; ii<4; ii++)
for(ii=0; ii<jj; ii++)
{
uaData[ii*4+0] = uaErrorData[ii] & 0xff;
uaData[ii*4+1] = (uaErrorData[ii]>>8) & 0xff;
uaData[ii*4+2] = (uaErrorData[ii]>>16) & 0xff;
uaData[ii*4+3] = (uaErrorData[ii]>>24) & 0xff;
}
jj = ucErrorCnt/2;
jj ++;
if (jj > 8) jj = 8;
// for(ii=0; ii<8; ii++)
for(ii=0; ii<jj; ii++)
{
uaAddr[ii*2+0] = inpw(REG_BCH_ECC_ADDR0 + ii*4) & 0x1fff;
uaAddr[ii*2+1] = (inpw(REG_BCH_ECC_ADDR0 + ii*4)>>16) & 0x1fff;
}
pDAddr += (ucFieidIndex-1)*0x200;
for(ii=0; ii<ucErrorCnt; ii++)
{
if (uPageSize == PSIZE_8K)
{
switch(inpw(REG_SMCSR) & SMCR_BCH_TSEL)
{
case BCH_T4: // 8K+256
default:
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset, only Field-0
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 7 - uaAddr[ii];
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_32+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T8: // 8K+256
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 14 - uaAddr[ii];
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_4+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T12: // 8K+376
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 23*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 22 - uaAddr[ii];
uaAddr[ii] += 23*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_2+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T15:
break;
}
}
else if (uPageSize == PSIZE_4K)
{
switch(inpw(REG_SMCSR) & SMCR_BCH_TSEL)
{
case BCH_T4: // 4K+128
default:
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset, only Field-0
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 7 - uaAddr[ii];
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_16+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T8: // 4K+128
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 14 - uaAddr[ii];
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_2+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T12: // 4K+216
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 23*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 22 - uaAddr[ii];
uaAddr[ii] += 23*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_8+uaAddr[ii]) ^= uaData[ii];
}
}
break;
}
}
else if (uPageSize == PSIZE_2K)
{
switch(inpw(REG_SMCSR) & SMCR_BCH_TSEL)
{
case BCH_T4:
default:
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset, only Field-0
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 7 - uaAddr[ii];
uaAddr[ii] += 8*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_8+uaAddr[ii]) ^= uaData[ii];
}
}
break;
case BCH_T8:
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 14 - uaAddr[ii];
uaAddr[ii] += 15*(ucFieidIndex-1); // field offset
*((UINT8*)REG_SMRA_1+uaAddr[ii]) ^= uaData[ii];
}
}
break;
}
}
else
{
if (uaAddr[ii] < 512)
*(pDAddr+uaAddr[ii]) ^= uaData[ii];
else
{
if (uaAddr[ii] < 515)
{
uaAddr[ii] -= 512;
*((UINT8*)REG_SMRA_0+uaAddr[ii]) ^= uaData[ii];
}
else
{
uaAddr[ii] = 543 - uaAddr[ii];
uaAddr[ii] = 7 - uaAddr[ii];
*((UINT8*)REG_SMRA_2+uaAddr[ii]) ^= uaData[ii];
}
}
}
}
}
INT fmiSM_Read_512(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 uDAddr)
{
int volatile ret=0;
UINT32 uStatus;
UINT32 uErrorCnt;
volatile UINT32 uError = 0;
outpw(REG_DMACSAR, uDAddr);
ret = fmiSM2BufferM(pSM, uSector, 0);
if (ret < 0)
return ret;
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
#ifdef _SIC_USE_INT_
while(!_fmi_bIsSMDataReady);
#else
while(1)
{
if (!(inpw(REG_SMCSR) & SMCR_DRD_EN))
break;
}
#endif
if (pSM->bIsCheckECC)
{
while(1)
{
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF)
{
if (inpw(REG_SMCSR) & BCH_T4) // BCH_ECC selected
{
uStatus = inpw(REG_SM_ECC_ST0);
uStatus &= 0x3f;
if ((uStatus & 0x03)==0x01) // correctable error in 1st field
{
uErrorCnt = uStatus >> 2;
fmiSM_CorrectData_BCH(1, uErrorCnt, (UINT8*)uDAddr);
#ifdef DEBUG
printf("Field 1 have %d error!!\n", uErrorCnt);
#endif
}
else if (((uStatus & 0x03)==0x02)
||((uStatus & 0x03)==0x03)) // uncorrectable error or ECC error
{
#ifdef DEBUG
printf("SM uncorrectable error is encountered, %4x !!\n", uStatus);
#endif
uError = 1;
}
}
else
{
#ifdef DEBUG
printf("Wrong BCH setting for page-512 NAND !!\n");
#endif
uError = 2;
}
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FLD_Error
}
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
{
if ( !(inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) )
break;
}
}
}
else
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
if (uError)
return -1;
return 0;
}
VOID fmiBuffer2SMM(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT8 ucColAddr)
{
// set the spare area configuration
/* write byte 514, 515 as used page */
#ifdef OPT_SOFTWARE_WRITE_ECC
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMRA_1, inpw(REG_SMRA_1) | 0x0000FFFF);
#else
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMRA_1, 0xFFFFFFFF);
#endif
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
}
static INT fmiSM_Write_512_BCH(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 uSAddr)
{
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
outpw(REG_DMACSAR, uSAddr);
fmiBuffer2SMM(pSM, uSector, 0);
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif // _SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMCMD, 0x10); // auto program command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_512: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
//INT fmiSM_Write_512(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 uSAddr)
static INT fmiSM_Write_512_SECC(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 uSAddr)
{
#ifdef OPT_SOFTWARE_WRITE_ECC
unsigned int i;
unsigned char u8Parity[10];
unsigned char *ptr = (unsigned char *)REG_SMRA_0; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
#endif
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
#ifdef OPT_SOFTWARE_WRITE_ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_EN); // disable ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN); // HW bug (if not to disable this bit, DMAC can't be complete)
#else
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
#endif
#ifdef OPT_SOFTWARE_WRITE_ECC
*ptr++=0xFF; /* Byte 0 ~5 recommand by HP */
*ptr++=0xFF;
*ptr++=0x00;
*ptr++=0x00;
*ptr++=0xFF;
*ptr++=0xFF;
Ecc4Encoder((char *)uSAddr, u8Parity, FALSE);
memcpy(ptr, u8Parity, 10); /* copy parity to REG_SMRA_0+6 */
DBG_PRINTF("Software ECC4 Encoder Successful\n");
#endif
outpw(REG_DMACSAR, uSAddr);
fmiBuffer2SMM(pSM, uSector, 0);
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif // _SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
#ifdef OPT_SOFTWARE_WRITE_ECC
DBG_PRINTF("Complete\n");
if (pSM->bIsCheckECC)
{
ptr = (unsigned char *)REG_SMRA_0; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
for(i=0; i<16; i=i+1)
{
outpw(REG_SMDATA, *ptr++);
}
}
#endif
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMCMD, 0x10); // auto program command
#ifdef OPT_SOFTWARE_WRITE_ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_EN); // enable ECC again
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
#endif
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_512: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
INT fmiSM_Read_2K(FMI_SM_INFO_T *pSM, UINT32 uPage, UINT32 uDAddr)
{
UINT32 uStatus;
UINT32 uErrorCnt, ii;
volatile UINT32 uError = 0;
// fmiSM_Reset(pSM);
while(inpw(REG_DMACCSR) & FMI_BUSY); // wait DMAC FMI ready;
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_EN);
outpw(REG_DMACSAR, uDAddr); // set DMA transfer starting address
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
//printf("read: ECC error!!\n");
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
outpw(REG_SMCMD, 0x00); // read command
outpw(REG_SMADDR, 0); // CA0 - CA7
outpw(REG_SMADDR, 0); // CA8 - CA11
outpw(REG_SMADDR, uPage & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uPage >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uPage >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uPage >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0x30); // read command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
// if ((pSM->bIsCheckECC) || (inpw(REG_SMCSR)&SMCR_ECC_CHK) )
if (pSM->bIsCheckECC)
{
while(1)
{
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF)
{
uStatus = inpw(REG_SM_ECC_ST0);
for (ii=1; ii<5; ii++)
{
#if 0
if (!(uStatus & 0x03))
{
uStatus >>= 8;
continue;
}
#endif
if ((uStatus & 0x03)==0x01) // correctable error in 1st field
{
uErrorCnt = uStatus >> 2;
fmiSM_CorrectData_BCH(ii, uErrorCnt, (UINT8*)uDAddr);
#ifdef DEBUG
printf("Field %d have %d error!!\n", ii, uErrorCnt);
#endif
break;
}
else if (((uStatus & 0x03)==0x02)
||((uStatus & 0x03)==0x03)) // uncorrectable error or ECC error in 1st field
{
#ifdef DEBUG
printf("SM uncorrectable error is encountered, %4x !!\n", uStatus);
#endif
uError = 1;
break;
}
uStatus >>= 8;
}
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FLD_Error
}
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
{
if ( !(inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) )
break;
}
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
{
if ( !(inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) )
break;
}
#endif //_SIC_USE_INT_
}
}
else
{
while(1)
{
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
if (inpw(REG_SMISR) & SMISR_DMA_IF)
{
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
break;
}
}
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
if (uError)
return -1;
return 0;
}
static INT fmiSM_Read_2K_SECC_1st512(FMI_SM_INFO_T *pSM, UINT32 uPage, UINT32 uDAddr)
{
UINT32 uStatus;
UINT32 uErrorCnt, ii;
while(inpw(REG_DMACCSR) & FMI_BUSY); // wait DMAC FMI ready;
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_EN);
outpw(REG_DMACSAR, uDAddr); // set DMA transfer starting address
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
//printf("read: ECC error!!\n");
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
outpw(REG_SMCMD, 0x00); // read command
outpw(REG_SMADDR, 0); // CA0 - CA7
outpw(REG_SMADDR, 0); // CA8 - CA11
outpw(REG_SMADDR, uPage & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uPage >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uPage >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uPage >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0x30); // read command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
{
while(1)
{
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
if (inpw(REG_SMISR) & SMISR_DMA_IF)
{
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
break;
}
}
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
return 0;
}
INT fmiSM_Read_RA(FMI_SM_INFO_T *pSM, UINT32 uPage, UINT32 ucColAddr)
{
/* clear R/B flag */
// fmiSM_Reset(pSM);
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCMD, 0x00); // read command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
// outpw(REG_SMADDR, (ucColAddr >> 8) & 0x1f); // CA8 - CA12
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xFF); // CA8 - CA12
outpw(REG_SMADDR, uPage & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uPage >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uPage >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uPage >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0x30); // read command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
}
INT fmiSM_Read_RA_512(FMI_SM_INFO_T *pSM, UINT32 uPage, UINT32 uColumm)
{
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCMD, 0x50); // read command
outpw(REG_SMADDR, uColumm);
outpw(REG_SMADDR, uPage & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uPage >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uPage >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uPage >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
return 0;
}
//INT fmiSM_Write_2K(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
static INT fmiSM_Write_2K_BCH(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
{
// fmiSM_Reset(pSM);
/* enable DMAC */
while(inpw(REG_DMACCSR) & FMI_BUSY); // wait DMAC FMI ready;
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_EN);
outpw(REG_DMACSAR, uSAddr); // set DMA transfer starting address
// set the spare area configuration
/* write byte 2050, 2051 as used page */
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
//printf("error sector !!\n");
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
// outpw(REG_SMADDR, (ucColAddr >> 8) & 0x0f); // CA8 - CA11
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xff); // CA8 - CA11
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMCMD, 0x10); // auto program command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_2K: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
#if 0
if (inpw(REG_SMRA_0) != 0x0000FFFF)
while(1);
#endif
return 0;
}
//INT fmiSM_Write_2K(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
static INT fmiSM_Write_2K_SECC(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
{
volatile char u8EccStatus = 0;
unsigned int i;
unsigned char u8Parity[10];
unsigned char *ptr = (unsigned char *)REG_SMRA_0; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_EN); // disable ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN); // HW bug (if not to disable this bit, DMAC can't be complete)
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_512); // psize:512
/* enable DMAC */
while(inpw(REG_DMACCSR) & FMI_BUSY); // wait DMAC FMI ready;
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_EN);
outpw(REG_DMACSAR, uSAddr); // set DMA transfer starting address
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
//printf("error sector !!\n");
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
// outpw(REG_SMADDR, (ucColAddr >> 8) & 0x0f); // CA8 - CA11
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xff); // CA8 - CA11
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
/* write 1st 512+16 */
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
// set the spare area configuration
*ptr++=0xFF; /* Byte 0 ~5 recommand by HP */
*ptr++=0xFF;
*ptr++=0x00;
*ptr++=0x00;
*ptr++=0xFF;
*ptr++=0xFF;
Ecc4Encoder((char *)uSAddr, u8Parity, FALSE);
memcpy(ptr, u8Parity, 10); /* copy parity to REG_SMRA_0+6 */
DBG_PRINTF("Software ECC4 Encoder Successful\n");
ptr = (unsigned char *)REG_SMRA_0; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
for(i=0; i<16; i=i+1)
{
outpw(REG_SMDATA, *ptr++);
}
/* write 2nd 512+16 */
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
// set the spare area configuration
*ptr++=0xFF; /* Byte 0 ~5 recommand by HP */
*ptr++=0xFF;
*ptr++=0x00;
*ptr++=0x00;
*ptr++=0xFF;
*ptr++=0xFF;
uSAddr += 512;
Ecc4Encoder((char *)uSAddr, u8Parity, FALSE);
memcpy(ptr, u8Parity, 10); /* copy parity to REG_SMRA_0+6 */
DBG_PRINTF("Software ECC4 Encoder Successful\n");
ptr = (unsigned char *)REG_SMRA_4; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
for(i=0; i<16; i=i+1)
{
outpw(REG_SMDATA, *ptr++);
}
/* write 3rd 512+16 */
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
// set the spare area configuration
*ptr++=0xFF; /* Byte 0 ~5 recommand by HP */
*ptr++=0xFF;
*ptr++=0x00;
*ptr++=0x00;
*ptr++=0xFF;
*ptr++=0xFF;
uSAddr += 512;
Ecc4Encoder((char *)uSAddr, u8Parity, FALSE);
memcpy(ptr, u8Parity, 10); /* copy parity to REG_SMRA_0+6 */
DBG_PRINTF("Software ECC4 Encoder Successful\n");
ptr = (unsigned char *)REG_SMRA_8; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
for(i=0; i<16; i=i+1)
{
outpw(REG_SMDATA, *ptr++);
}
/* write 4th 512+16 */
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
// set the spare area configuration
*ptr++=0xFF; /* Byte 0 ~5 recommand by HP */
*ptr++=0xFF;
*ptr++=0x00;
*ptr++=0x00;
*ptr++=0xFF;
*ptr++=0xFF;
uSAddr += 512;
Ecc4Encoder((char *)uSAddr, u8Parity, FALSE);
memcpy(ptr, u8Parity, 10); /* copy parity to REG_SMRA_0+6 */
DBG_PRINTF("Software ECC4 Encoder Successful\n");
ptr = (unsigned char *)REG_SMRA_12; /* ptr:Logical address, ECC4 encoder data to FMI_BA[0x200] */
for(i=0; i<16; i=i+1)
{
outpw(REG_SMDATA, *ptr++);
}
// program it
outpw(REG_SMCMD, 0x10); // auto program command
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_EN); // enable ECC again
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_2K); // psize:2048
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_2K: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
INT fmiSM_Write_2K_ALC(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
{
outpw(REG_DMACSAR, uSAddr); // set DMA transfer starting address
// set the spare area configuration
/* write byte 2050, 2051 as used page */
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN);
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, (ucColAddr >> 8) & 0x0f); // CA8 - CA11
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|0x80000000); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|0x80000000); // PA16 - PA17
}
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif // _SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
{
int i;
UINT8 *u8pData;
u8pData = (UINT8 *)REG_SMRA_0;
for (i=0; i<64; i++)
outpw(REG_SMDATA, *u8pData++);
}
outpw(REG_SMCMD, 0x10); // auto program command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_2K: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
INT fmiSM_Read_4K(FMI_SM_INFO_T *pSM, UINT32 uPage, UINT32 uDAddr)
{
UINT32 uStatus;
UINT32 uErrorCnt, ii, jj;
volatile UINT32 uError = 0;
outpw(REG_DMACSAR, uDAddr); // set DMA transfer starting address
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
outpw(REG_SMCMD, 0x00); // read command
outpw(REG_SMADDR, 0); // CA0 - CA7
outpw(REG_SMADDR, 0); // CA8 - CA11
outpw(REG_SMADDR, uPage & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uPage >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uPage >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uPage >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0x30); // read command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
if ((pSM->bIsCheckECC) || (inpw(REG_SMCSR)&SMCR_ECC_CHK) )
{
while(1)
{
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF)
{
for (jj=0; jj<2; jj++)
{
uStatus = inpw(REG_SM_ECC_ST0+jj*4);
if (!uStatus)
continue;
for (ii=1; ii<5; ii++)
{
if (!(uStatus & 0x03))
{
uStatus >>= 8;
continue;
}
if ((uStatus & 0x03)==0x01) // correctable error in 1st field
{
uErrorCnt = uStatus >> 2;
fmiSM_CorrectData_BCH(jj*4+ii, uErrorCnt, (UINT8*)uDAddr);
#ifdef DEBUG
printf("Field %d have %d error!!\n", jj*4+ii, uErrorCnt);
#endif
break;
}
else if (((uStatus & 0x03)==0x02)
||((uStatus & 0x03)==0x03)) // uncorrectable error or ECC error in 1st field
{
#ifdef _DEBUG
printf("SM uncorrectable BCH error is encountered !!\n");
#endif
uError = 1;
break;
}
uStatus >>= 8;
}
}
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FLD_Error
}
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
{
if ( !(inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) )
break;
}
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
{
if ( !(inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) )
break;
}
#endif //_SIC_USE_INT_
}
}
else
{
while(1)
{
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
if (inpw(REG_SMISR) & SMISR_DMA_IF)
{
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
break;
}
}
}
if (uError)
return -1;
return 0;
}
INT fmiSM_Write_4K(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
{
outpw(REG_DMACSAR, uSAddr); // set DMA transfer starting address
// set the spare area configuration
/* write byte 2050, 2051 as used page */
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
// outpw(REG_SMADDR, (ucColAddr >> 8) & 0x1f); // CA8 - CA12
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xff); // CA8 - CA12
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif //_SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMCMD, 0x10); // auto program command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_4K: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
INT fmiSM_Write_4K_ALC(FMI_SM_INFO_T *pSM, UINT32 uSector, UINT32 ucColAddr, UINT32 uSAddr)
{
outpw(REG_DMACSAR, uSAddr); // set DMA transfer starting address
// set the spare area configuration
/* write byte 2050, 2051 as used page */
outpw(REG_SMRA_0, 0x0000FFFF);
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN);
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, (ucColAddr >> 8) & 0x1f); // CA8 - CA12
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
#ifdef _SIC_USE_INT_
_fmi_bIsSMDataReady = FALSE;
#endif // _SIC_USE_INT_
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DWR_EN);
while(1)
{
#ifdef _SIC_USE_INT_
if (_fmi_bIsSMDataReady)
#else
if (inpw(REG_SMISR) & SMISR_DMA_IF) // wait to finish DMAC transfer.
#endif //_SIC_USE_INT_
break;
}
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
{
int i;
UINT8 *u8pData;
u8pData = (UINT8 *)REG_SMRA_0;
for (i=0; i<218; i++)
outpw(REG_SMDATA, *u8pData++);
}
outpw(REG_SMCMD, 0x10); // auto program command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("fmiSM_Write_4K: data error!!\n");
#endif
return FMI_SM_STATE_ERROR;
}
return 0;
}
// mhkuo
INT fmiCheckInvalidBlock(FMI_SM_INFO_T *pSM, UINT32 BlockNo)
{
int volatile status=0;
unsigned int volatile sector;
unsigned char volatile data512=0xff, data517=0xff, blockStatus=0xff;
if (BlockNo == 0)
return 0;
// sector = BlockNo * pSM->uPagePerBlock;
#ifdef OPT_SOFTWARE_2KNAND_ECC
if (pSM == pSM0)
{
if (pSM->bIsMLCNand == TRUE)
sector = (BlockNo+1) * pSM->uPagePerBlock - 1;
else
sector = BlockNo * pSM->uPagePerBlock;
if (pSM->nPageSize == NAND_PAGE_512B)
status = fmiSM2BufferM_RA(pSM, sector, 0);
else
status = fmiSM_Read_RA(pSM, sector, pSM->nPageSize);
}
else
{
sector = BlockNo * pSM->uPagePerBlock;
if (pSM->nPageSize == NAND_PAGE_512B)
status = fmiSM2BufferM_RA(pSM, sector, 0);
else if (pSM->nPageSize == NAND_PAGE_2KB)
status = fmiSM_Read_RA(pSM, sector, 512);
else
{
if (pSM->bIsMLCNand == TRUE)
sector = (BlockNo+1) * pSM->uPagePerBlock - 1;
status = fmiSM_Read_RA(pSM, sector, pSM->nPageSize);
}
}
#else
if (pSM->bIsMLCNand == TRUE)
sector = (BlockNo+1) * pSM->uPagePerBlock - 1;
else
sector = BlockNo * pSM->uPagePerBlock;
if (pSM->nPageSize == NAND_PAGE_512B)
status = fmiSM2BufferM_RA(pSM, sector, 0);
else
status = fmiSM_Read_RA(pSM, sector, pSM->nPageSize);
#endif
if (status < 0)
{
#ifdef DEBUG
printf("fmiCheckInvalidBlock 0x%x\n", status);
#endif
return 1;
}
#ifdef OPT_SOFTWARE_2KNAND_ECC
if ( (pSM->nPageSize == NAND_PAGE_512B) ||
((pSM->nPageSize == NAND_PAGE_2KB) && (pSM == pSM1) ))
{
#else
if (pSM->nPageSize == NAND_PAGE_512B)
{
#endif
data512 = inpw(REG_SMDATA) & 0xff;
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA) & 0xff;
// if ((data512 != 0xFF) || (data517 != 0xFF))
if ((data512 == 0xFF) && (data517 == 0xFF))
{
fmiSM_Reset(pSM);
#ifdef OPT_SOFTWARE_2KNAND_ECC
if (pSM->nPageSize == NAND_PAGE_512B)
status = fmiSM2BufferM_RA(pSM, sector+1, 0);
else
status = fmiSM_Read_RA(pSM, sector+1, 512);
#else
status = fmiSM2BufferM_RA(pSM, sector+1, 0);
#endif
if (status < 0)
{
#ifdef DEBUG
printf("fmiCheckInvalidBlock 0x%x\n", status);
#endif
return 1;
}
data512 = inpw(REG_SMDATA) & 0xff;
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA) & 0xff;
if ((data512 != 0xFF) || (data517 != 0xFF))
{
fmiSM_Reset(pSM);
return 1; // invalid block
}
}
else
{
fmiSM_Reset(pSM);
return 1; // invalid block
}
}
else
{
blockStatus = inpw(REG_SMDATA) & 0xff;
// if (blockStatus != 0xFF)
if (blockStatus == 0xFF)
{
fmiSM_Reset(pSM);
#if 0
return 1; // mhkuo@20100614
#else
status = fmiSM_Read_RA(pSM, sector+1, pSM->nPageSize);
if (status < 0)
{
#ifdef DEBUG
printf("fmiCheckInvalidBlock 0x%x\n", status);
#endif
return 1;
}
blockStatus = inpw(REG_SMDATA) & 0xff;
if (blockStatus != 0xFF)
{
fmiSM_Reset(pSM);
return 1; // invalid block
}
#endif
}
else
{
fmiSM_Reset(pSM);
return 1; // invalid block
}
}
fmiSM_Reset(pSM);
return 0;
}
static void sicSMselect(INT chipSel)
{
if (chipSel == 0)
{
outpw(REG_GPDFUN, inpw(REG_GPDFUN) | 0x0003CC00); // enable NAND NWR/NRD/RB0 pins
outpw(REG_GPEFUN, inpw(REG_GPEFUN) | 0x00F30000); // enable NAND ALE/CLE/CS0 pins
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_CS0);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_CS1);
}
else
{
outpw(REG_GPDFUN, inpw(REG_GPDFUN) | 0x0003F000); // enable NAND NWR/NRD/RB1 pins
outpw(REG_GPEFUN, inpw(REG_GPEFUN) | 0x00FC0000); // enable NAND ALE/CLE/CS1 pins
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_CS1);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_CS0);
}
}
static INT fmiNormalCheckBlock(FMI_SM_INFO_T *pSM, UINT32 BlockNo)
{
int volatile status=0;
unsigned int volatile sector;
unsigned char data, data517;
_fmi_pSMBuffer = (UINT8 *)((UINT32)_fmi_ucSMBuffer | 0x80000000);
/* MLC check the 2048 byte of last page per block */
if (pSM->bIsMLCNand == TRUE)
{
if (pSM->nPageSize == NAND_PAGE_2KB)
{
sector = (BlockNo+1) * pSM->uPagePerBlock - 1;
/* Read 2048 byte */
status = fmiSM_Read_RA(pSM, sector, 2048);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data != 0xFF)
return 1; // invalid block
}
else if (pSM->nPageSize == NAND_PAGE_4KB)
{
sector = (BlockNo+1) * pSM->uPagePerBlock - 1;
/* Read 4096 byte */
status = fmiSM_Read_RA(pSM, sector, 4096);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data != 0xFF)
return 1; // invalid block
}
}
/* SLC check the 2048 byte of 1st or 2nd page per block */
else // SLC
{
sector = BlockNo * pSM->uPagePerBlock;
if (pSM->nPageSize == NAND_PAGE_4KB)
{
status = fmiSM_Read_RA(pSM, sector, 4096);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data == 0xFF)
{
#ifdef DEBUG
// printf("find bad block, check next page to confirm it.\n");
#endif
status = fmiSM_Read_RA(pSM, sector+1, 4096);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data != 0xFF)
{
#ifdef DEBUG
printf("find bad block is conformed.\n");
#endif
return 1; // invalid block
}
}
else
{
#ifdef DEBUG
printf("find bad block is conformed.\n");
#endif
return 1; // invalid block
}
}
else if (pSM->nPageSize == NAND_PAGE_2KB)
{
status = fmiSM_Read_RA(pSM, sector, 2048);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data == 0xFF)
{
#ifdef DEBUG
// printf("find bad block, check next page to confirm it.\n");
#endif
status = fmiSM_Read_RA(pSM, sector+1, 2048);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
if (data != 0xFF)
{
#ifdef DEBUG
printf("find bad block is conformed.\n");
#endif
return 1; // invalid block
}
}
else
{
#ifdef DEBUG
printf("find bad block is conformed.\n");
#endif
return 1; // invalid block
}
}
else /* page size 512B */
{
status = fmiSM2BufferM_RA(pSM, sector, 0);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA) & 0xff;
// if ((data != 0xFF) || (data517 != 0xFF))
if ((data == 0xFF) && (data517 == 0xFF))
{
fmiSM_Reset(pSM);
status = fmiSM2BufferM_RA(pSM, sector+1, 0);
if (status < 0)
{
#ifdef DEBUG
printf("fmiNormalCheckBlock 0x%x\n", status);
#endif
return 1;
}
data = inpw(REG_SMDATA) & 0xff;
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA);
data517 = inpw(REG_SMDATA) & 0xff;
if ((data != 0xFF) || (data517 != 0xFF))
{
fmiSM_Reset(pSM);
return 1; // invalid block
}
}
else
{
#ifdef DEBUG
printf("find bad block is conformed.\n");
#endif
fmiSM_Reset(pSM);
return 1; // invalid block
}
fmiSM_Reset(pSM);
}
}
return 0;
}
/* function pointer */
FMI_SM_INFO_T *pSM0=0, *pSM1=0;
static INT sicSMInit(INT chipSel, NDISK_T *NDISK_info)
{
int status=0, count;
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_EN);
outpw(REG_DMACCSR, inpw(REG_DMACCSR) | DMAC_SWRST);
outpw(REG_DMACCSR, inpw(REG_DMACCSR) & ~DMAC_SWRST);
outpw(REG_FMICR, FMI_SM_EN);
if ((_nand_init0 == 0) && (_nand_init1 == 0))
{
// enable SM
/* select NAND control pin used */
// outpw(REG_GPDFUN, inpw(REG_GPDFUN) | 0x0003FC00); // enable NAND NWR/NRD/RB0/RB1 pins
// outpw(REG_GPEFUN, inpw(REG_GPEFUN) | 0x00FF0000); // enable NAND ALE/CLE/CS0/CS1 pins
// outpw(REG_GPDFUN, inpw(REG_GPDFUN) | 0x0003C000); // enable NAND NWR/NRD pins
// outpw(REG_GPEFUN, inpw(REG_GPEFUN) | 0x00F00000); // enable NAND ALE/CLE pins
// outpw(REG_SMTCR, 0x20304);
// outpw(REG_SMTCR, 0x10204);
outpw(REG_SMTCR, 0x20305);
outpw(REG_SMCSR, (inpw(REG_SMCSR) & ~SMCR_PSIZE) | PSIZE_512);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_3B_PROTECT);
// outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_3B_PROTECT);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_CHK);
/* init SM interface */
#ifdef _NAND_PAR_ALC_
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN);
#ifdef DEBUG
printf("Parity only written to SM registers but not NAND !!\n");
#endif
#else
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
#ifdef DEBUG
printf("Parity written to SM registers and NAND !!\n");
#endif
#endif // _NAND_PAR_ALC_
}
sicSMselect(chipSel);
if (chipSel == 0)
{
if (_nand_init0)
return 0;
pSM0 = malloc(sizeof(FMI_SM_INFO_T));
if (pSM0 == NULL)
return FMI_NO_MEMORY;
memset((char *)pSM0, 0, sizeof(FMI_SM_INFO_T));
if ((status = fmiSM_ReadID(pSM0, NDISK_info)) < 0)
{
if (pSM0 != NULL)
{
free(pSM0);
pSM0 = 0;
}
return status;
}
fmiSM_Initial(pSM0);
#ifdef OPT_SW_WP
outpw(REG_GPAFUN, inpw(REG_GPAFUN) & ~MF_GPA7); // port A7 low (WP)
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~0x0080); // port A7 low (WP)
outpw(REG_GPIOA_OMD, inpw(REG_GPIOA_OMD) | 0x0080); // port A7 output
#endif
// check NAND boot header
fmiSMCheckBootHeader(0, pSM0);
while(1)
{
//#ifdef OPT_SOFTWARE_2KNAND_ECC
// if (fmiCheckInvalidBlock(pSM0, pSM0->uLibStartBlock) != 1) // valid block
// break;
//#else
if (!fmiNormalCheckBlock(pSM0, pSM0->uLibStartBlock))
break;
//#endif
else
{
#ifdef DEBUG
printf("invalid start block %d\n", pSM0->uLibStartBlock);
#endif
pSM0->uLibStartBlock++;
}
}
if (pSM0->bIsCheckECC)
if (pSM0->uLibStartBlock == 0)
pSM0->uLibStartBlock++;
NDISK_info->nStartBlock = pSM0->uLibStartBlock; /* available start block */
pSM0->uBlockPerFlash -= pSM0->uLibStartBlock;
count = NDISK_info->nBlockPerZone * 2 / 100 + NAND_RESERVED_BLOCK;
NDISK_info->nBlockPerZone = (NDISK_info->nBlockPerZone * NDISK_info->nZone - NDISK_info->nStartBlock) / NDISK_info->nZone;
NDISK_info->nLBPerZone = NDISK_info->nBlockPerZone - count;
NDISK_info->nNandNo = chipSel;
_nand_init0 = 1;
}
else if (chipSel == 1)
{
if (_nand_init1)
return 0;
pSM1 = malloc(sizeof(FMI_SM_INFO_T));
if (pSM1 == NULL)
return FMI_NO_MEMORY;
memset((char *)pSM1, 0, sizeof(FMI_SM_INFO_T));
if ((status = fmiSM_ReadID(pSM1, NDISK_info)) < 0)
{
if (pSM1 != NULL)
{
free(pSM1);
pSM1 = 0;
}
return status;
}
fmiSM_Initial(pSM1);
#ifdef OPT_SW_WP
outpw(REG_GPAFUN, inpw(REG_GPAFUN) & ~MF_GPA7); // port A7 low (WP)
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~0x0080); // port A7 low (WP)
outpw(REG_GPIOA_OMD, inpw(REG_GPIOA_OMD) | 0x0080); // port A7 output
#endif
// check NAND boot header
fmiSMCheckBootHeader(1, pSM1);
while(1)
{
#ifdef OPT_SOFTWARE_2KNAND_ECC
if (fmiCheckInvalidBlock(pSM1, pSM1->uLibStartBlock) != 1) // valid block
break;
#else
if (!fmiNormalCheckBlock(pSM1, pSM1->uLibStartBlock))
break;
#endif
else
{
#ifdef DEBUG
printf("invalid start block %d\n", pSM0->uLibStartBlock);
#endif
pSM1->uLibStartBlock++;
}
}
if (pSM1->bIsCheckECC)
if (pSM1->uLibStartBlock == 0)
pSM1->uLibStartBlock++;
NDISK_info->nStartBlock = pSM1->uLibStartBlock; /* available start block */
pSM1->uBlockPerFlash -= pSM1->uLibStartBlock;
count = NDISK_info->nBlockPerZone * 2 / 100 + NAND_RESERVED_BLOCK;
NDISK_info->nBlockPerZone = (NDISK_info->nBlockPerZone * NDISK_info->nZone - NDISK_info->nStartBlock) / NDISK_info->nZone;
NDISK_info->nLBPerZone = NDISK_info->nBlockPerZone - count;
NDISK_info->nNandNo = chipSel;
_nand_init1 = 1;
}
else
return FMI_SM_INIT_ERROR;
return 0;
}
static INT sicSMpread_BCH(INT chipSel, INT PBA, INT page, UINT8 *buff)
{
FMI_SM_INFO_T *pSM;
int pageNo;
int status=0;
int i;
char *ptr;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM); //removed by mhuko
PBA += pSM->uLibStartBlock;
pageNo = PBA * pSM->uPagePerBlock + page;
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// set to ECC4 for Block 0-3
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA(pSM, pageNo, 2048);
for (i=0; i<64; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
status = fmiSM_Read_2K(pSM, pageNo, (UINT32)buff);
}
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 4KB */
{
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA(pSM, pageNo, 4096);
// for (i=0; i<216; i++)
for (i=0; i<128; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
status = fmiSM_Read_4K(pSM, pageNo, (UINT32)buff);
}
else /* 512B */
{
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA_512(pSM, pageNo, 0);
#ifdef OPT_RW_RUNDANT_BY_DMA
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 0x10);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_REN);
#else
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
#endif
status = fmiSM_Read_512(pSM, pageNo, (UINT32)buff);
}
#ifdef DEBUG
if (status)
printf("read NAND page fail !!!\n");
#endif
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// restore to ECC8
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
// sysFlushCache(I_D_CACHE);
// sysInvalidCache();
return status;
}
//static INT sicSMpread(INT chipSel, INT PBA, INT page, UINT8 *buff)
static INT sicSMpread(INT chipSel, INT PBA, INT page, UINT8 *buff)
//INT sicSMpread(INT chipSel, INT PBA, INT page, UINT8 *buff)
{
FMI_SM_INFO_T *pSM;
int pageNo;
int status=0;
int i;
char *ptr;
#ifdef OPT_SOFTWARE_ECC
volatile char u8EccStatus = 0;
unsigned char u8Ecc4Parity[10];
unsigned int u32ErrCount;
#endif
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM); //removed by mhuko
PBA += pSM->uLibStartBlock;
pageNo = PBA * pSM->uPagePerBlock + page;
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// set to ECC4 for Block 0-3
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
#ifdef OPT_SOFTWARE_2KNAND_ECC
if(pSM->bIsCheckECC)
u8EccStatus = 1;
else
u8EccStatus = 0;
pSM->bIsCheckECC = 0;
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_EN); // disable ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN); // HW bug (if not to disable this bit, DMAC can't be complete)
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_512); // psize:512
// read 1st 512+16
status = fmiSM_Read_2K_SECC_1st512(pSM, pageNo, (UINT32)buff);
ptr = (char *)REG_SMRA_0;
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
// read 2nd 512+16
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
while(inpw(REG_SMCSR) & SMCR_DRD_EN);
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
ptr = (char *)REG_SMRA_4;
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
// read 3rd 512+16
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
while(inpw(REG_SMCSR) & SMCR_DRD_EN);
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
ptr = (char *)REG_SMRA_8;
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
// read 4th 512+16
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_DRD_EN);
while(inpw(REG_SMCSR) & SMCR_DRD_EN);
outpw(REG_SMISR, SMISR_DMA_IF); // clear DMA flag
outpw(REG_SMISR, SMISR_ECC_FIELD_IF); // clear ECC_FIELD flag
ptr = (char *)REG_SMRA_12;
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
if (u8EccStatus)
{
// decode 1st 512+16
ptr = (char *)REG_SMRA_0+6;
u32ErrCount = Ecc4Decoder(buff, ptr);
if(u32ErrCount)
// if( Ecc4Decoder(buff, ptr) != 0 )
{//Ecc4Decoder will do Ecc4Encoder first in the internal. If the content of ptr != the parity that was generated by Ecc4Encoder
sysprintf("Software ECC4 decoder not match.. Do encode \n");
sysprintf("Error bit number %d \n", u32ErrCount);
Ecc4Encoder(buff, u8Ecc4Parity, FALSE);
if( Ecc4Decoder(buff, u8Ecc4Parity) != 0 )
{
sysprintf("Software ECC4 decoder error\n");
}
}
DBG_PRINTF("Software ECC4 decoder 1st 512+16 Successful\n");
// decode 2nd 512+16
ptr = (char *)REG_SMRA_4+6;
u32ErrCount = Ecc4Decoder((UINT8*)(UINT32)buff+512, ptr);
if(u32ErrCount)
// if( Ecc4Decoder(buff, ptr) != 0 )
{//Ecc4Decoder will do Ecc4Encoder first in the internal. If the content of ptr != the parity that was generated by Ecc4Encoder
sysprintf("Software ECC4 decoder not match.. Do encode \n");
sysprintf("Error bit number %d \n", u32ErrCount);
Ecc4Encoder(buff, u8Ecc4Parity, FALSE);
if( Ecc4Decoder(buff, u8Ecc4Parity) != 0 )
{
sysprintf("Software ECC4 decoder error\n");
}
}
DBG_PRINTF("Software ECC4 decoder 2nd 512+16 Successful\n");
// decode 3rd 512+16
ptr = (char *)REG_SMRA_8+6;
u32ErrCount = Ecc4Decoder((UINT8*)(UINT32)buff+1024, ptr);
if(u32ErrCount)
// if( Ecc4Decoder(buff, ptr) != 0 )
{//Ecc4Decoder will do Ecc4Encoder first in the internal. If the content of ptr != the parity that was generated by Ecc4Encoder
sysprintf("Software ECC4 decoder not match.. Do encode \n");
sysprintf("Error bit number %d \n", u32ErrCount);
Ecc4Encoder(buff, u8Ecc4Parity, FALSE);
if( Ecc4Decoder(buff, u8Ecc4Parity) != 0 )
{
sysprintf("Software ECC4 decoder error\n");
}
}
DBG_PRINTF("Software ECC4 decoder 3rd 512+16 Successful\n");
// decode 3rd 512+16
ptr = (char *)REG_SMRA_12+6;
u32ErrCount = Ecc4Decoder((UINT8*)(UINT32)buff+1536, ptr);
if(u32ErrCount)
// if( Ecc4Decoder(buff, ptr) != 0 )
{//Ecc4Decoder will do Ecc4Encoder first in the internal. If the content of ptr != the parity that was generated by Ecc4Encoder
sysprintf("Software ECC4 decoder not match.. Do encode \n");
sysprintf("Error bit number %d \n", u32ErrCount);
Ecc4Encoder(buff, u8Ecc4Parity, FALSE);
if( Ecc4Decoder(buff, u8Ecc4Parity) != 0 )
{
sysprintf("Software ECC4 decoder error\n");
}
}
DBG_PRINTF("Software ECC4 decoder 1st 512+16 Successful\n");
}
if(u8EccStatus)
pSM->bIsCheckECC = 1;
else
pSM->bIsCheckECC = 0;
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_EN); // enable ECC /* Why enable ECC if Software ECC ??*/
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
outpw(REG_SMCSR, (inpw(REG_SMCSR)&(~SMCR_PSIZE))|PSIZE_2K); // psize:2048
#else
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA(pSM, pageNo, 2048);
for (i=0; i<64; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
status = fmiSM_Read_2K(pSM, pageNo, (UINT32)buff);
#endif
}
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 4KB */
{
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA(pSM, pageNo, 4096);
// for (i=0; i<216; i++)
for (i=0; i<128; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
status = fmiSM_Read_4K(pSM, pageNo, (UINT32)buff);
}
else /* 512B */
{
#ifdef OPT_SOFTWARE_ECC
if(pSM->bIsCheckECC)
u8EccStatus = 1;
else
u8EccStatus = 0;
pSM->bIsCheckECC = 0;
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_ECC_EN); // disable ECC
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_REDUN_AUTO_WEN); // HW bug (if not to disable this bit, DMAC can't be complete)
status = fmiSM_Read_512(pSM, pageNo, (UINT32)buff);
#ifdef OPT_RW_RUNDANT_BY_DMA
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 0x10);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_REN);
#else
ptr = (char *)REG_SMRA_0;
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
#endif
#else
ptr = (char *)REG_SMRA_0;
fmiSM_Read_RA_512(pSM, pageNo, 0);
#ifdef OPT_RW_RUNDANT_BY_DMA
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 0x10);
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_REN);
#else
for (i=0; i<16; i++)
*ptr++ = inpw(REG_SMDATA) & 0xff;
#endif
status = fmiSM_Read_512(pSM, pageNo, (UINT32)buff);
#endif
#ifdef OPT_SOFTWARE_ECC
if (u8EccStatus)
{
ptr = (char *)REG_SMRA_0+6; //ptr is Logical address
u32ErrCount = Ecc4Decoder(buff, ptr);
if(u32ErrCount)
// if( Ecc4Decoder(buff, ptr) != 0 )
{//Ecc4Decoder will do Ecc4Encoder first in the internal. If the content of ptr != the parity that was generated by Ecc4Encoder
sysprintf("Software ECC4 decoder not match.. Do encode \n");
sysprintf("Error bit number %d \n", u32ErrCount);
Ecc4Encoder(buff, u8Ecc4Parity, FALSE);
if( Ecc4Decoder(buff, u8Ecc4Parity) != 0 )
{
sysprintf("Software ECC4 decoder error\n");
// DBG_PRINTF("Software ECC4 decoder error\n");
// while(1);
}
}
DBG_PRINTF("Software ECC4 decoder Successful\n");
}
#endif
#ifdef OPT_SOFTWARE_ECC
if(u8EccStatus)
pSM->bIsCheckECC = 1;
else
pSM->bIsCheckECC = 0;
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_ECC_EN); // enable ECC /* Why enable ECC if Software ECC ??*/
outpw(REG_SMCSR, inpw(REG_SMCSR) | SMCR_REDUN_AUTO_WEN);
#endif
}
#ifdef DEBUG
if (status)
printf("read NAND page fail !!!\n");
#endif
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// restore to ECC8
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
// sysFlushCache(I_D_CACHE);
// sysInvalidCache();
return status;
}
static INT sicSMpwrite_BCH(INT chipSel, INT PBA, INT page, UINT8 *buff)
{
FMI_SM_INFO_T *pSM;
int pageNo;
int status=0;
// sysFlushCache(D_CACHE);
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM); //removed by mhuko
PBA += pSM->uLibStartBlock;
pageNo = PBA * pSM->uPagePerBlock + page;
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// set to ECC4 for Block 0-3
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
#ifdef _NAND_PAR_ALC_
status = fmiSM_Write_2K_ALC(pSM, pageNo, 0, (UINT32)buff);
#else
status = fmiSM_Write_2K_BCH(pSM, pageNo, 0, (UINT32)buff);
#endif
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 2KB */
{
#ifdef _NAND_PAR_ALC_
status = fmiSM_Write_4K_ALC(pSM, pageNo, 0, (UINT32)buff);
#else
status = fmiSM_Write_4K(pSM, pageNo, 0, (UINT32)buff);
#endif
}
else /* 512B */
status = fmiSM_Write_512_BCH(pSM, pageNo, (UINT32)buff);
#ifdef DEBUG
if (status)
printf("write NAND page fail !!!\n");
#endif
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// restore to ECC8
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
return status;
}
static INT sicSMpwrite(INT chipSel, INT PBA, INT page, UINT8 *buff)
//INT sicSMpwrite(INT chipSel, INT PBA, INT page, UINT8 *buff)
{
FMI_SM_INFO_T *pSM;
int pageNo;
int status=0;
// sysFlushCache(D_CACHE);
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM); //removed by mhuko
PBA += pSM->uLibStartBlock;
pageNo = PBA * pSM->uPagePerBlock + page;
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// set to ECC4 for Block 0-3
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T4); // BCH_4 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
#ifdef _NAND_PAR_ALC_
status = fmiSM_Write_2K_ALC(pSM, pageNo, 0, (UINT32)buff);
#else
#ifdef OPT_SOFTWARE_WRITE_2KNAND_ECC
status = fmiSM_Write_2K_SECC(pSM, pageNo, 0, (UINT32)buff);
#else
status = fmiSM_Write_2K_BCH(pSM, pageNo, 0, (UINT32)buff);
#endif
#endif
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 2KB */
{
#ifdef _NAND_PAR_ALC_
status = fmiSM_Write_4K_ALC(pSM, pageNo, 0, (UINT32)buff);
#else
status = fmiSM_Write_4K(pSM, pageNo, 0, (UINT32)buff);
#endif
}
else /* 512B */
status = fmiSM_Write_512_SECC(pSM, pageNo, (UINT32)buff);
#ifdef DEBUG
if (status)
printf("write NAND page fail !!!\n");
#endif
#ifdef OPT_FIRST_4BLOCKS_ECC4
if (PBA <= 3)
{
// restore to ECC8
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
{
if (pSM->bIsNandECC8 == TRUE)
{
outpw(REG_SMCSR, inpw(REG_SMCSR) & ~SMCR_BCH_TSEL);
outpw(REG_SMCSR, inpw(REG_SMCSR) | BCH_T8); // BCH_8 is selected
outpw(REG_SMREAREA_CTL, (inpw(REG_SMREAREA_CTL) & ~SMRE_REA128_EXT) | 64); // Redundant area size
}
}
}
#endif
return status;
}
static INT sicSM_is_page_dirty(INT chipSel, INT PBA, INT page)
{
FMI_SM_INFO_T *pSM;
int pageNo;
UINT8 data0, data1;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM); //removed by mhuko
PBA += pSM->uLibStartBlock;
pageNo = PBA * pSM->uPagePerBlock + page;
#ifdef OPT_SOFTWARE_WRITE_2KNAND_ECC
if (pSM == pSM0)
{
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
fmiSM_Read_RA(pSM, pageNo, 2050);
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 4KB */
fmiSM_Read_RA(pSM, pageNo, 4098);
else if (pSM->nPageSize == NAND_PAGE_8KB) /* 8KB */
fmiSM_Read_RA(pSM, pageNo, 8194);
else /* 512B */
fmiSM_Read_RA_512(pSM, pageNo, 2);
}
else
{
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
fmiSM_Read_RA(pSM, pageNo, 514);
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 4KB */
fmiSM_Read_RA(pSM, pageNo, 4098);
else if (pSM->nPageSize == NAND_PAGE_8KB) /* 8KB */
fmiSM_Read_RA(pSM, pageNo, 8194);
else /* 512B */
fmiSM_Read_RA_512(pSM, pageNo, 2);
}
#else
if (pSM->nPageSize == NAND_PAGE_2KB) /* 2KB */
fmiSM_Read_RA(pSM, pageNo, 2050);
else if (pSM->nPageSize == NAND_PAGE_4KB) /* 4KB */
fmiSM_Read_RA(pSM, pageNo, 4098);
else if (pSM->nPageSize == NAND_PAGE_8KB) /* 8KB */
fmiSM_Read_RA(pSM, pageNo, 8194);
else /* 512B */
fmiSM_Read_RA_512(pSM, pageNo, 2);
#endif
data0 = inpw(REG_SMDATA);
data1 = inpw(REG_SMDATA);
if (pSM->nPageSize == NAND_PAGE_512B) /* 512B */
fmiSM_Reset(pSM);
//mhkuo
// if ((data0 == 0) && (data1 == 0x00))
// if ((data0 == 0) || (data1 == 0x00))
if (data0 == 0x00)
return 1; // used page
else if (data0 != 0xff)
return 1; // used page
return 0; // un-used page
}
static INT sicSM_is_valid_block(INT chipSel, INT PBA)
{
FMI_SM_INFO_T *pSM;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
PBA += pSM->uLibStartBlock;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM);
if (fmiNormalCheckBlock(pSM, PBA))
{
#ifdef DEBUG
printf("invalid block %d\n", PBA);
#endif
return 0;
}
else
return 1; // valid block
}
#ifdef OPT_MARK_BAD_BLOCK_WHILE_ERASE_FAIL
static INT sicSMMarkBadBlock_WhileEraseFail(FMI_SM_INFO_T *pSM, UINT32 BlockNo)
{
UINT32 uSector, ucColAddr;
/* check if MLC NAND */
if (pSM->bIsMLCNand == TRUE)
{
uSector = (BlockNo+1) * pSM->uPagePerBlock - 1; // write last page
if (pSM->nPageSize == NAND_PAGE_2KB)
{
ucColAddr = 2048; // write 2048th byte
}
else if (pSM->nPageSize == NAND_PAGE_4KB)
{
ucColAddr = 4096; // write 4096th byte
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xff); // CA8 - CA11
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMDATA, 0xf0); // mark bad block (use 0xf0 instead of 0x00 to differ from Old (Factory) Bad Blcok Mark)
outpw(REG_SMCMD, 0x10);
if (! fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
fmiSM_Reset(pSM);
return 0;
}
/* SLC check the 2048 byte of 1st or 2nd page per block */
else // SLC
{
uSector = BlockNo * pSM->uPagePerBlock; // write lst page
if (pSM->nPageSize == NAND_PAGE_2KB)
{
ucColAddr = 2048; // write 2048th byte
}
else if (pSM->nPageSize == NAND_PAGE_4KB)
{
ucColAddr = 4096; // write 4096th byte
}
else if (pSM->nPageSize == NAND_PAGE_512B)
{
ucColAddr = 0; // write 4096th byte
goto _mark_512;
}
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, (ucColAddr >> 8) & 0xff); // CA8 - CA11
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMDATA, 0xf0); // mark bad block (use 0xf0 instead of 0x00 to differ from Old (Factory) Bad Blcok Mark)
outpw(REG_SMCMD, 0x10);
if (! fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
fmiSM_Reset(pSM);
return 0;
_mark_512:
outpw(REG_SMCMD, 0x50); // point to redundant area
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, ucColAddr); // CA0 - CA7
outpw(REG_SMADDR, uSector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((uSector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (uSector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((uSector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMDATA, 0xf0); // 512
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xf0); // 516
outpw(REG_SMDATA, 0xf0); // 517
outpw(REG_SMCMD, 0x10);
if (! fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
fmiSM_Reset(pSM);
return 0;
}
}
#endif // OPT_MARK_BAD_BLOCK_WHILE_ERASE_FAIL
INT sicSMMarkBadBlock(FMI_SM_INFO_T *pSM, UINT32 BlockNo)
{
UINT32 sector, column;
/* page 0 */
sector = BlockNo * pSM->uPagePerBlock;
column = 512;
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, column); // CA0 - CA7
outpw(REG_SMADDR, (column >> 8) & 0x1f); // CA8 - CA12
outpw(REG_SMADDR, sector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((sector >> 8) & 0xff)|0x80000000); // PA8 - PA15
else
{
outpw(REG_SMADDR, (sector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((sector >> 16) & 0xff)|0x80000000); // PA16 - PA17
}
outpw(REG_SMDATA, 0xf0); // 512
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xf0); // 516
outpw(REG_SMDATA, 0xf0); // 517
outpw(REG_SMCMD, 0x10);
if (! fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
fmiSM_Reset(pSM);
/* page 1 */
sector++;
// send command
outpw(REG_SMCMD, 0x80); // serial data input command
outpw(REG_SMADDR, column); // CA0 - CA7
outpw(REG_SMADDR, (column >> 8) & 0x1f); // CA8 - CA12
outpw(REG_SMADDR, sector & 0xff); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((sector >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, (sector >> 8) & 0xff); // PA8 - PA15
outpw(REG_SMADDR, ((sector >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMDATA, 0xf0); // 512
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xff);
outpw(REG_SMDATA, 0xf0); // 516
outpw(REG_SMDATA, 0xf0); // 517
outpw(REG_SMCMD, 0x10);
if (! fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
fmiSM_Reset(pSM);
return 0;
}
static INT sicSMChangeBadBlockMark(INT chipSel)
{
int i, status=0;
FMI_SM_INFO_T *pSM;
_fmi_pSMBuffer = (UINT8 *)((UINT32)_fmi_ucSMBuffer | 0x80000000);
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, 0x08);
fmiSM_Initial(pSM);
//#ifndef OPT_FA93
#ifdef OPT_SOFTWARE_WRITE_2KNAND_ECC
// scan all nand chip
if (pSM == pSM1)
{
for (i=1; i<=pSM->uBlockPerFlash; i++)
{
if (fmiNormalCheckBlock(pSM, i)) // bad block
{
if (pSM->nPageSize == NAND_PAGE_2KB)
{
if (sicSMMarkBadBlock(pSM, i) < 0)
return FMI_SM_MARK_BAD_BLOCK_ERR;
}
}
}
}
#endif
/* read physical block 0 - image information */
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
if (!chipSel)
status = sicSMpread_BCH(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
else
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#else
// status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_ucSMBuffer);
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#endif
if (status < 0)
return status;
/* write specific mark */
_fmi_ucSMBuffer[pSM->nPageSize-6] = '5';
_fmi_ucSMBuffer[pSM->nPageSize-5] = '5';
_fmi_ucSMBuffer[pSM->nPageSize-4] = '0';
_fmi_ucSMBuffer[pSM->nPageSize-3] = '0';
_fmi_ucSMBuffer[pSM->nPageSize-2] = '9';
_fmi_ucSMBuffer[pSM->nPageSize-1] = '1';
// remove write "550091" in FA93
// sicSMpwrite(chipSel, 0, pSM->uPagePerBlock-1, _fmi_ucSMBuffer);
// status = sicSMpwrite(chipSel, 0, pSM->uPagePerBlock-1, _fmi_ucSMBuffer); //mhkuo@20100730
#ifdef OPT_SOFTWARE_WRITE_2KNAND_ECC
if (pSM == pSM1)
{
if (pSM->nPageSize == NAND_PAGE_2KB)
status = sicSMpwrite(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer); //mhkuo@20100730
}
#endif
return status;
}
//static INT sicSMblock_erase(INT chipSel, INT PBA)
INT sicSMblock_erase(INT chipSel, INT PBA)
{
FMI_SM_INFO_T *pSM;
UINT32 page_no;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
PBA += pSM->uLibStartBlock;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM);
if (fmiCheckInvalidBlock(pSM, PBA) != 1)
// if (1)
{
page_no = PBA * pSM->uPagePerBlock; // get page address
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
#ifdef DEBUG
printf("erase: error sector !!\n");
#endif
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
outpw(REG_SMCMD, 0x60); // erase setup command
outpw(REG_SMADDR, (page_no & 0xff)); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((page_no >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, ((page_no >> 8) & 0xff)); // PA8 - PA15
outpw(REG_SMADDR, ((page_no >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0xd0); // erase command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("sicSMblock_erase error!!\n");
#endif
#ifdef OPT_MARK_BAD_BLOCK_WHILE_ERASE_FAIL
#ifdef OPT_SOFTWARE_WRITE_2KNAND_ECC
if ( (pSM == pSM1)&&(pSM->nPageSize == NAND_PAGE_2KB) )
{
if (sicSMMarkBadBlock(pSM, PBA) < 0)
return FMI_SM_MARK_BAD_BLOCK_ERR;
}
else
sicSMMarkBadBlock_WhileEraseFail(pSM,PBA);
#else
sicSMMarkBadBlock_WhileEraseFail(pSM,PBA);
#endif
#endif
return FMI_SM_STATUS_ERR;
}
}
else
return FMI_SM_INVALID_BLOCK;
return 0;
}
//static INT sicSMblock_erase(INT chipSel, INT PBA)
INT sicSMblock_erase_test(INT chipSel, INT PBA)
{
FMI_SM_INFO_T *pSM;
UINT32 page_no;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, 0x08);
fmiSM_Initial(pSM);
page_no = PBA * pSM->uPagePerBlock; // get page address
/* clear R/B flag */
if (pSM == pSM0)
{
while(!(inpw(REG_SMISR) & SMISR_RB0));
outpw(REG_SMISR, SMISR_RB0_IF);
}
else
{
while(!(inpw(REG_SMISR) & SMISR_RB1));
outpw(REG_SMISR, SMISR_RB1_IF);
}
if (inpw(REG_SMISR) & SMISR_ECC_FIELD_IF) /* ECC_FLD_IF */
{
#ifdef DEBUG
printf("erase: error sector !!\n");
#endif
outpw(REG_SMISR, SMISR_ECC_FIELD_IF);
}
outpw(REG_SMCMD, 0x60); // erase setup command
outpw(REG_SMADDR, (page_no & 0xff)); // PA0 - PA7
if (!pSM->bIsMulticycle)
outpw(REG_SMADDR, ((page_no >> 8) & 0xff)|EOA_SM); // PA8 - PA15
else
{
outpw(REG_SMADDR, ((page_no >> 8) & 0xff)); // PA8 - PA15
outpw(REG_SMADDR, ((page_no >> 16) & 0xff)|EOA_SM); // PA16 - PA17
}
outpw(REG_SMCMD, 0xd0); // erase command
if (!fmiSMCheckRB(pSM))
return FMI_SM_RB_ERR;
outpw(REG_SMCMD, 0x70); // status read command
if (inpw(REG_SMDATA) & 0x01) // 1:fail; 0:pass
{
#ifdef DEBUG
printf("sicSMblock_erase error!!\n");
#endif
return FMI_SM_STATUS_ERR;
}
return 0;
}
static INT sicSMchip_erase(INT chipSel)
{
int i, status=0;
FMI_SM_INFO_T *pSM;
sicSMselect(chipSel);
if (chipSel == 0)
pSM = pSM0;
else
pSM = pSM1;
// enable SM
outpw(REG_FMICR, FMI_SM_EN);
fmiSM_Initial(pSM);
// erase all chip
for (i=0; i<=pSM->uBlockPerFlash; i++)
{
status = sicSMblock_erase(chipSel, i);
#ifdef DEBUG
if (status < 0)
printf("SM block erase fail <%d>!!\n", i);
#endif
}
// return status;
return 0;
}
/* driver function */
INT nandInit0(NDISK_T *NDISK_info)
{
return (sicSMInit(0, NDISK_info));
}
INT nandpread0(INT PBA, INT page, UINT8 *buff)
{
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
return (sicSMpread_BCH(0, PBA, page, buff));
#else
return (sicSMpread(0, PBA, page, buff));
#endif
}
INT nandpwrite0(INT PBA, INT page, UINT8 *buff)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
status = sicSMpwrite_BCH(0, PBA, page, buff);
#else
status = sicSMpwrite(0, PBA, page, buff);
#endif
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
return (sicSMpwrite_BCH(0, PBA, page, buff));
#else
return (sicSMpwrite(0, PBA, page, buff));
#endif
#endif
}
INT nand_is_page_dirty0(INT PBA, INT page)
{
return (sicSM_is_page_dirty(0, PBA, page));
}
INT nand_is_valid_block0(INT PBA)
{
return (sicSM_is_valid_block(0, PBA));
}
INT nand_block_erase0(INT PBA)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
status = sicSMblock_erase(0, PBA);
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
return (sicSMblock_erase(0, PBA));
#endif
}
INT nand_chip_erase0(VOID)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
status = sicSMchip_erase(0);
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
return (sicSMchip_erase(0));
#endif
}
INT nand_ioctl(INT param1, INT param2, INT param3, INT param4)
{
return 0;
}
INT fmiSMCheckBootHeader(INT chipSel, FMI_SM_INFO_T *pSM)
{
int fmiNandSysArea=0;
int volatile status, imageCount, i, block;
unsigned int *pImageList;
volatile int ii;
#define OPT_FOUR_BOOT_IMAGE
_fmi_pSMBuffer = (UINT8 *)((UINT32)_fmi_ucSMBuffer | 0x80000000);
pImageList = (UINT32 *)((UINT32)_fmi_ucSMBuffer | 0x80000000);
/* read physical block 0 - image information */
#ifdef OPT_FOUR_BOOT_IMAGE
for (ii=0; ii<4; ii++)
{
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
if (!chipSel)
status = sicSMpread_BCH(chipSel, ii, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
else
status = sicSMpread(chipSel, ii, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#else
status = sicSMpread(chipSel, ii, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#endif
if (!status)
{
if (((*(pImageList+0)) == 0x574255aa) && ((*(pImageList+3)) == 0x57425963))
break;
}
}
#else
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
if (!chipSel)
status = sicSMpread_BCH(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
else
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#else
// status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_ucSMBuffer);
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-1, _fmi_pSMBuffer);
#endif
#endif
if (status < 0)
return status;
/* check specific mark */
if (pSM->nPageSize != NAND_PAGE_512B)
{
if (((_fmi_ucSMBuffer[pSM->nPageSize-6]) == '5') && ((_fmi_ucSMBuffer[pSM->nPageSize-5]) == '5') &&
((_fmi_ucSMBuffer[pSM->nPageSize-4]) == '0') && ((_fmi_ucSMBuffer[pSM->nPageSize-3]) == '0') &&
((_fmi_ucSMBuffer[pSM->nPageSize-2]) == '9') && ((_fmi_ucSMBuffer[pSM->nPageSize-1]) == '1'))
{
_fmi_bIsNandFirstAccess = FALSE;
}
else
{
sicSMChangeBadBlockMark(chipSel);
}
}
if (((*(pImageList+0)) == 0x574255aa) && ((*(pImageList+3)) == 0x57425963))
{
fmiNandSysArea = *(pImageList+1);
}
if ((fmiNandSysArea != 0xFFFFFFFF) && (fmiNandSysArea != 0))
{
pSM->uLibStartBlock = (fmiNandSysArea / pSM->uSectorPerBlock) + 1;
}
else
{
/* read physical block 0 - image information */
#ifdef OPT_FOUR_BOOT_IMAGE
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
for (ii=0; ii<4; ii++)
{
if (!chipSel)
status = sicSMpread_BCH(chipSel, ii, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
else
status = sicSMpread(chipSel, ii, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
if (!status)
{
if (((*(pImageList+0)) == 0x574255aa) && ((*(pImageList+3)) == 0x57425963))
break;
}
}
#else
for (ii=0; ii<4; ii++)
{
status = sicSMpread(chipSel, ii, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
if (!status)
{
if (((*(pImageList+0)) == 0x574255aa) && ((*(pImageList+3)) == 0x57425963))
break;
}
}
#endif
#else
#ifdef OPT_BCH_PLUS_SECC_FOR_NAND512
if (!chipSel)
status = sicSMpread_BCH(chipSel, 0, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
else
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
#else
// status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-2, _fmi_ucSMBuffer);
status = sicSMpread(chipSel, 0, pSM->uPagePerBlock-2, _fmi_pSMBuffer);
#endif
#endif
if (status < 0)
return status;
if (((*(pImageList+0)) == 0x574255aa) && ((*(pImageList+3)) == 0x57425963))
{
imageCount = *(pImageList+1);
/* pointer to image information */
pImageList = pImageList+4;
for (i=0; i<imageCount; i++)
{
block = (*(pImageList + 1) & 0xFFFF0000) >> 16;
if (block > pSM->uLibStartBlock)
pSM->uLibStartBlock = block;
/* pointer to next image */
// pImageList = pImageList+12;
if (chipSel ==0)
pImageList = pImageList+12;
else
pImageList = pImageList+8;
}
pSM->uLibStartBlock++;
}
}
return 0;
}
VOID fmiSMClose(INT chipSel)
{
if (chipSel == 0)
{
_nand_init0 = 0;
if (pSM0 != 0)
{
free(pSM0);
pSM0 = 0;
}
}
else
{
_nand_init1 = 0;
if (pSM1 != 0)
{
free(pSM1);
pSM1 = 0;
}
}
if ((_nand_init0 == 0) && (_nand_init1 == 0))
{
outpw(REG_SMCSR, inpw(REG_SMCSR)|0x06000000); // CS-0/CS-1 -> HIGH
outpw(REG_SMISR, 0xfff);
outpw(REG_FMICR, 0x00);
outpw(REG_GPDFUN, inpw(REG_GPDFUN) & ~0x0003FC00); // enable NAND NWR/NRD/RB0/RB1 pins
outpw(REG_GPEFUN, inpw(REG_GPEFUN) & ~0x00FF0000); // enable NAND ALE/CLE/CS0/CS1 pins
}
}
INT nandInit1(NDISK_T *NDISK_info)
{
return (sicSMInit(1, NDISK_info));
}
INT nandpread1(INT PBA, INT page, UINT8 *buff)
{
return (sicSMpread(1, PBA, page, buff));
}
INT nandpwrite1(INT PBA, INT page, UINT8 *buff)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
status = sicSMpwrite(1, PBA, page, buff);
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
return (sicSMpwrite(1, PBA, page, buff));
#endif
}
INT nand_is_page_dirty1(INT PBA, INT page)
{
return (sicSM_is_page_dirty(1, PBA, page));
}
INT nand_is_valid_block1(INT PBA)
{
return (sicSM_is_valid_block(1, PBA));
}
INT nand_block_erase1(INT PBA)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
status = sicSMblock_erase(1, PBA);
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
return (sicSMblock_erase(1, PBA));
#endif
}
INT nand_chip_erase1(VOID)
{
#ifdef OPT_SW_WP
int status;
UINT32 ii;
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) | 0x0080); // port A7 high (WP)
for (ii=0; ii<SW_WP_DELAY_LOOP; ii++);
status = sicSMchip_erase(1);
outpw(REG_GPIOA_DOUT, inpw(REG_GPIOA_DOUT) & ~ 0x0080); // port A7 low (WP)
return status;
#else
return (sicSMchip_erase(1));
#endif
}
<file_sep>/LOADER/NandLoader/user_define/user_define_func.c
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2013 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#ifdef __USER_DEFINE_FUNC
#include "user_define_func.h"
void initVPostShowLogo(void);
INT32 vpostLCMInit(PLCDFORMATEX plcdformatex, UINT32 *pFramebuf);
LCDFORMATEX lcdInfo;
/*-----------------------------------------------------------------------------------*/
/* The entry point of User Define Function that called by NandLoader. */
/*-----------------------------------------------------------------------------------*/
void user_define_func()
{
//--- This is a sample code for user define function.
//--- This sample code will show Logo to panel on Nuvoton FA93 Demo Board.
initVPostShowLogo();
}
static UINT32 bIsInitVpost=FALSE;
void initVPostShowLogo(void)
{
if(bIsInitVpost==FALSE)
{
bIsInitVpost = TRUE;
lcdInfo.ucVASrcFormat = DRVVPOST_FRAME_RGB565;
lcdInfo.nScreenWidth = PANEL_WIDTH;
lcdInfo.nScreenHeight = PANEL_HEIGHT;
vpostLCMInit(&lcdInfo, (UINT32*)FB_ADDR);
}
}
#else
/*-----------------------------------------------------------------------------------*/
/* The entry point of User Define Function that called by NandLoader. */
/*-----------------------------------------------------------------------------------*/
void user_define_func()
{
//--- Keep empty if user define nothing for User Define Function.
}
#endif // end of #ifdef __USER_DEFINE_FUNC
<file_sep>/SIC_SECC/Src/Ecc4Decoder_HW.c
//#include "Platform.h"
#include "wblib.h"
#define FALSE 0
#define TRUE 1
#define GetBit(nValue, bit) (((nValue)>>(bit))&1)
/*
unsigned char g_ucSyndromeF1Lookup[1024];
unsigned char g_ucSyndromeF2Lookup[1024], g_ucSyndromeF3Lookup[1024];
unsigned char g_ucSyndromeF4Lookup[1024], g_ucSyndromeF5Lookup[1024];
unsigned char g_ucSyndromeF6Lookup[1024], g_ucSyndromeF7Lookup[1024];
*/
#include "Ecc4DecoderSyndromeFxLookup.h"
/*
unsigned char g_au8CorrectLookupR0[1024], g_au8CorrectLookupR1[1024];
unsigned char g_au8CorrectLookupR2[1024], g_au8CorrectLookupR3[1024];
unsigned short int g_au16CorrectLookupR4[1024], g_au16CorrectLookupR5[1024];
unsigned short int g_au16CorrectLookupR6[1024], g_au16CorrectLookupR7[1024];
unsigned short int g_au16CorrectInitLookupR0[1024], g_au16CorrectInitLookupR1[1024];
unsigned short int g_au16CorrectInitLookupR2[1024], g_au16CorrectInitLookupR3[1024];
unsigned short int g_au16CorrectInitLookupR4[1024], g_au16CorrectInitLookupR5[1024];
unsigned short int g_au16CorrectInitLookupR6[1024], g_au16CorrectInitLookupR7[1024];
*/
#include "Ecc4DecoderCorrectLookup.h"
/*
unsigned short int g_au16RiBmLookup[1024];
*/
#include "Ecc4DecoderRiBmLookup.h"
extern unsigned int g_p[8];
//extern void Ecc4Encoder(unsigned char *pacEncodeData, unsigned char *pacEc4ParityByte, bool bDecode);
// input - p_in[8] : each element contain 10 bits
// output - s[8]: each element contain 10 bits
void syndrome(unsigned int *p_in, unsigned int *s);
// input - s[8]: each element contain 10 bits
// output- L[5]: each element contain 10 bits
// output- o[4]: each element contain 10 bits
void riBM(unsigned int *s, unsigned int *L, unsigned int *o);
// input - L[5]: each element contain 10 bits
// input - o[4]: each element contain 10 bits
// output- err_addr[4]: each element contain 10 bits
// output- err_data[4]: each element contain 8 bits
unsigned int correct(unsigned int *L, unsigned int *o, unsigned int *err_addr, unsigned char *err_data);
unsigned int Ecc4Decoder(unsigned char *pacEncodeData, unsigned char *pacEcc4ParityByte)
{
unsigned int i;
unsigned int s[8];
unsigned int L[5];
unsigned int o[4];
unsigned int nErrCount;
unsigned int auiErrorAddr[4];
unsigned char acCorrectData[4];
Ecc4Encoder( pacEncodeData, pacEcc4ParityByte, TRUE );
for( i = 0; i < 8; i ++ )
{
if ( g_p[i] != 0 )
{
syndrome(g_p, s);
riBM(s, L, o);
nErrCount = correct(L, o, &auiErrorAddr[0], &acCorrectData[0]);
if ( nErrCount && (nErrCount <= 4) )
{
for( i = 0; i < nErrCount; i ++ )
pacEncodeData[auiErrorAddr[i]] ^= acCorrectData[i];
}
return nErrCount;
}
}
return 0;
}
void syndrome(unsigned int *p_in, unsigned int *s)
{
unsigned int _s[8], f[8], clock, Xorf, i;
/*
{f7, f6, f5, f4, f3, f2, f1, f0} <= p_in[79:0];
{_s7, _s6, _s5, _s4, _s3, _s2, _s1, _s0} <= {8{10'h0}};
*/
for(i = 0; i<= 7; i++)
{
f[i] = p_in[i];
_s[i] = 0;
}
for(clock = 0; clock < 10; clock++)
{
/* _s0 <= {_s0[8:0],{f1[9]^f1[8]^f1[4]^f1[1]^f2[7]^f2[6]^f2[3]^f2[0]^f3[9]^f3[7]^f3[6]^
f3[5]^f3[3]^f3[2]^f3[1]^f3[0]^f4[8]^f4[7]^f4[4]^f4[3]^f4[1]^f5[6]^f5[4]^f5[2]^
f5[1]^f5[0]^f6[9]^f6[8]^f6[7]^f6[5]^f6[4]^f6[2]^f6[0]^f7[9]^f7[3]^f7[1]^f7[0]}};
_s1<= {_s1[8:0],{f1[8]^f1[7]^f1[3]^f1[0]^f2[8]^f2[4]^f2[1]^f3[9]^f3[8]^f3[7]^f3[5]^
f3[3]^f3[2]^f3[0]^f4[9]^f4[7]^f4[6]^f4[3]^f4[0]^f5[9]^f5[7]^f5[5]^f5[4]^f5[3]^
f5[2]^f5[1]^f6[9]^f6[8]^f6[5]^f6[4]^f6[2]^f7[6]^f7[4]^f7[2]^f7[1]^f7[0]}};
_s2<= {_s2[8:0],{f1[9]^f1[7]^f1[2]^f2[9]^f2[2]^f3[9]^f3[7]^f3[5]^f3[2]^f3[0]^f4[9]^
f4[5]^f4[2]^f5[9]^f5[8]^f5[7]^f5[5]^f5[3]^f5[2]^f5[0]^f6[9]^f6[8]^f6[5]^f6[2]^
f7[9]^f7[7]^f7[6]^f7[5]^f7[3]^f7[2]^f7[1]^f7[0]}};
_s3<= {_s3[8:0],{f1[8]^f1[6]^f1[1]^f2[7]^f2[0]^f3[9]^f3[7]^f3[2]^f4[8]^f4[1]^f5[8]^
f5[7]^f5[3]^f5[0]^f6[9]^f6[2]^f7[9]^f7[8]^f7[4]^f7[1]}};
_s4<= {_s4[8:0],{f1[7]^f1[5]^f1[0]^f2[8]^f3[9]^f3[4]^f4[7]^f5[8]^f5[3]^f6[6]^f7[7]^f7[2]}};
_s5<= {_s5[8:0],{f1[9]^f1[4]^f2[6]^f3[6]^f3[1]^f4[3]^f5[8]^f5[5]^f5[3]^f6[0]^f7[5]^
f7[2]^f7[0]}};
_s6<= {_s6[8:0],{f1[8]^f1[3]^f2[4]^f3[8]^f3[5]^f3[3]^f4[9]^f4[6]^f5[8]^f5[5]^f5[3]^
f5[0]^f6[4]^f6[1]^f7[8]^f7[3]^f7[2]^f7[0]}};
_s7<= {_s7[8:0],{f1[7]^f1[2]^f2[2]^f3[5]^f3[2]^f3[0]^f4[5]^f4[2]^f5[8]^f5[3]^f5[2]^
f5[0]^f6[8]^f6[2]^f7[6]^f7[5]^f7[2]^f7[1]^f7[0]}}; */
Xorf =
g_ucSyndromeF1Lookup[f[1]]^
g_ucSyndromeF2Lookup[f[2]]^
g_ucSyndromeF3Lookup[f[3]]^
g_ucSyndromeF4Lookup[f[4]]^
g_ucSyndromeF5Lookup[f[5]]^
g_ucSyndromeF6Lookup[f[6]]^
g_ucSyndromeF7Lookup[f[7]];
_s[0] = (_s[0]<<1)|((Xorf>>0)&1);
_s[1] = (_s[1]<<1)|((Xorf>>1)&1);
_s[2] = (_s[2]<<1)|((Xorf>>2)&1);
_s[3] = (_s[3]<<1)|((Xorf>>3)&1);
_s[4] = (_s[4]<<1)|((Xorf>>4)&1);
_s[5] = (_s[5]<<1)|((Xorf>>5)&1);
_s[6] = (_s[6]<<1)|((Xorf>>6)&1);
_s[7] = (_s[7]<<1)|((Xorf>>7)&1);
/* f1<= #1 {f1[8:0],(f1[9]^f1[6])};
f2<= #1 {f2[8:0],(f2[9]^f2[6])};
f3<= #1 {f3[8:0],(f3[9]^f3[6])};
f4<= #1 {f4[8:0],(f4[9]^f4[6])};
f5<= #1 {f5[8:0],(f5[9]^f5[6])};
f6<= #1 {f6[8:0],(f6[9]^f6[6])};
f7<= #1 {f7[8:0],(f7[9]^f7[6])};*/
f[1] = ((f[1]<<1)|(((f[1]>>9)^(f[1]>>6))&1))&0x3ff;
f[2] = ((f[2]<<1)|(((f[2]>>9)^(f[2]>>6))&1))&0x3ff;
f[3] = ((f[3]<<1)|(((f[3]>>9)^(f[3]>>6))&1))&0x3ff;
f[4] = ((f[4]<<1)|(((f[4]>>9)^(f[4]>>6))&1))&0x3ff;
f[5] = ((f[5]<<1)|(((f[5]>>9)^(f[5]>>6))&1))&0x3ff;
f[6] = ((f[6]<<1)|(((f[6]>>9)^(f[6]>>6))&1))&0x3ff;
f[7] = ((f[7]<<1)|(((f[7]>>9)^(f[7]>>6))&1))&0x3ff;
}
/*
assign s0 = _s0 ^ f0;
assign s1 = _s1 ^ f0;
assign s2 = _s2 ^ f0;
assign s3 = _s3 ^ f0;
assign s4 = _s4 ^ f0;
assign s5 = _s5 ^ f0;
assign s6 = _s6 ^ f0;
assign s7 = _s7 ^ f0;
*/
s[0] = (_s[0]^f[0])&0x3ff;
s[1] = (_s[1]^f[0])&0x3ff;
s[2] = (_s[2]^f[0])&0x3ff;
s[3] = (_s[3]^f[0])&0x3ff;
s[4] = (_s[4]^f[0])&0x3ff;
s[5] = (_s[5]^f[0])&0x3ff;
s[6] = (_s[6]^f[0])&0x3ff;
s[7] = (_s[7]^f[0])&0x3ff;
}
unsigned int _10BitXor(unsigned int x )
{
unsigned int nXor, count;
nXor = x&1;
for( count = 1; count < 10; count++ )
{
x>>=1;
nXor = nXor ^ x;
}
return nXor&1;
}
void riBM(unsigned int *s, unsigned int *L, unsigned int *oo)
{
unsigned int count, clock;
unsigned int o[8]; // 10 bits for each element
unsigned int fmulo[9]; // 10 bits for each element
unsigned int fmult[8]; // 10 bits for each element
unsigned int fmull[5]; // 10 bits for each element
unsigned int fmulb[4]; // 10 bits for each element
unsigned int B_val[9]; // 10 bits for each element
unsigned int theta[8]; // 10 bits for each element
unsigned int gamma, delta; // 10 bits for each element
unsigned int K_val; // 4 bits
unsigned int enb1, enb2;
unsigned int i;
{
/*
gamma <= 10'h200;
K_val <= 4'h0;
B_val0 <= 10'h004;
{B_val4, B_val3, B_val2, B_val1} <= {4{10'h0}};
{theta3, theta2, theta1, theta0} <= {s3, s2, s1, s0};
{theta7, theta6, theta5, theta4} <= {s7, s6, s5, s4};
L0 <= 10'h004;
{L4, L3, L2, L1} <= {4{10'h0}};
{o7, o6, o5, o4, o3, o2, o1, o0} <= {s7, s6, s5, s4, s3, s2, s1, s0};
*/
gamma = 0x200;
K_val = 0x0;
B_val[0] = 0x4;
B_val[1] = 0;
B_val[2] = 0;
B_val[3] = 0;
B_val[4] = 0;
L[0] = 0x4;
L[1] = 0;
L[2] = 0;
L[3] = 0;
L[4] = 0;
for( i = 0; i <= 7; i ++)
o[i] = theta[i] = s[i];
}
for(clock = count = 0; clock < 88; clock++)
{
{
/*
wire enb1 = riBM_en & (|count);
wire enb2 = riBM_en & ~(|count);
*/
enb1 = (count!=0);
enb2 = !enb1;
}
{
/*
if(enb1)
begin
L0 <= {L0[8:0], ^(gamma&fmull0)};
L1 <= {L1[8:0], ^((gamma&fmull1)^(delta&fmulb0))};
L2 <= {L2[8:0], ^((gamma&fmull2)^(delta&fmulb1))};
L3 <= {L3[8:0], ^((gamma&fmull3)^(delta&fmulb2))};
L4 <= {L4[8:0], ^((gamma&fmull4)^(delta&fmulb3))};
o0 <= {o0[8:0], ^((gamma&fmulo1)^(delta&fmult0))};
o1 <= {o1[8:0], ^((gamma&fmulo2)^(delta&fmult1))};
o2 <= {o2[8:0], ^((gamma&fmulo3)^(delta&fmult2))};
o3 <= {o3[8:0], ^((gamma&fmulo4)^(delta&fmult3))};
o4 <= {o4[8:0], ^((gamma&fmulo5)^(delta&fmult4))};
o5 <= {o5[8:0], ^((gamma&fmulo6)^(delta&fmult5))};
o6 <= {o6[8:0], ^((gamma&fmulo7)^(delta&fmult6))};
o7 <= {o7[8:0], ^(delta&fmult7)};
end
*/
if ( enb1 )
{
L[0] = (L[0]<<1)+_10BitXor((gamma&fmull[0]));
L[1] = (L[1]<<1)+_10BitXor((gamma&fmull[1])^(delta&fmulb[0]));
L[2] = (L[2]<<1)+_10BitXor((gamma&fmull[2])^(delta&fmulb[1]));
L[3] = (L[3]<<1)+_10BitXor((gamma&fmull[3])^(delta&fmulb[2]));
L[4] = (L[4]<<1)+_10BitXor((gamma&fmull[4])^(delta&fmulb[3]));
o[0] = (o[0]<<1)+_10BitXor((gamma&fmulo[1])^(delta&fmult[0]));
o[1] = (o[1]<<1)+_10BitXor((gamma&fmulo[2])^(delta&fmult[1]));
o[2] = (o[2]<<1)+_10BitXor((gamma&fmulo[3])^(delta&fmult[2]));
o[3] = (o[3]<<1)+_10BitXor((gamma&fmulo[4])^(delta&fmult[3]));
o[4] = (o[4]<<1)+_10BitXor((gamma&fmulo[5])^(delta&fmult[4]));
o[5] = (o[5]<<1)+_10BitXor((gamma&fmulo[6])^(delta&fmult[5]));
o[6] = (o[6]<<1)+_10BitXor((gamma&fmulo[7])^(delta&fmult[6]));
o[7] = (o[7]<<1)+_10BitXor((delta&fmult[7]));
}
}
{
/*
if(enb2)
begin
if(|o0[9:0] && (~K_val[3]))
begin
{B_val4, B_val3, B_val2, B_val1, B_val0} <= {L4, L3, L2, L1, L0};
{theta3, theta2, theta1, theta0} <= {o4, o3, o2, o1};
{theta7, theta6, theta5, theta4} <= {10'h0, o7, o6, o5};
end
else
{B_val4, B_val3, B_val2, B_val1, B_val0} <= {B_val3, B_val2, B_val1, B_val0, 10'h0};
end
*/
/*
if(enb2)
begin
{fmull4, fmull3, fmull2, fmull1, fmull0} <= {L4, L3, L2, L1, L0};
{fmulb3, fmulb2, fmulb1, fmulb0} <= {B_val3, B_val2, B_val1, B_val0};
{fmulo3, fmulo2, fmulo1} <= {o3, o2, o1};
{fmulo7, fmulo6, fmulo5, fmulo4} <= {o7, o6, o5, o4};
{fmult3, fmult2, fmult1, fmult0} <= {theta3, theta2, theta1, theta0};
{fmult7, fmult6, fmult5, fmult4} <= {theta7, theta6, theta5, theta4};
delta <= {(o0[9]^o0[2]), (o0[7]^o0[3]^o0[0]), (o0[8]^o0[4]^o0[1]),
o0[5], o0[6], o0[7], o0[8], o0[9], (o0[7]^o0[0]), (o0[8]^o0[1])};
end
else if(enb1) // Step of riBM.1: Compute new L(x) and o(x) according to step riBM.1
begin
fmull0 <= {fmull0[8:0], (fmull0[9]^fmull0[6])};
fmull1 <= {fmull1[8:0], (fmull1[9]^fmull1[6])};
fmull2 <= {fmull2[8:0], (fmull2[9]^fmull2[6])};
fmull3 <= {fmull3[8:0], (fmull3[9]^fmull3[6])};
fmull4 <= {fmull4[8:0], (fmull4[9]^fmull4[6])};
fmulb0 <= {fmulb0[8:0], (fmulb0[9]^fmulb0[6])};
fmulb1 <= {fmulb1[8:0], (fmulb1[9]^fmulb1[6])};
fmulb2 <= {fmulb2[8:0], (fmulb2[9]^fmulb2[6])};
fmulb3 <= {fmulb3[8:0], (fmulb3[9]^fmulb3[6])};
fmulo1 <= {fmulo1[8:0], (fmulo1[9]^fmulo1[6])};
fmulo2 <= {fmulo2[8:0], (fmulo2[9]^fmulo2[6])};
fmulo3 <= {fmulo3[8:0], (fmulo3[9]^fmulo3[6])};
fmulo4 <= {fmulo4[8:0], (fmulo4[9]^fmulo4[6])};
fmulo5 <= {fmulo5[8:0], (fmulo5[9]^fmulo5[6])};
fmulo6 <= {fmulo6[8:0], (fmulo6[9]^fmulo6[6])};
fmulo7 <= {fmulo7[8:0], (fmulo7[9]^fmulo7[6])};
fmult0 <= {fmult0[8:0], (fmult0[9]^fmult0[6])};
fmult1 <= {fmult1[8:0], (fmult1[9]^fmult1[6])};
fmult2 <= {fmult2[8:0], (fmult2[9]^fmult2[6])};
fmult3 <= {fmult3[8:0], (fmult3[9]^fmult3[6])};
fmult4 <= {fmult4[8:0], (fmult4[9]^fmult4[6])};
fmult5 <= {fmult5[8:0], (fmult5[9]^fmult5[6])};
fmult6 <= {fmult6[8:0], (fmult6[9]^fmult6[6])};
fmult7 <= {fmult7[8:0], (fmult7[9]^fmult7[6])};
end
*/
if ( enb2 )
{
for( i = 0; i <=4; i++ )
fmull[i] = L[i];
for( i =0; i <=3; i++ )
fmulb[i] = B_val[i];
for( i = 1; i <=7; i++ )
fmulo[i] = o[i];
for( i = 0; i <= 7; i ++ )
fmult[i] = theta[i];
o[0] &= 0x3ff;
delta = g_au16RiBmLookup[o[0]];
if ( o[0] && (!(K_val&0x8)) )
{
for( i = 0; i <=4; i++ )
B_val[i] = L[i];
for( i = 0; i <= 6; i++ )
theta[i] = o[i+1];
theta[7] = 0;
}
else
{
for( i = 4; i >= 1; i-- )
B_val[i] = B_val[i-1];
B_val[0] = 0;
}
}
else if ( enb1 )
{
for( i = 0; i <= 4; i++ )
fmull[i] = (fmull[i]<<1)|(((fmull[i]>>9)^(fmull[i]>>6))&1);
for( i = 0; i <= 3; i++ )
fmulb[i] = (fmulb[i]<<1)|(((fmulb[i]>>9)^(fmulb[i]>>6))&1);
for( i = 1; i <= 7; i++ )
fmulo[i] = (fmulo[i]<<1)|(((fmulo[i]>>9)^(fmulo[i]>>6))&1);
for( i = 0; i <= 7; i++ )
fmult[i] = (fmult[i]<<1)|(((fmult[i]>>9)^(fmult[i]>>6))&1);
}
}
{
/*
if(riBM_en && (count==4'ha))
begin
if(|delta && (~K_val[3]))
begin
gamma <= delta;
K_val[3:0] <= ~K_val[3:0]; // K = -K - 1
end
else K_val <= K_val + 1'b1;
end
*/
/*
if(~riBM_en || (count==4'ha))
count <= 4'h0;
else if(riBM_en)
count <= count + 1'b1;
*/
if ( count == 0xa )
{
if ( delta && (!(K_val&(1<<3))) )
{
gamma = delta;
K_val = (~K_val)&0xf;
}
else
K_val ++;
count = 0;
}
else
count ++;
}
}
for( i = 0; i <= 3; i ++ )
oo[i] = o[i]&0x3ff;
for( i = 0; i <= 4; i++ )
L[i] &= 0x3ff;
}
unsigned int _2BitXor(unsigned int x )
{
unsigned int nXor;
nXor = x&1;
nXor = nXor ^ (x>>1);
return nXor&1;
}
// x: 10 bits
// y: 10 bits
// return z: 10 bits
unsigned int galoisdiv(unsigned int x, unsigned int y)
{
unsigned int count; // 5 bits
unsigned int state;
unsigned int z; // 10 bits
unsigned int div0, div1, _div1; // 10 bits
unsigned int div2, divy, _divy; // 11 bits
unsigned int clock, nBit10, nBit9, nBit7, nBit5, nBit2, nBit1;
/*
reg [10:0] div2, divy;
reg [9:0] div0, div1;
reg state;
reg [4:0] count;
wire [10:0] _divy;
wire [9:0] _div1;
*/
/* init
state <= 1'b0;
{z, div1, div0} <= {x, 10'h0, 10'h0};
//{divy, div2} <= {2{11'h0}};
div2 <= 11'h049;
divy <= {y, 1'b0};
*/
count = 0;
state = 0;
z = x;
div0 = div1 = 0;
div2 = 0x49;
divy = y <<1;
// Need 18 clock to complete
for( clock = 0; clock < 18; clock++ )
{
/*
assign _divy = {divy[9:6], divy[9]^divy[5]^divy[2], divy[4:3], divy[9], divy[1],
(divy[10]^divy[7]), (divy[9]^divy[2])};
assign _div1 = {div1[8:0], (div1[9]^div1[6])};
*/
nBit10= GetBit(divy,10);
nBit9 = GetBit(divy,9);
nBit7 = GetBit(divy,7);
nBit5 = GetBit(divy,5);
nBit2 = GetBit(divy,2);
nBit1 = GetBit(divy,1);
_divy = ((divy&0x3d8)<<1) | ((nBit9^nBit5^nBit2)<<6) | (nBit9<<3) | (nBit1<<2) | ((nBit10^nBit7)<<1) | (nBit9^nBit2);
_div1 = ((div1<<1)|(((div1>>9)^(div1>>6))&1))&0x3ff;
/*
if(~state)
begin
if(_divy[0])
begin
state <= ~state;
divy <= _divy ^ div2;
div1 <= z;
div2 <= _divy;
end
else {div1, divy} <= {_div1, _divy};
end
else
begin
if(~_divy[0])
begin
{div1, divy} <= {_div1, _divy};
if(count==1)
begin
z <= div0 ^ _div1;
div0 <= z;
state <= ~state;
end
end
else
begin
divy <= _divy ^ div2;
div1 <= _div1 ^ z;
if (count==1)
begin
z <= div0 ^ _div1 ^ z;
div0 <= z;
state <= ~state;
end
end
end
*/
/*
begin
if(~state) count <= count + 1'b1;
else count <= count - 1'b1;
end
*/
if (!state)
{
if ( _divy&1 )
{
state = !state;
divy = _divy ^ div2;
div1 = z;
div2 = _divy;
}
else
{
div1 = _div1;
divy = _divy;
}
count ++;
}
else
{
if ( !(_divy&1) )
{
div1 = _div1;
divy = _divy;
if(count==1)
{
unsigned int z_temp;
z_temp = z;
z = div0 ^ _div1;
div0 = z_temp;
state = !state;
}
}
else
{
divy = _divy ^ div2;
div1 = _div1 ^ z;
if (count==1)
{
unsigned int z_temp;
z_temp = z;
z = div0 ^ _div1 ^ z_temp;
div0 = z_temp;
state = !state;
}
}
count --;
}
}
return z;
}
unsigned int correct(unsigned int *L, unsigned int *o, unsigned int *err_addr, unsigned char *err_data)
{
unsigned int cor_addr; // 10 bits
unsigned int err_cnt; // 3 bits
unsigned int r0, r1, r2, r3, r4, r5, r6,r7; // 10 bits
unsigned galoisdiv_e;
{
/* init
r0[9] <= L1[9]^L1[8]^L1[5]^L1[4]^L1[2]^L1[1]^L1[0];
r0[8] <= L1[9]^L1[8]^L1[7]^L1[6]^L1[4]^L1[3]^L1[1]^L1[0];
r0[7] <= L1[9]^L1[8]^L1[7]^L1[5]^L1[3]^L1[2]^L1[0];
r0[6] <= L1[9]^L1[8]^L1[7]^L1[4]^L1[2]^L1[1];
r0[5] <= L1[8]^L1[7]^L1[6]^L1[3]^L1[1]^L1[0];
r0[4] <= L1[9]^L1[7]^L1[5]^L1[2]^L1[0];
r0[3] <= L1[9]^L1[8]^L1[4]^L1[1];
r0[2] <= L1[8]^L1[7]^L1[3]^L1[0];
r0[1] <= L1[9]^L1[7]^L1[2];
r0[0] <= L1[8]^L1[6]^L1[1];
r1[9] <= L2[8]^L2[7]^L2[6]^L2[3]^L2[2]^L2[0];
r1[8] <= L2[9]^L2[7]^L2[5]^L2[2]^L2[1];
r1[7] <= L2[8]^L2[6]^L2[4]^L2[1]^L2[0];
r1[6] <= L2[9]^L2[7]^L2[6]^L2[5]^L2[3]^L2[0];
r1[5] <= L2[9]^L2[8]^L2[5]^L2[4]^L2[2];
r1[4] <= L2[8]^L2[7]^L2[4]^L2[3]^L2[1];
r1[3] <= L2[7]^L2[6]^L2[3]^L2[2]^L2[0];
r1[2] <= L2[9]^L2[5]^L2[2]^L2[1];
r1[1] <= L2[8]^L2[4]^L2[1]^L2[0];
r1[0] <= L2[9]^L2[7]^L2[6]^L2[3]^L2[0];
r2[9] <= L3[5]^L3[4]^L3[3]^L3[0];
r2[8] <= L3[9]^L3[6]^L3[4]^L3[3]^L3[2];
r2[7] <= L3[8]^L3[5]^L3[3]^L3[2]^L3[1];
r2[6] <= L3[7]^L3[4]^L3[2]^L3[1]^L3[0];
r2[5] <= L3[9]^L3[3]^L3[1]^L3[0];
r2[4] <= L3[9]^L3[8]^L3[6]^L3[2]^L3[0];
r2[3] <= L3[9]^L3[8]^L3[7]^L3[6]^L3[5]^L3[1];
r2[2] <= L3[8]^L3[7]^L3[6]^L3[5]^L3[4]^L3[0];
r2[1] <= L3[9]^L3[7]^L3[5]^L3[4]^L3[3];
r2[0] <= L3[8]^L3[6]^L3[4]^L3[3]^L3[2];
r3[9] <= L4[8]^L4[5]^L4[4]^L4[3]^L4[2]^L4[1];
r3[8] <= L4[7]^L4[4]^L4[3]^L4[2]^L4[1]^L4[0];
r3[7] <= L4[9]^L4[3]^L4[2]^L4[1]^L4[0];
r3[6] <= L4[9]^L4[8]^L4[6]^L4[2]^L4[1]^L4[0];
r3[5] <= L4[9]^L4[8]^L4[7]^L4[6]^L4[5]^L4[1]^L4[0];
r3[4] <= L4[9]^L4[8]^L4[7]^L4[5]^L4[4]^L4[0];
r3[3] <= L4[9]^L4[8]^L4[7]^L4[4]^L4[3];
r3[2] <= L4[8]^L4[7]^L4[6]^L4[3]^L4[2];
r3[1] <= L4[7]^L4[6]^L4[5]^L4[2]^L4[1];
r3[0] <= L4[6]^L4[5]^L4[4]^L4[1]^L4[0];
r4[9] <= o0[9]^o0[5]^o0[3];
r4[8] <= o0[8]^o0[4]^o0[2];
r4[7] <= o0[7]^o0[3]^o0[1];
r4[6] <= o0[6]^o0[2]^o0[0];
r4[5] <= o0[9]^o0[6]^o0[5]^o0[1];
r4[4] <= o0[8]^o0[5]^o0[4]^o0[0];
r4[3] <= o0[9]^o0[7]^o0[6]^o0[4]^o0[3];
r4[2] <= o0[8]^o0[6]^o0[5]^o0[3]^o0[2];
r4[1] <= o0[7]^o0[5]^o0[4]^o0[2]^o0[1];
r4[0] <= o0[6]^o0[4]^o0[3]^o0[1]^o0[0];
r5[9] <= o1[8]^o1[7]^o1[6]^o1[5]^o1[3]^o1[2]^o1[1];
r5[8] <= o1[7]^o1[6]^o1[5]^o1[4]^o1[2]^o1[1]^o1[0];
r5[7] <= o1[9]^o1[5]^o1[4]^o1[3]^o1[1]^o1[0];
r5[6] <= o1[9]^o1[8]^o1[6]^o1[4]^o1[3]^o1[2]^o1[0];
r5[5] <= o1[9]^o1[8]^o1[7]^o1[6]^o1[5]^o1[3]^o1[2]^o1[1];
r5[4] <= o1[8]^o1[7]^o1[6]^o1[5]^o1[4]^o1[2]^o1[1]^o1[0];
r5[3] <= o1[9]^o1[7]^o1[5]^o1[4]^o1[3]^o1[1]^o1[0];
r5[2] <= o1[9]^o1[8]^o1[4]^o1[3]^o1[2]^o1[0];
r5[1] <= o1[9]^o1[8]^o1[7]^o1[6]^o1[3]^o1[2]^o1[1];
r5[0] <= o1[8]^o1[7]^o1[6]^o1[5]^o1[2]^o1[1]^o1[0];
r6[9] <= o2[9]^o2[5]^o2[4]^o2[2];
r6[8] <= o2[8]^o2[4]^o2[3]^o2[1];
r6[7] <= o2[7]^o2[3]^o2[2]^o2[0];
r6[6] <= o2[9]^o2[2]^o2[1];
r6[5] <= o2[8]^o2[1]^o2[0];
r6[4] <= o2[9]^o2[7]^o2[6]^o2[0];
r6[3] <= o2[9]^o2[8]^o2[5];
r6[2] <= o2[8]^o2[7]^o2[4];
r6[1] <= o2[7]^o2[6]^o2[3];
r6[0] <= o2[6]^o2[5]^o2[2];
r7[9] <= o3[8]^o3[7]^o3[6]^o3[4];
r7[8] <= o3[7]^o3[6]^o3[5]^o3[3];
r7[7] <= o3[6]^o3[5]^o3[4]^o3[2];
r7[6] <= o3[5]^o3[4]^o3[3]^o3[1];
r7[5] <= o3[4]^o3[3]^o3[2]^o3[0];
r7[4] <= o3[9]^o3[6]^o3[3]^o3[2]^o3[1];
r7[3] <= o3[8]^o3[5]^o3[2]^o3[1]^o3[0];
r7[2] <= o3[9]^o3[7]^o3[6]^o3[4]^o3[1]^o3[0];
r7[1] <= o3[9]^o3[8]^o3[5]^o3[3]^o3[0];
r7[0] <= o3[9]^o3[8]^o3[7]^o3[6]^o3[4]^o3[2];
*/
r0 = g_au16CorrectInitLookupR0[L[1]];
r1 = g_au16CorrectInitLookupR1[L[2]];
r2 = g_au16CorrectInitLookupR2[L[3]];
r3 = g_au16CorrectInitLookupR3[L[4]];
r4 = g_au16CorrectInitLookupR4[o[0]];
r5 = g_au16CorrectInitLookupR5[o[1]];
r6 = g_au16CorrectInitLookupR6[o[2]];
r7 = g_au16CorrectInitLookupR7[o[3]];
cor_addr = err_cnt = 0;
}
do
{
if ( !(L[0]^r0^r1^r2^r3) )
{
// error find
galoisdiv_e = galoisdiv( r4^r5^r6^r7, r0^r2 );
/*
if(^galoisdiv_e[1:0] | (&err_cnt))
err_cnt <= 3'd7;
else
err_cnt <= err_cnt + 1'b1;
// cor_data
assign cor_data = galoisdiv_e[9:2];
*/
if (err_cnt<4)
{
err_addr[err_cnt] = cor_addr - 2;
err_data[err_cnt] = galoisdiv_e>>2;
}
if ( _2BitXor(galoisdiv_e) | (err_cnt == 7) )
err_cnt = 7;
else
err_cnt ++;
}
/*
if(chk_en)
begin
r0 <= {r0[8:0], r0[9]^r0[6]};
r1 <= {r1[7:0], (r1[9]^r1[6]), (r1[8]^r1[5])};
r2 <= {r2[6:0], (r2[9]^r2[6]), (r2[8]^r2[5]), (r2[7]^r2[4])};
r3 <= {r3[5:0], (r3[9]^r3[6]), (r3[8]^r3[5]), (r3[7]^r3[4]), (r3[6]^r3[3])};
r4 <= {(r4[6]^r4[1]), (r4[5]^r4[0]), (r4[9]^r4[6]^r4[4]), (r4[8]^r4[5]^r4[3]),
(r4[7]^r4[4]^r4[2]), (r4[6]^r4[3]^r4[1]), (r4[5]^r4[2]^r4[0]),
(r4[9]^r4[6]^r4[4]^r4[1]), (r4[8]^r4[5]^r4[3]^r4[0]), (r4[9]^r4[7]^r4[6]^r4[4]^r4[2])};
r5 <= {(r5[5]^r5[0]), (r5[9]^r5[6]^r5[4]), (r5[8]^r5[5]^r5[3]), (r5[7]^r5[4]^r5[2]),
(r5[6]^r5[3]^r5[1]), (r5[5]^r5[2]^r5[0]), (r5[9]^r5[6]^r5[4]^r5[1]),
(r5[8]^r5[5]^r5[3]^r5[0]), (r5[9]^r5[7]^r5[6]^r5[4]^r5[2]),
(r5[8]^r5[6]^r5[5]^r5[3]^r5[1])};
r6 <= {(r6[9]^r6[6]^r6[4]), (r6[8]^r6[5]^r6[3]), (r6[7]^r6[4]^r6[2]), (r6[6]^r6[3]^r6[1]),
(r6[5]^r6[2]^r6[0]), (r6[9]^r6[6]^r6[4]^r6[1]), (r6[8]^r6[5]^r6[3]^r6[0]),
(r6[9]^r6[7]^r6[6]^r6[4]^r6[2]), (r6[8]^r6[6]^r6[5]^r6[3]^r6[1]),
(r6[7]^r6[5]^r6[4]^r6[2]^r6[0])};
r7 <= {(r7[8]^r7[5]^r7[3]), (r7[7]^r7[4]^r7[2]), (r7[6]^r7[3]^r7[1]), (r7[5]^r7[2]^r7[0]),
(r7[9]^r7[6]^r7[4]^r7[1]), (r7[8]^r7[5]^r7[3]^r7[0]), (r7[9]^r7[7]^r7[6]^r7[4]^r7[2]),
(r7[8]^r7[6]^r7[5]^r7[3]^r7[1]), (r7[7]^r7[5]^r7[4]^r7[2]^r7[0]), (r7[9]^r7[4]^r7[3]^r7[1])};
end
*/
if ( cor_addr != (512+1) )//if ( cor_addr != (512+2) )
{
r0 = ((r0<<1)|g_au8CorrectLookupR0[r0])&0x3ff;
r1 = ((r1<<2)|g_au8CorrectLookupR1[r1])&0x3ff;
r2 = ((r2<<3)|g_au8CorrectLookupR2[r2])&0x3ff;
r3 = ((r3<<4)|g_au8CorrectLookupR3[r3])&0x3ff;
r4 = g_au16CorrectLookupR4[r4];
r5 = g_au16CorrectLookupR5[r5];
r6 = g_au16CorrectLookupR6[r6];
r7 = g_au16CorrectLookupR7[r7];
}
else
break;
cor_addr ++;
}while(1);
return err_cnt;
}
<file_sep>/gpio/lib/w55fa93_gpio.h
/****************************************************************************
* *
* Copyright (c) 2009 Nuvoton Tech. Corp. All rights reserved. *
* *
*****************************************************************************/
/****************************************************************************
* FILENAME
* nuc930_gpio.h
*
* VERSION
* 1.0
*
* DESCRIPTION
* GPIO library header file
*
* DATA STRUCTURES
* None
*
* FUNCTIONS
*
* HISTORY
*
* REMARK
* None
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_reg.h"
#define GPIO_PORTA 1
#define GPIO_PORTB 2
#define GPIO_PORTC 4
#define GPIO_PORTD 8
#define GPIO_PORTE 16
extern int gpio_open(unsigned char port);
extern int gpio_configure(unsigned char port, unsigned short num);
extern int gpio_readport(unsigned char port, unsigned short *val);
extern int gpio_setportdir(unsigned char port, unsigned short mask, unsigned short dir);
extern int gpio_setportval(unsigned char port, unsigned short mask, unsigned short val);
extern int gpio_setportpull(unsigned char port, unsigned short mask, unsigned short pull);
extern int gpio_setdebounce(unsigned int clk, unsigned char src);
extern void gpio_getdebounce(unsigned int *clk, unsigned char *src);
extern int gpio_setsrcgrp(unsigned char port, unsigned short mask, unsigned char irq);
extern int gpio_getsrcgrp(unsigned char port, unsigned int *val);
extern int gpio_setintmode(unsigned char port, unsigned short mask, unsigned short falling, unsigned short rising);
extern int gpio_getintmode(unsigned char port, unsigned short *falling, unsigned short *rising);
extern int gpio_setlatchtrigger(unsigned char src);
extern void gpio_getlatchtrigger(unsigned char *src);
extern int gpio_getlatchval(unsigned char port, unsigned short *val);
extern int gpio_gettriggersrc(unsigned char port, unsigned short *src);
extern int gpio_cleartriggersrc(unsigned char port);<file_sep>/SIC_SECC/Lib/w55fa93_sic.h
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2008 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#ifndef _FMILIB_H_
#define _FMILIB_H_
#define OPT_FA93
//#define OPT_SW_WP
#define OPT_MARK_BAD_BLOCK_WHILE_ERASE_FAIL
#define FMI_SD_CARD 0
#define FMI_SM_CARD 1
#define FMI_ERR_ID 0xFFFF0100
#define FMI_TIMEOUT (FMI_ERR_ID|0x01)
#define FMI_NO_MEMORY (FMI_ERR_ID|0x02)
/* SD error */
#define FMI_NO_SD_CARD (FMI_ERR_ID|0x10)
#define FMI_ERR_DEVICE (FMI_ERR_ID|0x11)
#define FMI_SD_INIT_TIMEOUT (FMI_ERR_ID|0x12)
#define FMI_SD_SELECT_ERROR (FMI_ERR_ID|0x13)
#define FMI_SD_WRITE_PROTECT (FMI_ERR_ID|0x14)
#define FMI_SD_INIT_ERROR (FMI_ERR_ID|0x15)
#define FMI_SD_CRC7_ERROR (FMI_ERR_ID|0x16)
#define FMI_SD_CRC16_ERROR (FMI_ERR_ID|0x17)
#define FMI_SD_CRC_ERROR (FMI_ERR_ID|0x18)
#define FMI_SD_CMD8_ERROR (FMI_ERR_ID|0x19)
/* NAND error */
#define FMI_SM_INIT_ERROR (FMI_ERR_ID|0x20)
#define FMI_SM_RB_ERR (FMI_ERR_ID|0x21)
#define FMI_SM_STATE_ERROR (FMI_ERR_ID|0x22)
#define FMI_SM_ECC_ERROR (FMI_ERR_ID|0x23)
#define FMI_SM_STATUS_ERR (FMI_ERR_ID|0x24)
#define FMI_SM_ID_ERR (FMI_ERR_ID|0x25)
#define FMI_SM_INVALID_BLOCK (FMI_ERR_ID|0x26)
#define FMI_SM_MARK_BAD_BLOCK_ERR (FMI_ERR_ID|0x27)
/* MS error */
#define FMI_NO_MS_CARD (FMI_ERR_ID|0x30)
#define FMI_MS_INIT_ERROR (FMI_ERR_ID|0x31)
#define FMI_MS_INT_TIMEOUT (FMI_ERR_ID|0x32)
#define FMI_MS_BUSY_TIMEOUT (FMI_ERR_ID|0x33)
#define FMI_MS_CRC_ERROR (FMI_ERR_ID|0x34)
#define FMI_MS_INT_CMDNK (FMI_ERR_ID|0x35)
#define FMI_MS_INT_ERR (FMI_ERR_ID|0x36)
#define FMI_MS_INT_BREQ (FMI_ERR_ID|0x37)
#define FMI_MS_INT_CED_ERR (FMI_ERR_ID|0x38)
#define FMI_MS_READ_PAGE_ERROR (FMI_ERR_ID|0x39)
#define FMI_MS_COPY_PAGE_ERR (FMI_ERR_ID|0x3a)
#define FMI_MS_ALLOC_ERR (FMI_ERR_ID|0x3b)
#define FMI_MS_WRONG_SEGMENT (FMI_ERR_ID|0x3c)
#define FMI_MS_WRONG_PHYBLOCK (FMI_ERR_ID|0x3d)
#define FMI_MS_WRONG_TYPE (FMI_ERR_ID|0x3e)
#define FMI_MS_WRITE_DISABLE (FMI_ERR_ID|0x3f)
#define NAND_TYPE_SLC 0x01
#define NAND_TYPE_MLC 0x00
#define NAND_PAGE_512B 512
#define NAND_PAGE_2KB 2048
#define NAND_PAGE_4KB 4096
#define NAND_PAGE_8KB 8192
typedef struct fmi_sm_info_t
{
UINT32 uSectorPerFlash;
UINT32 uBlockPerFlash;
UINT32 uPagePerBlock;
UINT32 uSectorPerBlock;
UINT32 uLibStartBlock;
UINT32 nPageSize;
UINT32 uBadBlockCount;
BOOL bIsMulticycle;
BOOL bIsMLCNand;
BOOL bIsNandECC4;
BOOL bIsNandECC8;
BOOL bIsNandECC12;
BOOL bIsNandECC15;
BOOL bIsCheckECC;
} FMI_SM_INFO_T;
extern FMI_SM_INFO_T *pSM0, *pSM1;
typedef struct fmi_sd_info_t
{
UINT32 uCardType; // sd2.0, sd1.1, or mmc
UINT32 uRCA; // relative card address
BOOL bIsCardInsert;
} FMI_SD_INFO_T;
extern FMI_SD_INFO_T *pSD0;
extern FMI_SD_INFO_T *pSD1;
extern FMI_SD_INFO_T *pSD2;
// function prototype
VOID fmiInitDevice(VOID);
VOID fmiSetFMIReferenceClock(UINT32 uClock);
INT fmiSD_CardSel(INT cardSel);
INT fmiSD_Read(UINT32 uSector, UINT32 uBufcnt, UINT32 uDAddr);
INT fmiSD_Write(UINT32 uSector, UINT32 uBufcnt, UINT32 uSAddr);
// for file system
//INT fmiInitSDDevice(void);
INT fmiInitSDDevice(INT cardSel);
//PDISK_T *fmiGetpDisk(UINT32 uCard);
// callback function
VOID fmiSetCallBack(UINT32 uCard, PVOID pvRemove, PVOID pvInsert);
/* extern function */
#define SIC_SET_CLOCK 0
#define SIC_SET_CALLBACK 1
#define SIC_GET_CARD_STATUS 2
#define SD_FREQ 24000
#define SDHC_FREQ 24000
void sicOpen(void);
void sicClose(void);
INT sicSdOpen(void);
//INT sicSdOpen(INT cardSel);
VOID sicSdClose(void);
//VOID sicSdClose(INT cardSel);
INT sicSdOpen0(void);
INT sicSdOpen1(void);
INT sicSdOpen2(void);
VOID sicSdClose0(void);
VOID sicSdClose1(void);
VOID sicSdClose2(void);
VOID sicIoctl(INT32 sicFeature, INT32 sicArg0, INT32 sicArg1, INT32 sicArg2);
INT sicSdRead(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdTargetAddr);
INT sicSdRead0(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdTargetAddr);
INT sicSdRead1(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdTargetAddr);
INT sicSdRead2(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdTargetAddr);
INT sicSdWrite(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdSourceAddr);
INT sicSdWrite0(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdSourceAddr);
INT sicSdWrite1(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdSourceAddr);
INT sicSdWrite2(INT32 sdSectorNo, INT32 sdSectorCount, INT32 sdSourceAddr);
VOID fmiSMClose(INT chipSel);
/* gnand use */
#include "w55fa93_gnand.h"
INT nandInit0(NDISK_T *NDISK_info);
INT nandpread0(INT PBA, INT page, UINT8 *buff);
INT nandpwrite0(INT PBA, INT page, UINT8 *buff);
INT nand_is_page_dirty0(INT PBA, INT page);
INT nand_is_valid_block0(INT PBA);
INT nand_block_erase0(INT PBA);
INT nand_chip_erase0(VOID);
INT nand_ioctl(INT param1, INT param2, INT param3, INT param4);
INT nandInit1(NDISK_T *NDISK_info);
INT nandpread1(INT PBA, INT page, UINT8 *buff);
INT nandpwrite1(INT PBA, INT page, UINT8 *buff);
INT nand_is_page_dirty1(INT PBA, INT page);
INT nand_is_valid_block1(INT PBA);
INT nand_block_erase1(INT PBA);
INT nand_chip_erase1(VOID);
#endif //_FMILIB_H_<file_sep>/BLT/sample/CommFunc.c
#include <stdio.h>
#include "w55fa93_reg.h"
#include "blt.h"
#include "DrvBLT.h"
#include "FI.h"
UINT32 gDisplayFormat = eDRVBLT_DEST_RGB565;
void defaultSetting(void)
{
outp32(MLTA, 0x00000100);
outp32(MLTR, 0x00000100);
outp32(MLTG, 0x00000100);
outp32(MLTB, 0x00000100);
outp32(ELEMENTA, 0x00010000);
outp32(ELEMENTB, 0x00000000);
outp32(ELEMENTC, 0x00000000);
outp32(ELEMENTD, 0x00010000);
}
UINT32 GetSrcRowByte(E_DRVBLT_BMPIXEL_FORMAT eSrcFmt, UINT32 u32pixelwidth)
{
#if (STRIDE_FOR_BYTE ==0)
return u32pixelwidth;
#else
UINT32 u32Byte;
switch (eSrcFmt)
{
case eDRVBLT_SRC_ARGB8888:
return u32pixelwidth* 4;
case eDRVBLT_SRC_RGB565:
return u32pixelwidth* 2;
case eDRVBLT_SRC_1BPP:
u32Byte = u32pixelwidth /8;
break;
case eDRVBLT_SRC_2BPP:
u32Byte = u32pixelwidth * 2 /8;
break;
case eDRVBLT_SRC_4BPP:
u32Byte = u32pixelwidth * 4 /8;
break;
case eDRVBLT_SRC_8BPP:
u32Byte = u32pixelwidth;
break;
}
return (u32Byte+3)/4*4;
#endif
}
UINT32 GetDestRowByte(E_DRVBLT_DISPLAY_FORMAT eDestFmt, UINT32 u32pixelwidth)
{
#if (STRIDE_FOR_BYTE ==0)
return u32pixelwidth;
#else
if (eDestFmt == eDRVBLT_DEST_ARGB8888)
return u32pixelwidth * 4;
else
return u32pixelwidth * 2;
#endif
}
<file_sep>/AVI/Example/Demo_AVI.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#pragma import(__use_no_semihosting_swi)
#include "wbio.h"
#include "wblib.h"
#include "w55fa93_vpost.h"
#include "w55fa93_sic.h"
#include "nvtfat.h"
#include "AviLib.h"
#include "spu.h"
UINT32 StorageForNAND(void);
//#pragma import(__use_no_semihosting_swi)
#define VPOST_FRAME_BUFSZ (320*240*2) //(640*480*2)
static __align(256) UINT8 _VpostFrameBufferPool[VPOST_FRAME_BUFSZ];
static UINT8 *_VpostFrameBuffer;
#define STORAGE_SD 1 // comment to work NAND, uncomment to use SD
//#define NAND_2 1 // comment to use 1 disk foor NAND, uncomment to use 2 disk
#ifndef STORAGE_SD
static NDISK_T ptNDisk;
static NDRV_T _nandDiskDriver0 =
{
nandInit0,
nandpread0,
nandpwrite0,
nand_is_page_dirty0,
nand_is_valid_block0,
nand_ioctl,
nand_block_erase0,
nand_chip_erase0,
0
};
#define NAND1_1_SIZE 32 /* MB unit */
void AudioChanelControl(void)
{
}
UINT32 StorageForNAND(void)
{
UINT32 block_size, free_size, disk_size;
UINT32 u32TotalSize;
fsAssignDriveNumber('C', DISK_TYPE_SMART_MEDIA, 0, 1);
#ifdef NAND_2
fsAssignDriveNumber('D', DISK_TYPE_SMART_MEDIA, 0, 2);
#endif
/* For detect VBUS stable */
sicOpen();
sicIoctl(SIC_SET_CLOCK, 192000, 0, 0); /* clock from PLL */
/* Initialize GNAND */
if(GNAND_InitNAND(&_nandDiskDriver0, &ptNDisk, TRUE) < 0)
{
sysprintf("GNAND_InitNAND error\n");
goto halt;
}
if(GNAND_MountNandDisk(&ptNDisk) < 0)
{
sysprintf("GNAND_MountNandDisk error\n");
goto halt;
}
/* Get NAND disk information*/
u32TotalSize = ptNDisk.nZone* ptNDisk.nLBPerZone*ptNDisk.nPagePerBlock*ptNDisk.nPageSize;
sysprintf("Total Disk Size %d\n", u32TotalSize);
/* Format NAND if necessery */
#ifdef NAND_2
if ((fsDiskFreeSpace('C', &block_size, &free_size, &disk_size) < 0) ||
(fsDiskFreeSpace('D', &block_size, &free_size, &disk_size) < 0))
{
sysprintf("unknow disk type, format device .....\n");
if (fsTwoPartAndFormatAll((PDISK_T *)ptNDisk.pDisk, NAND1_1_SIZE*1024, (u32TotalSize- NAND1_1_SIZE*1024)) < 0) {
sysprintf("Format failed\n");
goto halt;
}
fsSetVolumeLabel('C', "NAND1-1\n", strlen("NAND1-1"));
fsSetVolumeLabel('D', "NAND1-2\n", strlen("NAND1-2"));
}
#endif
AudioChanelControl();
/* Initial SPU in advance for linux set volume issue */
spuOpen(eDRVSPU_FREQ_8000);
spuDacOn(1);
// spuIoctl(SPU_IOCTL_SET_VOLUME, 0x20, 0x20);
halt:
sysprintf("systen exit\n");
return 0;
}
#endif
void avi_play_control(AVI_INFO_T *aviInfo)
{
static INT last_time;
int frame_rate;
if (aviInfo->uPlayCurTimePos != 0)
frame_rate = ((aviInfo->uVidFramesPlayed - aviInfo->uVidFramesSkipped) * 100) / aviInfo->uPlayCurTimePos;
if (aviInfo->uPlayCurTimePos - last_time > 100)
{
sysprintf("%02d:%02d / %02d:%02d Vid fps: %d / %d\n",
aviInfo->uPlayCurTimePos / 6000, (aviInfo->uPlayCurTimePos / 100) % 60,
aviInfo->uMovieLength / 6000, (aviInfo->uMovieLength / 100) % 60,
frame_rate, aviInfo->uVideoFrameRate);
last_time = aviInfo->uPlayCurTimePos;
}
}
int main()
{
WB_UART_T uart;
LCDFORMATEX lcdformatex;
CHAR suFileName[128];
INT nStatus;
/* CACHE_ON */
sysEnableCache(CACHE_WRITE_BACK);
/*-----------------------------------------------------------------------*/
/* CPU/AHB/APH: 200/100/50 */
/*-----------------------------------------------------------------------*/
sysSetSystemClock(eSYS_UPLL, //E_SYS_SRC_CLK eSrcClk,
192000, //UINT32 u32PllKHz,
192000, //UINT32 u32SysKHz,
192000, //UINT32 u32CpuKHz,
192000/2, //UINT32 u32HclkKHz,
192000/4); //UINT32 u32ApbKHz
/*-----------------------------------------------------------------------*/
/* Init UART, N,8,1, 115200 */
/*-----------------------------------------------------------------------*/
sysUartPort(1);
uart.uiFreq = 12000000; //use XIN clock
uart.uiBaudrate = 115200;
uart.uiDataBits = WB_DATA_BITS_8;
uart.uiStopBits = WB_STOP_BITS_1;
uart.uiParity = WB_PARITY_NONE;
uart.uiRxTriggerLevel = LEVEL_1_BYTE;
sysInitializeUART(&uart);
sysprintf("UART initialized.\n");
_VpostFrameBuffer = (UINT8 *)((UINT32)_VpostFrameBufferPool | 0x80000000);
/*-----------------------------------------------------------------------*/
/* Init timer */
/*-----------------------------------------------------------------------*/
sysSetTimerReferenceClock (TIMER0, 60000000);
sysStartTimer(TIMER0, 100, PERIODIC_MODE);
/*-----------------------------------------------------------------------*/
/* Init FAT file system */
/*-----------------------------------------------------------------------*/
sysprintf("fsInitFileSystem.\n");
fsInitFileSystem();
#ifdef STORAGE_SD
/*-----------------------------------------------------------------------*/
/* Init SD card */
/*-----------------------------------------------------------------------*/
sicIoctl(SIC_SET_CLOCK, 200000, 0, 0);
sicOpen();
sysprintf("total sectors (%x)\n", sicSdOpen0());
spuOpen(eDRVSPU_FREQ_8000);
spuDacOn(1);
#else
StorageForNAND();
#endif
#if 0
/*-----------------------------------------------------------------------*/
/* */
/* Direct RGB555 AVI playback */
/* */
/*-----------------------------------------------------------------------*/
lcdformatex.ucVASrcFormat = DRVVPOST_FRAME_RGB555;
vpostLCMInit(&lcdformatex, (UINT32 *)_VpostFrameBuffer);
fsAsciiToUnicode("c:\\sample.avi", suFileName, TRUE);
if (aviPlayFile(suFileName, 0, 0, DIRECT_RGB555, avi_play_control) < 0)
sysprintf("Playback failed, code = %x\n", nStatus);
else
sysprintf("Playback done.\n");
#endif
#if 1
/*-----------------------------------------------------------------------*/
/* */
/* Direct RGB565 AVI playback */
/* */
/*-----------------------------------------------------------------------*/
lcdformatex.ucVASrcFormat = DRVVPOST_FRAME_RGB565;
vpostLCMInit(&lcdformatex, (UINT32 *)_VpostFrameBuffer);
fsAsciiToUnicode("c:\\sample.avi", suFileName, TRUE);
if (aviPlayFile(suFileName, 0, 0, DIRECT_RGB565, avi_play_control) < 0)
sysprintf("Playback failed, code = %x\n", nStatus);
else
sysprintf("Playback done.\n");
#endif
#if 0
/*-----------------------------------------------------------------------*/
/* */
/* Direct YUV422 AVI playback */
/* */
/*-----------------------------------------------------------------------*/
lcdformatex.ucVASrcFormat = DRVVPOST_FRAME_YCBYCR;
vpostLCMInit(&lcdformatex, (UINT32 *)_VpostFrameBuffer);
fsAsciiToUnicode("c:\\sample.avi", suFileName, TRUE);
if (aviPlayFile(suFileName, 0, 0, DIRECT_YUV422, avi_play_control) < 0)
sysprintf("Playback failed, code = %x\n", nStatus);
else
sysprintf("Playback done.\n");
#endif
#ifndef STORAGE_SD
GNAND_UnMountNandDisk(&ptNDisk);
fmiSMClose(0);
sicClose();
#endif
while(1);
}
<file_sep>/SIC_SECC/Src/sd.c
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2008 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#ifdef ECOS
#include "drv_api.h"
#include "diag.h"
#include "wbtypes.h"
#include "wbio.h"
#else
#include "wblib.h"
#endif
//#include "nuc930_reg.h"
//#include "nuc930_sic.h"
#include "w55fa93_reg.h"
#include "w55fa93_sic.h"
#include "fmi.h"
#include "nvtfat.h"
#define SD_BLOCK_SIZE 512
#define FMI_SD_INITCOUNT 2000
#define FMI_TICKCOUNT 1000
#define FMI_TYPE_UNKNOWN 0
#define FMI_TYPE_SD_HIGH 1
#define FMI_TYPE_SD_LOW 2
#define FMI_TYPE_MMC 3
// global variables
UINT32 _fmi_uR3_CMD=0;
UINT32 _fmi_uR7_CMD=0;
__align(4096) UCHAR _fmi_ucSDHCBuffer[64];
UINT8 *_fmi_pSDHCBuffer;
void fmiCheckRB()
{
while(1)
{
outpw(REG_SDCR, inpw(REG_SDCR)|SDCR_8CLK_OE);
while(inpw(REG_SDCR) & SDCR_8CLK_OE);
if (inpw(REG_SDISR) & SDISR_SD_DATA0)
break;
}
}
INT fmiSDCommand(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg)
{
outpw(REG_SDARG, uArg);
outpw(REG_SDCR, (inpw(REG_SDCR)&(~SDCR_CMD_CODE))|(ucCmd << 8)|(SDCR_CO_EN));
while(inpw(REG_SDCR) & SDCR_CO_EN)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
return Successful;
}
INT fmiSDCmdAndRsp(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg, INT ntickCount)
{
// unsigned int reg;
outpw(REG_SDARG, uArg);
outpw(REG_SDCR, (inpw(REG_SDCR)&(~SDCR_CMD_CODE))|(ucCmd << 8)|(SDCR_CO_EN | SDCR_RI_EN));
if (ntickCount > 0)
{
while(inpw(REG_SDCR) & SDCR_RI_EN)
{
if(ntickCount-- == 0) {
outpw(REG_SDCR, inpw(REG_SDCR)|SDCR_SWRST); // reset SD engine
return 2;
}
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
}
else
{
while(inpw(REG_SDCR) & SDCR_RI_EN)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
}
if (_fmi_uR7_CMD)
{
if (((inpw(REG_SDRSP1) & 0xff) != 0x55) && ((inpw(REG_SDRSP0) & 0xf) != 0x01))
{
_fmi_uR7_CMD = 0;
return FMI_SD_CMD8_ERROR;
}
}
if (!_fmi_uR3_CMD)
{
if (inpw(REG_SDISR) & SDISR_CRC_7) // check CRC7
return Successful;
else
{
#ifdef DEBUG
sysprintf("response error [%d]!\n", ucCmd);
#endif
return FMI_SD_CRC7_ERROR;
}
}
else
{
_fmi_uR3_CMD = 0;
outpw(REG_SDISR, SDISR_CRC_IF);
return Successful;
}
}
// Get 16 bytes CID or CSD
INT fmiSDCmdAndRsp2(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg, UINT *puR2ptr)
{
unsigned int i;
unsigned int tmpBuf[5];
// unsigned int reg;
outpw(REG_SDARG, uArg);
outpw(REG_SDCR, (inpw(REG_SDCR)&(~SDCR_CMD_CODE))|(ucCmd << 8)|(SDCR_CO_EN | SDCR_R2_EN));
while(inpw(REG_SDCR) & SDCR_R2_EN)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if (inpw(REG_SDISR) & SDISR_CRC_7)
{
for (i=0; i<5; i++)
tmpBuf[i] = Swap32(inpw(REG_FB_0+i*4));
for (i=0; i<4; i++)
*puR2ptr++ = ((tmpBuf[i] & 0x00ffffff)<<8) | ((tmpBuf[i+1] & 0xff000000)>>24);
return Successful;
}
else
return FMI_SD_CRC7_ERROR;
}
INT fmiSDCmdAndRspDataIn(FMI_SD_INFO_T *pSD, UINT8 ucCmd, UINT32 uArg)
{
// unsigned int reg;
outpw(REG_SDARG, uArg);
outpw(REG_SDCR, (inpw(REG_SDCR)&(~SDCR_CMD_CODE))|(ucCmd << 8)|(SDCR_CO_EN | SDCR_RI_EN | SDCR_DI_EN));
while (inpw(REG_SDCR) & SDCR_RI_EN)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
while (inpw(REG_SDCR) & SDCR_DI_EN)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_7)) // check CRC7
{
#ifdef DEBUG
sysprintf("fmiSDCmdAndRspDataIn: response error [%d]!\n", ucCmd);
#endif
return FMI_SD_CRC7_ERROR;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_16)) // check CRC16
{
#ifdef DEBUG
sysprintf("fmiSDCmdAndRspDataIn: read data error!\n");
#endif
return FMI_SD_CRC16_ERROR;
}
return Successful;
}
// Initial
INT fmiSD_Init(FMI_SD_INFO_T *pSD)
{
int volatile i, status, rate;
unsigned int resp;
unsigned int CIDBuffer[4];
unsigned int volatile u32CmdTimeOut;
#if 1
// set the clock to 200KHz
/* divider */
rate = _fmi_uFMIReferenceClock / 200;
if ((_fmi_uFMIReferenceClock % 200) == 0)
rate = rate - 1;
#else
// set the clock to 400KHz
/* divider */
rate = _fmi_uFMIReferenceClock / 400;
if ((_fmi_uFMIReferenceClock % 400) == 0)
rate = rate - 1;
#endif
for(i=0; i<100; i++);
// outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_S) | (0x02 << 19)); // SD clock from APLL
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_S) | (0x03 << 19)); // SD clock from UPLL
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_N0) | (0x07 << 16)); // SD clock divided by 8
rate /= 8;
rate &= 0xFF;
if (rate) rate--;
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_N1) | (rate << 24)); // SD clock divider
for(i=0; i<1000; i++);
// power ON 74 clock
outpw(REG_SDCR, inpw(REG_SDCR) | SDCR_74CLK_OE);
while(inpw(REG_SDCR) & SDCR_74CLK_OE)
{
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
fmiSDCommand(pSD, 0, 0); // reset all cards
for (i=0x100; i>0; i--);
// initial SDHC
_fmi_uR7_CMD = 1;
u32CmdTimeOut = 5000;
i = fmiSDCmdAndRsp(pSD, 8, 0x00000155, u32CmdTimeOut);
if (i == Successful)
{
// SD 2.0
fmiSDCmdAndRsp(pSD, 55, 0x00, u32CmdTimeOut);
_fmi_uR3_CMD = 1;
fmiSDCmdAndRsp(pSD, 41, 0x40ff8000, u32CmdTimeOut); // 2.7v-3.6v
resp = inpw(REG_SDRSP0);
while (!(resp & 0x00800000)) // check if card is ready
{
fmiSDCmdAndRsp(pSD, 55, 0x00, u32CmdTimeOut);
_fmi_uR3_CMD = 1;
fmiSDCmdAndRsp(pSD, 41, 0x40ff8000, u32CmdTimeOut); // 3.0v-3.4v
resp = inpw(REG_SDRSP0);
}
if (resp & 0x00400000)
pSD->uCardType = FMI_TYPE_SD_HIGH;
else
pSD->uCardType = FMI_TYPE_SD_LOW;
}
else
{
// SD 1.1
fmiSDCommand(pSD, 0, 0); // reset all cards
for (i=0x100; i>0; i--);
i = fmiSDCmdAndRsp(pSD, 55, 0x00, u32CmdTimeOut);
if (i == 2) // MMC memory
{
fmiSDCommand(pSD, 0, 0); // reset
for (i=0x100; i>0; i--);
_fmi_uR3_CMD = 1;
if (fmiSDCmdAndRsp(pSD, 1, 0x80ff8000, u32CmdTimeOut) != 2) // MMC memory
{
resp = inpw(REG_SDRSP0);
while (!(resp & 0x00800000)) // check if card is ready
{
_fmi_uR3_CMD = 1;
fmiSDCmdAndRsp(pSD, 1, 0x80ff8000, u32CmdTimeOut); // high voltage
resp = inpw(REG_SDRSP0);
}
pSD->uCardType = FMI_TYPE_MMC;
}
else
{
pSD->uCardType = FMI_TYPE_UNKNOWN;
return FMI_ERR_DEVICE;
}
}
else if (i == 0) // SD Memory
{
_fmi_uR3_CMD = 1;
fmiSDCmdAndRsp(pSD, 41, 0x00ff8000, u32CmdTimeOut); // 3.0v-3.4v
resp = inpw(REG_SDRSP0);
while (!(resp & 0x00800000)) // check if card is ready
{
fmiSDCmdAndRsp(pSD, 55, 0x00,u32CmdTimeOut);
_fmi_uR3_CMD = 1;
fmiSDCmdAndRsp(pSD, 41, 0x00ff8000, u32CmdTimeOut); // 3.0v-3.4v
resp = inpw(REG_SDRSP0);
}
pSD->uCardType = FMI_TYPE_SD_LOW;
}
else
{
pSD->uCardType = FMI_TYPE_UNKNOWN;
#ifdef DEBUG
sysprintf("CMD55 CRC error !!\n");
#endif
return FMI_SD_INIT_ERROR;
}
}
// CMD2, CMD3
if (pSD->uCardType != FMI_TYPE_UNKNOWN)
{
fmiSDCmdAndRsp2(pSD, 2, 0x00, CIDBuffer);
if (pSD->uCardType == FMI_TYPE_MMC)
{
if ((status = fmiSDCmdAndRsp(pSD, 3, 0x10000, 0)) != Successful) // set RCA
return status;
pSD->uRCA = 0x10000;
}
else
{
if ((status = fmiSDCmdAndRsp(pSD, 3, 0x00, 0)) != Successful) // get RCA
return status;
else
pSD->uRCA = (inpw(REG_SDRSP0) << 8) & 0xffff0000;
}
}
#ifdef DEBUG
if (pSD->uCardType == FMI_TYPE_SD_HIGH)
sysprintf("This is high capacity SD memory card\n");
if (pSD->uCardType == FMI_TYPE_SD_LOW)
sysprintf("This is standard capacity SD memory card\n");
if (pSD->uCardType == FMI_TYPE_MMC)
sysprintf("This is MMC memory card\n");
#endif
// set data transfer clock
return Successful;
}
INT fmiSwitchToHighSpeed(FMI_SD_INFO_T *pSD)
{
int volatile status=0;
UINT16 current_comsumption, fun1_info, switch_status, busy_status0, busy_status1;
outpw(REG_DMACSAR, (UINT32)_fmi_pSDHCBuffer); // set DMA transfer starting address
outpw(REG_SDBLEN, 63); // 512 bit
if ((status = fmiSDCmdAndRspDataIn(pSD, 6, 0x00ffff01)) != Successful)
return Fail;
current_comsumption = _fmi_pSDHCBuffer[0]<<8 | _fmi_pSDHCBuffer[1];
if (!current_comsumption)
return Fail;
fun1_info = _fmi_pSDHCBuffer[12]<<8 | _fmi_pSDHCBuffer[13];
switch_status = _fmi_pSDHCBuffer[16] & 0xf;
busy_status0 = _fmi_pSDHCBuffer[28]<<8 | _fmi_pSDHCBuffer[29];
if (!busy_status0) // function ready
{
outpw(REG_DMACSAR, (UINT32)_fmi_pSDHCBuffer); // set DMA transfer starting address
outpw(REG_SDBLEN, 63); // 512 bit
if ((status = fmiSDCmdAndRspDataIn(pSD, 6, 0x80ffff01)) != Successful)
return Fail;
// function change timing: 8 clocks
outpw(REG_SDCR, inpw(REG_SDCR)|SDCR_8CLK_OE);
while(inpw(REG_SDCR) & SDCR_8CLK_OE);
current_comsumption = _fmi_pSDHCBuffer[0]<<8 | _fmi_pSDHCBuffer[1];
if (!current_comsumption)
return Fail;
busy_status1 = _fmi_pSDHCBuffer[28]<<8 | _fmi_pSDHCBuffer[29];
#ifdef DEBUG
if (!busy_status1)
sysprintf("switch into high speed mode !!!\n");
#endif
return Successful;
}
else
return Fail;
}
INT fmiSelectCard(FMI_SD_INFO_T *pSD)
{
int volatile status=0, i;
if ((status = fmiSDCmdAndRsp(pSD, 7, pSD->uRCA, 0)) != Successful)
return status;
fmiCheckRB();
// if SD card set 4bit
if (pSD->uCardType == FMI_TYPE_SD_HIGH)
{
_fmi_pSDHCBuffer = (UINT8 *)((UINT32)_fmi_ucSDHCBuffer | 0x80000000);
outpw(REG_DMACSAR, (UINT32)_fmi_pSDHCBuffer); // set DMA transfer starting address
outpw(REG_SDBLEN, 7); // 64 bit
if ((status = fmiSDCmdAndRsp(pSD, 55, pSD->uRCA, 0)) != Successful)
return status;
if ((status = fmiSDCmdAndRspDataIn(pSD, 51, 0x00)) != Successful)
return status;
// #define SDHC_FREQ 50000
//#define SDHC_FREQ 48000
{
int rate;
if ((_fmi_ucSDHCBuffer[0] & 0xf) == 0x2)
{
status = fmiSwitchToHighSpeed(pSD);
if (status == Successful)
{
/* divider */
rate = _fmi_uFMIReferenceClock / SDHC_FREQ;
// if ((_fmi_uFMIReferenceClock % SDHC_FREQ) == 0)
// rate = rate - 1;
if ((_fmi_uFMIReferenceClock % SDHC_FREQ) > 0)
rate ++;
for(i=0; i<100; i++);
// outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_S) | (0x02 << 19)); // SD clock from APLL
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_S) | (0x03 << 19)); // SD clock from UPLL
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_N0) | (0x01 << 16)); // SD clock divided by 8
if (rate % 2)
{
rate /= 2;
rate &= 0xFF;
}
else
{
rate /= 2;
rate &= 0xFF;
rate--;
}
outpw(REG_CLKDIV2, (inpw(REG_CLKDIV2) & ~SD_N1) | (rate << 24)); // SD clock divider
for(i=0; i<1000; i++);
}
}
}
if ((status = fmiSDCmdAndRsp(pSD, 55, pSD->uRCA, 0)) != Successful)
return status;
if ((status = fmiSDCmdAndRsp(pSD, 6, 0x02, 0)) != Successful) // set bus width
return status;
outpw(REG_SDCR, inpw(REG_SDCR)|SDCR_DBW);
}
else if (pSD->uCardType == FMI_TYPE_SD_LOW)
{
#if 0
_fmi_pSDHCBuffer = (UINT8 *)((UINT32)_fmi_ucSDHCBuffer | 0x80000000);
outpw(REG_DMACSAR, (UINT32)_fmi_pSDHCBuffer); // set DMA transfer starting address
outpw(REG_SDBLEN, 7); // 64 bit
if ((status = fmiSDCmdAndRsp(pSD, 55, pSD->uRCA, 0)) != Successful)
return status;
if ((status = fmiSDCmdAndRspDataIn(pSD, 51, 0x00)) != Successful)
return status;
#endif
if ((status = fmiSDCmdAndRsp(pSD, 55, pSD->uRCA, 0)) != Successful)
return status;
if ((status = fmiSDCmdAndRsp(pSD, 6, 0x02, 0)) != Successful) // set bus width
return status;
outpw(REG_SDCR, inpw(REG_SDCR)|SDCR_DBW);
}
else if (pSD->uCardType == FMI_TYPE_MMC)
{
outpw(REG_SDCR, inpw(REG_SDCR) & ~SDCR_DBW);
}
if ((status = fmiSDCmdAndRsp(pSD, 16, SD_BLOCK_SIZE, 0)) != Successful) // set block length
return status;
fmiSDCommand(pSD, 7, 0);
#ifdef _SIC_USE_INT_
outpw(REG_SDIER, inpw(REG_SDIER)|SDIER_BLKD_IEN);
#endif //_SIC_USE_INT_
return Successful;
}
INT fmiSD_Read_in(FMI_SD_INFO_T *pSD, UINT32 uSector, UINT32 uBufcnt, UINT32 uDAddr)
{
BOOL volatile bIsSendCmd=FALSE;
unsigned int volatile reg;
int volatile i, loop, status;
if ((status = fmiSDCmdAndRsp(pSD, 7, pSD->uRCA, 0)) != Successful)
return status;
fmiCheckRB();
// outpw(REG_SDBLEN, 0x1ff); // 512 bytes
outpw(REG_SDBLEN, SD_BLOCK_SIZE - 1);
if (pSD->uCardType == FMI_TYPE_SD_HIGH)
outpw(REG_SDARG, uSector);
else
outpw(REG_SDARG, uSector * SD_BLOCK_SIZE);
outpw(REG_DMACSAR, uDAddr);
loop = uBufcnt / 255;
for (i=0; i<loop; i++)
{
#ifdef _SIC_USE_INT_
_fmi_bIsSDDataReady = FALSE;
#endif //_SIC_USE_INT_
reg = inpw(REG_SDCR) & ~SDCR_CMD_CODE;
reg = reg | 0xff0000;
if (bIsSendCmd == FALSE)
{
outpw(REG_SDCR, reg|(18<<8)|(SDCR_CO_EN | SDCR_RI_EN | SDCR_DI_EN));
bIsSendCmd = TRUE;
}
else
outpw(REG_SDCR, reg | SDCR_DI_EN);
#ifdef _SIC_USE_INT_
while(!_fmi_bIsSDDataReady)
#else
while(1)
#endif //_SIC_USE_INT_
{
#ifndef _SIC_USE_INT_
if ((inpw(REG_SDISR) & SDISR_BLKD_IF) && (!(inpw(REG_SDCR) & SDCR_DI_EN)))
{
outpw(REG_SDISR, SDISR_BLKD_IF);
break;
}
#endif
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_7)) // check CRC7
{
#ifdef DEBUG
sysprintf("fmiSD_Read: response error!\n");
#endif
return FMI_SD_CRC7_ERROR;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_16)) // check CRC16
{
#ifdef DEBUG
sysprintf("fmiSD_Read_in:read data error!\n");
#endif
return FMI_SD_CRC16_ERROR;
}
}
loop = uBufcnt % 255;
if (loop != 0)
{
#ifdef _SIC_USE_INT_
_fmi_bIsSDDataReady = FALSE;
#endif //_SIC_USE_INT_
reg = inpw(REG_SDCR) & (~SDCR_CMD_CODE);
reg = reg & (~SDCR_BLKCNT);
reg |= (loop << 16);
if (bIsSendCmd == FALSE)
{
outpw(REG_SDCR, reg|(18<<8)|(SDCR_CO_EN | SDCR_RI_EN | SDCR_DI_EN));
bIsSendCmd = TRUE;
}
else
outpw(REG_SDCR, reg | SDCR_DI_EN);
#ifdef _SIC_USE_INT_
while(!_fmi_bIsSDDataReady)
#else
while(1)
#endif //_SIC_USE_INT_
{
#ifndef _SIC_USE_INT_
if ((inpw(REG_SDISR) & SDISR_BLKD_IF) && (!(inpw(REG_SDCR) & SDCR_DI_EN)))
{
outpw(REG_SDISR, SDISR_BLKD_IF);
break;
}
#endif
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_7)) // check CRC7
{
#ifdef DEBUG
sysprintf("fmiSD_Read: response error!\n");
#endif
return FMI_SD_CRC7_ERROR;
}
if (!(inpw(REG_SDISR) & SDISR_CRC_16)) // check CRC16
{
#ifdef DEBUG
sysprintf("fmiSD_Read_in:read data error!\n");
#endif
return FMI_SD_CRC16_ERROR;
}
}
if (fmiSDCmdAndRsp(pSD, 12, 0, 0)) // stop command
{
#ifdef DEBUG
sysprintf("stop command fail !!\n");
#endif
return FMI_SD_CRC7_ERROR;
}
fmiCheckRB();
fmiSDCommand(pSD, 7, 0);
return Successful;
}
INT fmiSD_Write_in(FMI_SD_INFO_T *pSD, UINT32 uSector, UINT32 uBufcnt, UINT32 uSAddr)
{
BOOL volatile bIsSendCmd=FALSE;
unsigned int volatile reg;
int volatile i, loop, status;
if ((status = fmiSDCmdAndRsp(pSD, 7, pSD->uRCA, 0)) != Successful)
return status;
fmiCheckRB();
// outpw(REG_SDBLEN, 0x1ff); // 512 bytes
outpw(REG_SDBLEN, SD_BLOCK_SIZE - 1);
if (pSD->uCardType == FMI_TYPE_SD_HIGH)
outpw(REG_SDARG, uSector);
else
outpw(REG_SDARG, uSector * SD_BLOCK_SIZE);
outpw(REG_DMACSAR, uSAddr);
loop = uBufcnt / 255;
for (i=0; i<loop; i++)
{
#ifdef _SIC_USE_INT_
_fmi_bIsSDDataReady = FALSE;
#endif //_SIC_USE_INT_
reg = inpw(REG_SDCR) & 0xff00c080;
reg = reg | 0xff0000;
if (!bIsSendCmd)
{
outpw(REG_SDCR, reg|(25<<8)|0x0b);
bIsSendCmd = TRUE;
}
else
outpw(REG_SDCR, reg | 0x08);
#ifdef _SIC_USE_INT_
while(!_fmi_bIsSDDataReady)
#else
while(1)
#endif //_SIC_USE_INT_
{
#ifndef _SIC_USE_INT_
if ((inpw(REG_SDISR) & 0x01) && (!(inpw(REG_SDCR) & 0x08)))
{
outpw(REG_SDISR, 0x01);
break;
}
#endif
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if ((inpw(REG_SDISR) & 0x02) != 0) // check CRC
{
#ifdef DEBUG
sysprintf("1. fmiSD_Write:write data error [0x%x]\n", inpw(REG_SDISR));
#endif
outpw(REG_SDISR, 0x02);
return FMI_SD_CRC_ERROR;
}
}
loop = uBufcnt % 255;
if (loop != 0)
{
#ifdef _SIC_USE_INT_
_fmi_bIsSDDataReady = FALSE;
#endif //_SIC_USE_INT_
reg = (inpw(REG_SDCR) & 0xff00c080) | (loop << 16);
if (!bIsSendCmd)
{
outpw(REG_SDCR, reg|(25<<8)|0x0b);
bIsSendCmd = TRUE;
}
else
outpw(REG_SDCR, reg | 0x08);
#ifdef _SIC_USE_INT_
while(!_fmi_bIsSDDataReady)
#else
while(1)
#endif //_SIC_USE_INT_
{
#ifndef _SIC_USE_INT_
if ((inpw(REG_SDISR) & 0x01) && (!(inpw(REG_SDCR) & 0x08)))
{
outpw(REG_SDISR, 0x01);
break;
}
#endif
if (pSD->bIsCardInsert == FALSE)
return FMI_NO_SD_CARD;
}
if ((inpw(REG_SDISR) & 0x02) != 0) // check CRC
{
#ifdef DEBUG
sysprintf("2. fmiSD_Write:write data error [0x%x]!\n", inpw(REG_SDISR));
#endif
outpw(REG_SDISR, 0x02);
return FMI_SD_CRC_ERROR;
}
}
outpw(REG_SDISR, 0x02);
if (fmiSDCmdAndRsp(pSD, 12, 0, 0)) // stop command
{
#ifdef DEBUG
sysprintf("stop command fail !!\n");
#endif
return FMI_SD_CRC7_ERROR;
}
fmiCheckRB();
fmiSDCommand(pSD, 7, 0);
return Successful;
}
VOID fmiGet_SD_info(FMI_SD_INFO_T *pSD, DISK_DATA_T *_info)
{
unsigned int i;
unsigned int R_LEN, C_Size, MULT, size;
unsigned int Buffer[4];
unsigned char *ptr;
fmiSDCmdAndRsp2(pSD, 9, pSD->uRCA, Buffer);
#ifdef DEBUG
sysprintf("max. data transfer rate [%x][%08x]\n", Buffer[0]&0xff, Buffer[0]);
#endif
if ((Buffer[0] & 0xc0000000) && (pSD->uCardType != FMI_TYPE_MMC))
{
C_Size = ((Buffer[1] & 0x0000003f) << 16) | ((Buffer[2] & 0xffff0000) >> 16);
size = (C_Size+1) * 512; // Kbytes
_info->diskSize = size;
_info->totalSectorN = size << 1;
}
else
{
R_LEN = (Buffer[1] & 0x000f0000) >> 16;
C_Size = ((Buffer[1] & 0x000003ff) << 2) | ((Buffer[2] & 0xc0000000) >> 30);
MULT = (Buffer[2] & 0x00038000) >> 15;
size = (C_Size+1) * (1<<(MULT+2)) * (1<<R_LEN);
_info->diskSize = size / 1024;
_info->totalSectorN = size / 512;
}
_info->sectorSize = 512;
fmiSDCmdAndRsp2(pSD, 10, pSD->uRCA, Buffer);
_info->vendor[0] = (Buffer[0] & 0xff000000) >> 24;
ptr = (unsigned char *)Buffer;
ptr = ptr + 4;
for (i=0; i<5; i++)
_info->product[i] = *ptr++;
ptr = ptr + 10;
for (i=0; i<4; i++)
_info->serial[i] = *ptr++;
}
#if 0
int SdChipErase(FMI_SD_INFO_T *pSD, DISK_DATA_T *_info)
{
int status=0;
//sysprintf("doing erase ...\n");
status = fmiSDCmdAndRsp(pSD, 32, 512, 6000);
if (status < 0)
{
//sysprintf("1.. ");
return status;
}
status = fmiSDCmdAndRsp(pSD, 33, _info->totalSectorN*512, 6000);
if (status < 0)
{
//sysprintf("2.. ");
return status;
}
status = fmiSDCmdAndRsp(pSD, 38, 0, 6000);
if (status < 0)
{
//sysprintf("3.. ");
return status;
}
fmiCheckRB();
//sysprintf("finish erase !!!\n");
return 0;
}
#endif
<file_sep>/Font/Example/Writer.h
#define MAJOR_VERSION_NUM 1
#define MINOR_VERSION_NUM 3
extern UINT g_Font_Height, g_Font_Width, g_Font_Step;
#define COLOR_RGB16_RED 0xF800
#define COLOR_RGB16_WHITE 0xFFFF
#define COLOR_RGB16_GREEN 0x07E0
#define COLOR_RGB16_BLUE 0x001F
#define COLOR_RGB16_BLACK 0x0000
#define NVT_SM_INFO_T FMI_SM_INFO_T
/* F/W update information */
typedef struct fw_update_info_t
{
UINT16 imageNo;
UINT16 imageFlag;
UINT16 startBlock;
UINT16 endBlock;
UINT32 executeAddr;
UINT32 fileLen;
CHAR imageName[32];
} FW_UPDATE_INFO_T;
typedef struct IBR_boot_struct_t
{
UINT32 BootCodeMarker;
UINT32 ExeAddr;
UINT32 ImageSize;
UINT32 SkewMarker;
UINT32 DQSODS;
UINT32 CLKQSDS;
UINT32 DRAMMarker;
UINT32 DRAMSize;
} IBR_BOOT_STRUCT_T;
typedef struct INI_Info {
char NandLoader[512];
char Logo[512];
char NVTLoader[512];
int SystemReservedMegaByte;
int NAND1_1_SIZE;
int NAND1_1_FAT;
int NAND1_2_FAT;
} INI_INFO_T;
/* extern parameters */
extern UINT32 infoBuf;
extern FMI_SM_INFO_T *pNvtSM0;
extern UINT8 *pInfo;
extern INT8 nIsSysImage;
INT nvtSMInit(void);
INT setNandPartition(INT sysArea);
INT nvtSMchip_erase(UINT32 startBlcok, UINT32 endBlock);
INT nvtSMpread(INT PBA, INT page, UINT8 *buff);
INT nvtSMpwrite(INT PBA, INT page, UINT8 *buff);
INT nvtSMblock_erase(INT PBA);
INT CheckBadBlockMark(UINT32 block);
INT fmiNormalCheckBlock(FMI_SM_INFO_T *pSM, UINT32 BlockNo);
void Draw_Font(UINT16 u16RGB,S_DEMO_FONT* ptFont,UINT32 u32x,UINT32 u32y,PCSTR pszString);
void Draw_Status(UINT32 u32x,UINT32 u32y,int Status);
void Draw_Clear(int xStart, int yStart, int xEnd, int yEnd, UINT16 color);
void Draw_CurrentOperation(PCSTR pszString, int Retcode);
void Draw_FinalStatus(int bIsAbort);
void Draw_Init(void);
void Draw_Wait_Status(UINT32 u32x, UINT32 u32y);
void Draw_Clear_Wait_Status(UINT32 u32x, UINT32 u32y);
int ProcessINI(char *fileName);
<file_sep>/gpio/example/gpio.c
/****************************************************************************
* *
* Copyright (c) 2009 Nuvoton Tech. Corp. All rights reserved. *
* *
*****************************************************************************/
/****************************************************************************
* FILENAME
* gpio.c
*
* VERSION
* 1.0
*
* DESCRIPTION
* GPIO sample application using GPIO library. Pull up and low port D pins
*
* DATA STRUCTURES
* None
*
* FUNCTIONS
*
* HISTORY
*
* REMARK
* None
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_gpio.h"
int main(void)
{
WB_UART_T uart;
UINT32 u32ExtFreq;
int i;
sysSetSystemClock(eSYS_UPLL, //E_SYS_SRC_CLK eSrcClk,
192000, //UINT32 u32PllKHz,
192000, //UINT32 u32SysKHz,
192000, //UINT32 u32CpuKHz,
96000, //UINT32 u32HclkKHz,
48000); //UINT32 u32ApbKHz
u32ExtFreq = sysGetExternalClock();
uart.uiFreq = u32ExtFreq*1000;
uart.uiBaudrate = 115200;
uart.uiDataBits = WB_DATA_BITS_8;
uart.uiStopBits = WB_STOP_BITS_1;
uart.uiParity = WB_PARITY_NONE;
uart.uiRxTriggerLevel = LEVEL_1_BYTE;
sysInitializeUART(&uart);
sysEnableCache(I_D_CACHE);
gpio_setportval(GPIO_PORTB, 0xf, 0);
gpio_setportpull(GPIO_PORTB, 0xf, 0);
gpio_setportdir(GPIO_PORTB, 0xf, 0xf);
sysprintf("start gpio test... \n");
while(1) {
for(i = 0; i < 0xf; i++) {
gpio_setportval(GPIO_PORTB, 0xf, i);
sysDelay(100);
}
}
sysprintf("quit gpio test\n");
return(0);
}<file_sep>/I2C/example/demo/main.c
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2008 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#ifdef ECOS
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "kapi.h"
#include "diag.h"
#include "wbio.h"
#else
#include <stdio.h>
#include <string.h>
#include "wblib.h"
#endif
#include "w55fa93_i2c.h"
#include "W55FA93_VideoIn.h"
#define DBG_PRINTF sysprintf
//#define DBG_PRINTF(...)
#define RETRY 10 /* Programming cycle may be in progress. Please refer to 24LC64 datasheet */
int main (VOID)
{
WB_UART_T uart;
UINT32 u32ExtFreq;
UINT8 u8DeviceID;
UINT8 u8ID;
INT32 rtval;
INT j;
sysUartPort(1);
uart.uiFreq =sysGetExternalClock()*1000; //use APB clock
uart.uiBaudrate = 115200;
uart.uiDataBits = WB_DATA_BITS_8;
uart.uiStopBits = WB_STOP_BITS_1;
uart.uiParity = WB_PARITY_NONE;
uart.uiRxTriggerLevel = LEVEL_1_BYTE;
sysInitializeUART(&uart);
DBG_PRINTF("\nI2C demo read OV7670 sensor ID...\n");
sysSetSystemClock(eSYS_UPLL, //E_SYS_SRC_CLK eSrcClk,
192000, //UINT32 u32PllKHz,
192000, //UINT32 u32SysKHz,
192000, //UINT32 u32CpuKHz,
96000, //UINT32 u32HclkKHz,
48000); //UINT32 u32ApbKHz
sysEnableCache(CACHE_WRITE_BACK);
/* init timer */
u32ExtFreq = sysGetExternalClock(); /* KHz unit */
sysSetTimerReferenceClock (TIMER0,
u32ExtFreq*1000); /* Hz unit */
sysStartTimer(TIMER0,
100,
PERIODIC_MODE);
videoIn_Init(TRUE, 0, 24000, eVIDEOIN_SNR_CCIR601);
videoIn_Open(48000, 24000); /* For sensor clock output */
i2cInit();
rtval = i2cOpen();
if(rtval < 0)
{
DBG_PRINTF("Open I2C error!\n");
goto exit_test;
}
u8DeviceID = 0x42;
i2cIoctl(I2C_IOC_SET_DEV_ADDRESS, (u8DeviceID>>1), 0);
i2cIoctl(I2C_IOC_SET_SPEED, 100, 0);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0x0A, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j <= 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0x0A);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0x0B, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j <= 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0x0B);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0x1C, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j < 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0x1C);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0x1D, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j < 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0x1D);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0xD7, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j < 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0xD7);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
i2cIoctl(I2C_IOC_SET_SUB_ADDRESS, 0x6A, 1);
j = RETRY;
while(j-- > 0)
{
if(i2cRead_OV(&u8ID, 1) == 1)
break;
}
if(j < 0)
DBG_PRINTF("Read ERROR [%x]!\n", 0x6A);
DBG_PRINTF("Sensor ID0 = 0x%x\n", u8ID);
exit_test:
return 0;
}
<file_sep>/SPI/Lib/SPIGlue.h
#include <stdio.h>
#include "wbio.h"
#define TIMER0 0
//-- function return value
#define Successful 0
#define Fail 1
#define STOR_STRING_LEN 32
/* we allocate one of these for every device that we remember */
typedef struct disk_data_t
{
struct disk_data_t *next; /* next device */
/* information about the device -- always good */
unsigned int totalSectorN; /* SPI flash size in Kbyte*/
unsigned int diskSize; /* disk size in Kbytes */
int sectorSize;
char vendor[STOR_STRING_LEN];
char product[STOR_STRING_LEN];
char serial[STOR_STRING_LEN];
} DISK_DATA_T;
#define SPI_NO_MEMORY (SPI_ERR_ID|0x02)
#define SPI_INIT_TIMEOUT (SPI_ERR_ID|0x12)<file_sep>/Font/Lib/Font.h
/****************************************************************
* *
* Copyright (c) Nuvoton Technology Corp. All rights reserved. *
* *
****************************************************************/
#ifndef __FONT_H__
#define __FONT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "wblib.h"
typedef struct
{
UINT32 volatile u32FontRectWidth;
UINT32 volatile u32FontRectHeight;
UINT32 volatile u32FontOffset;
UINT32 volatile u32FontStep;
UINT32 volatile u32FontOutputStride;
UINT32 volatile u32FontInitDone;
UINT32 u32FontFileSize;
PUINT32 pu32FontFileTmp;
PUINT32 pu32FontFile;
UINT16 au16FontColor[3];
} S_DEMO_FONT;
typedef struct
{
UINT32 volatile u32StartX;
UINT32 volatile u32StartY;
UINT32 volatile u32EndX;
UINT32 volatile u32EndY;
} S_DEMO_RECT;
/* Please choice a option */
//#define _DEMO_WVGA_ /* 480x272 */
//#define _DEMO_QVGA_ /* 320x240 */
//#define _DEMO_VGA_ /* 640x480 */
//#define _DEMO_WSVGA_ /* 800x480 */
#define _BPP_ 2
#define _BORDER_WIDTH_ 2 //2 Pixels
#ifdef _DEMO_WVGA_
#define _FONT_STRIDE_ 480
#define _FONT_LINE_ 47 //480/10 = 48,
#define _LCM_WIDTH_ 480
#define _LCM_HEIGHT_ 272
#endif
#ifdef _DEMO_QVGA_
#define _FONT_STRIDE_ 320
#define _FONT_LINE_ 31 //320/10 = 32,
#define _LCM_WIDTH_ 320
#define _LCM_HEIGHT_ 240
#endif
#ifdef _DEMO_VGA_
#define _FONT_STRIDE_ 640
#define _FONT_LINE_ 63 //640/10 = 64,
#define _LCM_WIDTH_ 640
#define _LCM_HEIGHT_ 480
#endif
#ifdef _DEMO_WSVGA_
#define _FONT_STRIDE_ 800
#define _FONT_LINE_ 79 //800/10 = 80,
#define _LCM_WIDTH_ 800
#define _LCM_HEIGHT_ 480
#endif
#define _FONT_ASCII_START_ 32
#define _FONT_ASCII_END_ 126
#define _FONT_ASCII_OUTRANGE_ (63 - _FONT_ASCII_START_)
#define _FONT_RECT_WIDTH_ 16
#define _FONT_RECT_HEIGHT_ 22
#define _FONT_OFFSET_ 10
#define _FONT_COLOR_BG_ 0x0000
#define _FONT_COLOR_ 0x7FFF
#define _FONT_COLOR_BORDER_ 0x001F
#ifndef NULL
#define NULL 0
#endif
void
InitFont(
S_DEMO_FONT* ptFont,
UINT32 u32FrameBufAddr
);
void
UnInitFont(S_DEMO_FONT* ptFont);
void
DemoFont_PaintA(
S_DEMO_FONT* ptFont,
UINT32 u32x,
UINT32 u32y,
PCSTR pszString
);
void
DemoFont_Rect(
S_DEMO_FONT* ptFont,
S_DEMO_RECT* ptRect
);
void
DemoFont_RectClear(
S_DEMO_FONT* ptFont,
S_DEMO_RECT* ptRect
);
void
DemoFont_Border(
S_DEMO_FONT* ptFont,
S_DEMO_RECT* ptRect,
UINT32 u32Width
);
void Font_ClrFrameBuffer(UINT32 u32FrameBufAddr);
void
DemoFont_ChangeFontColor(
S_DEMO_FONT* ptFont,
UINT16 u16TRGB565
);
UINT16
DemoFont_GetFontColor(
S_DEMO_FONT* ptFont
);
#ifdef __cplusplus
}
#endif
#endif //__FONT_H__
<file_sep>/SIC_SECC/Src/Ecc4DecoderRiBmLookup.h
#ifndef __ECC4DECODERRIBMLOOKUP_H__
#define __ECC4DECODERRIBMLOOKUP_H__
unsigned short int g_au16RiBmLookup[1024] =
{
0x000, 0x102, 0x081, 0x183, 0x200, 0x302, 0x281, 0x383,
0x100, 0x002, 0x181, 0x083, 0x300, 0x202, 0x381, 0x283,
0x080, 0x182, 0x001, 0x103, 0x280, 0x382, 0x201, 0x303,
0x180, 0x082, 0x101, 0x003, 0x380, 0x282, 0x301, 0x203,
0x040, 0x142, 0x0c1, 0x1c3, 0x240, 0x342, 0x2c1, 0x3c3,
0x140, 0x042, 0x1c1, 0x0c3, 0x340, 0x242, 0x3c1, 0x2c3,
0x0c0, 0x1c2, 0x041, 0x143, 0x2c0, 0x3c2, 0x241, 0x343,
0x1c0, 0x0c2, 0x141, 0x043, 0x3c0, 0x2c2, 0x341, 0x243,
0x020, 0x122, 0x0a1, 0x1a3, 0x220, 0x322, 0x2a1, 0x3a3,
0x120, 0x022, 0x1a1, 0x0a3, 0x320, 0x222, 0x3a1, 0x2a3,
0x0a0, 0x1a2, 0x021, 0x123, 0x2a0, 0x3a2, 0x221, 0x323,
0x1a0, 0x0a2, 0x121, 0x023, 0x3a0, 0x2a2, 0x321, 0x223,
0x060, 0x162, 0x0e1, 0x1e3, 0x260, 0x362, 0x2e1, 0x3e3,
0x160, 0x062, 0x1e1, 0x0e3, 0x360, 0x262, 0x3e1, 0x2e3,
0x0e0, 0x1e2, 0x061, 0x163, 0x2e0, 0x3e2, 0x261, 0x363,
0x1e0, 0x0e2, 0x161, 0x063, 0x3e0, 0x2e2, 0x361, 0x263,
0x112, 0x010, 0x193, 0x091, 0x312, 0x210, 0x393, 0x291,
0x012, 0x110, 0x093, 0x191, 0x212, 0x310, 0x293, 0x391,
0x192, 0x090, 0x113, 0x011, 0x392, 0x290, 0x313, 0x211,
0x092, 0x190, 0x013, 0x111, 0x292, 0x390, 0x213, 0x311,
0x152, 0x050, 0x1d3, 0x0d1, 0x352, 0x250, 0x3d3, 0x2d1,
0x052, 0x150, 0x0d3, 0x1d1, 0x252, 0x350, 0x2d3, 0x3d1,
0x1d2, 0x0d0, 0x153, 0x051, 0x3d2, 0x2d0, 0x353, 0x251,
0x0d2, 0x1d0, 0x053, 0x151, 0x2d2, 0x3d0, 0x253, 0x351,
0x132, 0x030, 0x1b3, 0x0b1, 0x332, 0x230, 0x3b3, 0x2b1,
0x032, 0x130, 0x0b3, 0x1b1, 0x232, 0x330, 0x2b3, 0x3b1,
0x1b2, 0x0b0, 0x133, 0x031, 0x3b2, 0x2b0, 0x333, 0x231,
0x0b2, 0x1b0, 0x033, 0x131, 0x2b2, 0x3b0, 0x233, 0x331,
0x172, 0x070, 0x1f3, 0x0f1, 0x372, 0x270, 0x3f3, 0x2f1,
0x072, 0x170, 0x0f3, 0x1f1, 0x272, 0x370, 0x2f3, 0x3f1,
0x1f2, 0x0f0, 0x173, 0x071, 0x3f2, 0x2f0, 0x373, 0x271,
0x0f2, 0x1f0, 0x073, 0x171, 0x2f2, 0x3f0, 0x273, 0x371,
0x089, 0x18b, 0x008, 0x10a, 0x289, 0x38b, 0x208, 0x30a,
0x189, 0x08b, 0x108, 0x00a, 0x389, 0x28b, 0x308, 0x20a,
0x009, 0x10b, 0x088, 0x18a, 0x209, 0x30b, 0x288, 0x38a,
0x109, 0x00b, 0x188, 0x08a, 0x309, 0x20b, 0x388, 0x28a,
0x0c9, 0x1cb, 0x048, 0x14a, 0x2c9, 0x3cb, 0x248, 0x34a,
0x1c9, 0x0cb, 0x148, 0x04a, 0x3c9, 0x2cb, 0x348, 0x24a,
0x049, 0x14b, 0x0c8, 0x1ca, 0x249, 0x34b, 0x2c8, 0x3ca,
0x149, 0x04b, 0x1c8, 0x0ca, 0x349, 0x24b, 0x3c8, 0x2ca,
0x0a9, 0x1ab, 0x028, 0x12a, 0x2a9, 0x3ab, 0x228, 0x32a,
0x1a9, 0x0ab, 0x128, 0x02a, 0x3a9, 0x2ab, 0x328, 0x22a,
0x029, 0x12b, 0x0a8, 0x1aa, 0x229, 0x32b, 0x2a8, 0x3aa,
0x129, 0x02b, 0x1a8, 0x0aa, 0x329, 0x22b, 0x3a8, 0x2aa,
0x0e9, 0x1eb, 0x068, 0x16a, 0x2e9, 0x3eb, 0x268, 0x36a,
0x1e9, 0x0eb, 0x168, 0x06a, 0x3e9, 0x2eb, 0x368, 0x26a,
0x069, 0x16b, 0x0e8, 0x1ea, 0x269, 0x36b, 0x2e8, 0x3ea,
0x169, 0x06b, 0x1e8, 0x0ea, 0x369, 0x26b, 0x3e8, 0x2ea,
0x19b, 0x099, 0x11a, 0x018, 0x39b, 0x299, 0x31a, 0x218,
0x09b, 0x199, 0x01a, 0x118, 0x29b, 0x399, 0x21a, 0x318,
0x11b, 0x019, 0x19a, 0x098, 0x31b, 0x219, 0x39a, 0x298,
0x01b, 0x119, 0x09a, 0x198, 0x21b, 0x319, 0x29a, 0x398,
0x1db, 0x0d9, 0x15a, 0x058, 0x3db, 0x2d9, 0x35a, 0x258,
0x0db, 0x1d9, 0x05a, 0x158, 0x2db, 0x3d9, 0x25a, 0x358,
0x15b, 0x059, 0x1da, 0x0d8, 0x35b, 0x259, 0x3da, 0x2d8,
0x05b, 0x159, 0x0da, 0x1d8, 0x25b, 0x359, 0x2da, 0x3d8,
0x1bb, 0x0b9, 0x13a, 0x038, 0x3bb, 0x2b9, 0x33a, 0x238,
0x0bb, 0x1b9, 0x03a, 0x138, 0x2bb, 0x3b9, 0x23a, 0x338,
0x13b, 0x039, 0x1ba, 0x0b8, 0x33b, 0x239, 0x3ba, 0x2b8,
0x03b, 0x139, 0x0ba, 0x1b8, 0x23b, 0x339, 0x2ba, 0x3b8,
0x1fb, 0x0f9, 0x17a, 0x078, 0x3fb, 0x2f9, 0x37a, 0x278,
0x0fb, 0x1f9, 0x07a, 0x178, 0x2fb, 0x3f9, 0x27a, 0x378,
0x17b, 0x079, 0x1fa, 0x0f8, 0x37b, 0x279, 0x3fa, 0x2f8,
0x07b, 0x179, 0x0fa, 0x1f8, 0x27b, 0x379, 0x2fa, 0x3f8,
0x204, 0x306, 0x285, 0x387, 0x004, 0x106, 0x085, 0x187,
0x304, 0x206, 0x385, 0x287, 0x104, 0x006, 0x185, 0x087,
0x284, 0x386, 0x205, 0x307, 0x084, 0x186, 0x005, 0x107,
0x384, 0x286, 0x305, 0x207, 0x184, 0x086, 0x105, 0x007,
0x244, 0x346, 0x2c5, 0x3c7, 0x044, 0x146, 0x0c5, 0x1c7,
0x344, 0x246, 0x3c5, 0x2c7, 0x144, 0x046, 0x1c5, 0x0c7,
0x2c4, 0x3c6, 0x245, 0x347, 0x0c4, 0x1c6, 0x045, 0x147,
0x3c4, 0x2c6, 0x345, 0x247, 0x1c4, 0x0c6, 0x145, 0x047,
0x224, 0x326, 0x2a5, 0x3a7, 0x024, 0x126, 0x0a5, 0x1a7,
0x324, 0x226, 0x3a5, 0x2a7, 0x124, 0x026, 0x1a5, 0x0a7,
0x2a4, 0x3a6, 0x225, 0x327, 0x0a4, 0x1a6, 0x025, 0x127,
0x3a4, 0x2a6, 0x325, 0x227, 0x1a4, 0x0a6, 0x125, 0x027,
0x264, 0x366, 0x2e5, 0x3e7, 0x064, 0x166, 0x0e5, 0x1e7,
0x364, 0x266, 0x3e5, 0x2e7, 0x164, 0x066, 0x1e5, 0x0e7,
0x2e4, 0x3e6, 0x265, 0x367, 0x0e4, 0x1e6, 0x065, 0x167,
0x3e4, 0x2e6, 0x365, 0x267, 0x1e4, 0x0e6, 0x165, 0x067,
0x316, 0x214, 0x397, 0x295, 0x116, 0x014, 0x197, 0x095,
0x216, 0x314, 0x297, 0x395, 0x016, 0x114, 0x097, 0x195,
0x396, 0x294, 0x317, 0x215, 0x196, 0x094, 0x117, 0x015,
0x296, 0x394, 0x217, 0x315, 0x096, 0x194, 0x017, 0x115,
0x356, 0x254, 0x3d7, 0x2d5, 0x156, 0x054, 0x1d7, 0x0d5,
0x256, 0x354, 0x2d7, 0x3d5, 0x056, 0x154, 0x0d7, 0x1d5,
0x3d6, 0x2d4, 0x357, 0x255, 0x1d6, 0x0d4, 0x157, 0x055,
0x2d6, 0x3d4, 0x257, 0x355, 0x0d6, 0x1d4, 0x057, 0x155,
0x336, 0x234, 0x3b7, 0x2b5, 0x136, 0x034, 0x1b7, 0x0b5,
0x236, 0x334, 0x2b7, 0x3b5, 0x036, 0x134, 0x0b7, 0x1b5,
0x3b6, 0x2b4, 0x337, 0x235, 0x1b6, 0x0b4, 0x137, 0x035,
0x2b6, 0x3b4, 0x237, 0x335, 0x0b6, 0x1b4, 0x037, 0x135,
0x376, 0x274, 0x3f7, 0x2f5, 0x176, 0x074, 0x1f7, 0x0f5,
0x276, 0x374, 0x2f7, 0x3f5, 0x076, 0x174, 0x0f7, 0x1f5,
0x3f6, 0x2f4, 0x377, 0x275, 0x1f6, 0x0f4, 0x177, 0x075,
0x2f6, 0x3f4, 0x277, 0x375, 0x0f6, 0x1f4, 0x077, 0x175,
0x28d, 0x38f, 0x20c, 0x30e, 0x08d, 0x18f, 0x00c, 0x10e,
0x38d, 0x28f, 0x30c, 0x20e, 0x18d, 0x08f, 0x10c, 0x00e,
0x20d, 0x30f, 0x28c, 0x38e, 0x00d, 0x10f, 0x08c, 0x18e,
0x30d, 0x20f, 0x38c, 0x28e, 0x10d, 0x00f, 0x18c, 0x08e,
0x2cd, 0x3cf, 0x24c, 0x34e, 0x0cd, 0x1cf, 0x04c, 0x14e,
0x3cd, 0x2cf, 0x34c, 0x24e, 0x1cd, 0x0cf, 0x14c, 0x04e,
0x24d, 0x34f, 0x2cc, 0x3ce, 0x04d, 0x14f, 0x0cc, 0x1ce,
0x34d, 0x24f, 0x3cc, 0x2ce, 0x14d, 0x04f, 0x1cc, 0x0ce,
0x2ad, 0x3af, 0x22c, 0x32e, 0x0ad, 0x1af, 0x02c, 0x12e,
0x3ad, 0x2af, 0x32c, 0x22e, 0x1ad, 0x0af, 0x12c, 0x02e,
0x22d, 0x32f, 0x2ac, 0x3ae, 0x02d, 0x12f, 0x0ac, 0x1ae,
0x32d, 0x22f, 0x3ac, 0x2ae, 0x12d, 0x02f, 0x1ac, 0x0ae,
0x2ed, 0x3ef, 0x26c, 0x36e, 0x0ed, 0x1ef, 0x06c, 0x16e,
0x3ed, 0x2ef, 0x36c, 0x26e, 0x1ed, 0x0ef, 0x16c, 0x06e,
0x26d, 0x36f, 0x2ec, 0x3ee, 0x06d, 0x16f, 0x0ec, 0x1ee,
0x36d, 0x26f, 0x3ec, 0x2ee, 0x16d, 0x06f, 0x1ec, 0x0ee,
0x39f, 0x29d, 0x31e, 0x21c, 0x19f, 0x09d, 0x11e, 0x01c,
0x29f, 0x39d, 0x21e, 0x31c, 0x09f, 0x19d, 0x01e, 0x11c,
0x31f, 0x21d, 0x39e, 0x29c, 0x11f, 0x01d, 0x19e, 0x09c,
0x21f, 0x31d, 0x29e, 0x39c, 0x01f, 0x11d, 0x09e, 0x19c,
0x3df, 0x2dd, 0x35e, 0x25c, 0x1df, 0x0dd, 0x15e, 0x05c,
0x2df, 0x3dd, 0x25e, 0x35c, 0x0df, 0x1dd, 0x05e, 0x15c,
0x35f, 0x25d, 0x3de, 0x2dc, 0x15f, 0x05d, 0x1de, 0x0dc,
0x25f, 0x35d, 0x2de, 0x3dc, 0x05f, 0x15d, 0x0de, 0x1dc,
0x3bf, 0x2bd, 0x33e, 0x23c, 0x1bf, 0x0bd, 0x13e, 0x03c,
0x2bf, 0x3bd, 0x23e, 0x33c, 0x0bf, 0x1bd, 0x03e, 0x13c,
0x33f, 0x23d, 0x3be, 0x2bc, 0x13f, 0x03d, 0x1be, 0x0bc,
0x23f, 0x33d, 0x2be, 0x3bc, 0x03f, 0x13d, 0x0be, 0x1bc,
0x3ff, 0x2fd, 0x37e, 0x27c, 0x1ff, 0x0fd, 0x17e, 0x07c,
0x2ff, 0x3fd, 0x27e, 0x37c, 0x0ff, 0x1fd, 0x07e, 0x17c,
0x37f, 0x27d, 0x3fe, 0x2fc, 0x17f, 0x07d, 0x1fe, 0x0fc,
0x27f, 0x37d, 0x2fe, 0x3fc, 0x07f, 0x17d, 0x0fe, 0x1fc
};
#endif<file_sep>/VIDEOIN/Example/Smpl_VPOST_Init.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wbio.h"
#include "wbtypes.h"
#include "W55fa93_vpost.h"
void InitVPOST(UINT8* pu8FrameBuffer)
{
LCDFORMATEX lcdFormat;
lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_RGB565;
lcdFormat.nScreenWidth = 480;
lcdFormat.nScreenHeight = 272;
vpostLCMInit(&lcdFormat, (UINT32*)pu8FrameBuffer);
} <file_sep>/SYSLIB/Src/wb_power.c
/***************************************************************************
* *
* Copyright (c) 2008 Nuvoton Technolog. All rights reserved. *
* *
***************************************************************************/
/****************************************************************************
* FILENAME
* wb_power.c
*
* VERSION
* 1.0
*
* DESCRIPTION
* The power managemnet related function of Nuvoton ARM9 MCU
*
* DATA STRUCTURES
* None
*
* FUNCTIONS
* sysDisableAllPM_IRQ
* sysEnablePM_IRQ
* sysPMStart
*
* HISTORY
* 2008-07-24 Ver 1.0 Modified by <NAME>
*
* REMARK
* When enter PD or MIDLE mode, the sysPMStart function will disable cache
* (in order to access SRAM) and then recovery it after wake up.
****************************************************************************/
#include <string.h>
#include "wblib.h"
extern BOOL sysGetCacheState(VOID);
extern INT32 sysGetCacheMode(VOID);
extern INT32 _sysLockCode(UINT32, INT32);
extern INT32 _sysUnLockCode(VOID);
static UINT32 volatile _sys_PM_IRQ = 0;
UINT8 _tmp_buf[PD_RAM_SIZE];
/****************************************************************************
* FUNCTION
* sysEnablePM_IRQ
*
* DESCRIPTION
* This function is use to set _sys_PM_IRQ variable. The _sys_PM_IRQ variable
* save the IRQ channel which use to wake up the system form IDLE, MIDLE, and
* PD mode
*
* INPUTS
* irq_no The interrupt channel
*
* OUTPUTS
* Successful The interrupt channel saved successfully
* WB_PM_INVALID_IRQ_NUM The interrupt channel number out of range
*
****************************************************************************/
INT sysEnablePM_IRQ(INT irq_no) // set the PM needed IRQ flag
{
if ((irq_no > 31) || (irq_no < 1))
{
return WB_PM_INVALID_IRQ_NUM;
}
_sys_PM_IRQ = _sys_PM_IRQ | (UINT32)(1<<irq_no);
return Successful;
}
/****************************************************************************
* FUNCTION
* sysDisableAllPM_IRQ
*
* DESCRIPTION
* This function is use to reset the _sys_PM_IRQ variable.
*
* INPUTS
* None
*
* OUTPUTS
* None
*
****************************************************************************/
VOID sysDisableAllPM_IRQ(VOID) // clear the PM IRQ flag
{
_sys_PM_IRQ = 0;
}
/****************************************************************************
* FUNCTION
* _sysEnterPowerSavingMode
*
* DESCRIPTION
* This function is use to enter idle or power down mode
*
* INPUTS
* None
*
* OUTPUTS
* None
*
****************************************************************************/
VOID _sysEnterPowerSavingMode(INT mode, UINT32 irqno)
{
volatile UINT32 i;
outpw(REG_AIC_MECR, irqno); /* interrupt source to return from power saving mode */
//outpw(REG_PMCON, mode); /* write control register to enter power saving mode */
outpw(REG_SDCMD, inpw(REG_SDCMD) |
(AUTOEXSELFREF | REF_CMD));
__asm
{
mov r2, 0xb0000200
ldmia r2, {r0, r1}
bic r0, r0, #0x01
bic r1, r1, #0x01
stmia r2, {r0, r1}
}
for (i=0; i<0x100; i++) ;
}
/****************************************************************************
* FUNCTION
* sysPMStart
*
* DESCRIPTION
* This function is use to enter power saving mode.
*
* INPUTS
* pd_type WB_PM_IDLE/WB_PM_MIDLE/WB_PM_PD
* The Power saving mode
*
* OUTPUTS
* Successful Enter power saving mode and wake up successfully
* WB_PM_PD_IRQ_Fail Enter PD mode without enable one of USB DEVICE, KPI,
* RTC or nIRQ
* which supports to wake up the system from PD mode
* WB_PM_Type_Fail pd_type error
* WB_PM_CACHE_OFF cache is disabled that can not lock necessary
* instructions into cache
*
****************************************************************************/
INT sysPMStart(INT pd_type)
{
E_SYS_SRC_CLK eSrcClk;
UINT32 u32PllKHz;
UINT32 u32SysKHz;
UINT32 u32CpuKHz;
UINT32 u32HclkKHz;
UINT32 u32ApbKHz;
VOID (*wb_func)(INT32, UINT32);
UINT32 vram_base, aic_status = 0;
if(pd_type != WB_PM_IDLE && pd_type != WB_PM_MIDLE && pd_type != WB_PM_PD)
{
return WB_PM_Type_Fail;
}
if(pd_type == WB_PM_PD)
{
// Enter PD mode, but IRQ setting error
// one of nIRQ0~7, KPI, RTC or USBD_INT must enable when enter PD mode
if (!(_sys_PM_IRQ & (1<<IRQ_EXTINT0 | 1<<IRQ_EXTINT1 | 1<<IRQ_EXTINT2 | 1<<IRQ_EXTINT3 | 1<<IRQ_ADC)))
{
return WB_PM_PD_IRQ_Fail;
}
}
aic_status = inpw(REG_AIC_IMR);
outpw(REG_AIC_MDCR, 0xFFFFFFFF);
if ((pd_type == WB_PM_MIDLE) || (pd_type == WB_PM_PD))
{
//use VRAM Block 1 to store power down function
vram_base = PD_RAM_BASE;
memcpy((VOID *)_tmp_buf, (VOID *)vram_base, PD_RAM_SIZE);
memcpy((VOID *)vram_base,(VOID *)_sysEnterPowerSavingMode, PD_RAM_SIZE);
}
#if 0
// Select CPU clock from external clock source
sysGetPLLConfig(&_oldsysClk);
_newsysClk.pll0 = PLL_DISABLE;
_newsysClk.cpu_src = CPU_FROM_EXTERNAL;
_newsysClk.ahb_clk = AHB_CPUCLK_1_1;
_newsysClk.apb_clk = APB_AHB_1_2;
sysSetPLLConfig(&_newsysClk);
#else
sysGetSystemClock(&eSrcClk,
&u32PllKHz,
&u32SysKHz,
&u32CpuKHz,
&u32HclkKHz,
&u32ApbKHz);
#endif
// Entering Power saving mode
wb_func = (void(*)(INT32, UINT32)) vram_base;
wb_func(pd_type, _sys_PM_IRQ);
#if 0
// Restore CPU clock source
sysSetPLLConfig(&_oldsysClk);
#else
sysSetSystemClock(eSrcClk,
u32PllKHz,
u32SysKHz,
u32CpuKHz,
u32HclkKHz,
u32ApbKHz);
#endif
//Restore VRAM
memcpy((VOID *)vram_base, (VOID *)_tmp_buf, PD_RAM_SIZE);
outpw(REG_AIC_MDCR, 0xFFFFFFFF); // Disable all interrupt
outpw(REG_AIC_MECR, aic_status); // Restore AIC setting
return Successful;
}
/**************************************************************************
* The function is used to power down PLL or not if system power down
* If PLL Power down as system power down, the wake up time may take 25ms ~ 75ms
* If PLL is not powered down as system power down, the wake up time may take 3ms
*
* Note: Remember that function Sample_PowerDown() is running on SRAM.
* Because program code can't access variable on SDRAM after SDRAM entry self-refresh.
* REG_GPAFUN[31:24] is unused.
* REG_GPAFUN[26] is used to record the paramter for power down or not power down PLL.
* REG_GPAFUN[26] = 1. Power down PLL
* REG_GPAFUN[26] = 0. Keep PLL running
***************************************************************************/
void sysPowerDownPLLDuringSysPowerDown(BOOL bIsPowerDownPLL)
{//GPAFUN[31:26] is unused. Use Bit 26 to judge power down PLL or not
if(bIsPowerDownPLL==1)
outp32(REG_GPAFUN, inp32(REG_GPAFUN) | BIT26);
else
outp32(REG_GPAFUN, inp32(REG_GPAFUN) & ~BIT26);
}
static void Sample_PowerDown(void)
{
/* Enter self refresh */
__asm
{/* Dealy */
mov r2, #100
mov r1, #0
mov r0, #1
loopa: add r1, r1, r0
cmp r1, r2
bne loopa
}
outp32(REG_SDOPM, inp32(REG_SDOPM) & ~OPMODE);
outp32(REG_SDCMD, (inp32(REG_SDCMD) & ~(AUTOEXSELFREF | CKE_H)) | SELF_REF);
//outp32(REG_GPIOD_DOUT, inp32(REG_GPIOD_DOUT) & ~0x3);
/* Change the system clock souce to 12M crystal*/
outp32(REG_CLKDIV0, (inp32(REG_CLKDIV0) & (~0x18)) );
__asm
{/* Delay */
mov r2, #100
mov r1, #0
mov r0, #1
loop0: add r1, r1, r0
cmp r1, r2
bne loop0
}
//outp32(REG_GPIOD_DOUT, inp32(REG_GPIOD_DOUT) | 0x3);
if( (inp32(REG_GPAFUN)&BIT26) == BIT26){
outp32(REG_UPLLCON, inp32(REG_UPLLCON) | PD); /* Power down UPLL and APLL */
outp32(REG_APLLCON, inp32(REG_APLLCON) | PD);
}else{
outp32(REG_UPLLCON, inp32(REG_UPLLCON) & ~PD);
outp32(REG_APLLCON, inp32(REG_APLLCON) & ~PD);
}
__asm
{
mov r2, #300
mov r1, #0
mov r0, #1
loop1: add r1, r1, r0
cmp r1, r2
bne loop1
}
/* Fill and enable the pre-scale for power down wake up */
//outp32(REG_PWRCON, (inp32(REG_PWRCON) & ~0xFFFF00) | 0xFFFF02); //1.2 s
if( (inp32(REG_GPAFUN)&BIT26) == BIT26)
outp32(REG_PWRCON, (inp32(REG_PWRCON) & ~0xFFFF00) | 0xFF02); // 25ms ~ 75ms depends on system power and PLL character
else
outp32(REG_PWRCON, (inp32(REG_PWRCON) & ~0xFFFF00) | 0x0002); // 3ms wake up
__asm
{
mov r2, #10
mov r1, #0
mov r0, #1
loop2: add r1, r1, r0
cmp r1, r2
bne loop2
}
//outp32(REG_GPIOD_DOUT, (inp32(REG_GPIOD_DOUT) & ~0x03) | 0x1);
/* Enter power down. (Stop the external clock */
__asm
{/* Power down */
mov r2, 0xb0000200
ldmia r2, {r0}
bic r0, r0, #0x01
stmia r2, {r0}
}
__asm
{/* Wake up*/
mov r2, #300
mov r1, #0
mov r0, #1
loop3: add r1, r1, r0
cmp r1, r2
bne loop3
}
//outp32(REG_GPIOD_DOUT, (inp32(REG_GPIOD_DOUT) & ~0x03) | 0x2);
/* Force UPLL and APLL in normal mode */
outp32(REG_UPLLCON, inp32(REG_UPLLCON) & (~PD));
outp32(REG_APLLCON, inp32(REG_APLLCON) & (~PD));
if( (inp32(REG_GPAFUN)&BIT26) == BIT26)
{//Waitting for PLL stable if enable PLL again
__asm
{/* Delay a moment for PLL stable */
mov r2, #5000
mov r1, #0
mov r0, #1
loop4: add r1, r1, r0
cmp r1, r2
bne loop4
}
}
/* Change system clock to PLL and delay a moment. Let DDR/SDRAM lock the frequency */
outp32(REG_CLKDIV0, inp32(REG_CLKDIV0) | 0x18);
__asm
{
mov r2, #500
mov r1, #0
mov r0, #1
loop5: add r1, r1, r0
cmp r1, r2
bne loop5
}
/* Set CKE to Low and escape self-refresh mode, Force DDR/SDRAM escape self-refresh */
outp32(0xB0003004, 0x20);
__asm
{/* Delay a moment until the escape self-refresh command reached to DDR/SDRAM */
mov r2, #100
mov r1, #0
mov r0, #1
loop6: add r1, r1, r0
cmp r1, r2
bne loop6
}
}
static void Entry_PowerDown(UINT32 u32WakeUpSrc)
{
UINT32 j;
UINT32 u32IntEnable;
void (*wb_fun)(void);
UINT32 u32RamBase = PD_RAM_BASE;
UINT32 u32RamSize = PD_RAM_SIZE;
BOOL bIsEnableIRQ = FALSE;
if( sysGetIBitState()==TRUE )
{
bIsEnableIRQ = TRUE;
sysSetLocalInterrupt(DISABLE_IRQ);
}
memcpy((char*)((UINT32)_tmp_buf| 0x80000000), (char*)(u32RamBase | 0x80000000), u32RamSize);
memcpy((VOID *)((UINT32)u32RamBase | 0x80000000),
(VOID *)( ((UINT32)Sample_PowerDown -(PD_RAM_START-PD_RAM_BASE)) | 0x80000000),
PD_RAM_SIZE);
if(memcmp((char*)(u32RamBase | 0x80000000), (char*)((UINT32)((UINT32)Sample_PowerDown -(PD_RAM_START-PD_RAM_BASE)) | 0x80000000), u32RamSize)!=0)
{
sysprintf("Memcpy copy wrong\n");
}
sysFlushCache(I_CACHE);
//wb_fun = (void(*)(void)) u32RamBase;
wb_fun = (void(*)(void))PD_RAM_START;
sysprintf("Jump to SRAM (Suspend)\n");
u32IntEnable = inp32(REG_AIC_IMR);
outp32(REG_AIC_MDCR, 0xFFFFFFFE);
outp32(REG_AIC_MECR, 0x00000000);
j = 0x800;
while(j--);
outp32(0xb0000030, ((u32WakeUpSrc<<24)|(u32WakeUpSrc<<16))); //Enable and Clear interrupt
wb_fun();
outp32(0xb0000030, ((u32WakeUpSrc<<24)|(u32WakeUpSrc<<16))); //Enable and Clear interrupt
memcpy((VOID *)u32RamBase, (VOID *)_tmp_buf, PD_RAM_SIZE);
sysprintf("Exit to SRAM (Suspend)\n");
outp32(REG_AIC_MECR, u32IntEnable); /* Restore the interrupt channels */
if(bIsEnableIRQ==TRUE)
sysSetLocalInterrupt(ENABLE_IRQ);
}
INT32 sysPowerDown(WAKEUP_SOURCE_E eWakeUpSrc)
{
Entry_PowerDown(eWakeUpSrc);
return Successful;
}
<file_sep>/SYSLIB/Src/wb_uartdev.c
#include "wblib.h"
extern UARTDEV_T nvt_uart0;
extern UARTDEV_T nvt_uart1;
INT32 register_uart_device(UINT32 u32port, UARTDEV_T* pUartDev)
{
if(u32port==0)
*pUartDev = nvt_uart0;
else if(u32port==1)
*pUartDev = nvt_uart1;
else
return -1;
return Successful;
}
<file_sep>/SIC/example/Src/main_sd_performance.c
/****************************************************************************
*
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wbio.h"
#include "wbtypes.h"
//#include "WBChipDef.h"
//#include "usbd.h"
#include "wbio.h"
#include "wblib.h"
#include "wbtypes.h"
#include "w55fa93_reg.h"
#include "w55fa93_sic.h"
#include "w55fa93_GNAND.h"
#include "nvtfat.h"
//#include "nvtfat.h"
__align (32) UINT8 g_ram0[512*16*16];
__align (32) UINT8 g_ram1[512*16*16];
UINT32 u32SecCnt;
UINT32 u32backup[10];
extern PDISK_T *pDisk_SD0;
extern PDISK_T *pDisk_SD1;
extern PDISK_T *pDisk_SD2;
int volatile gTotalSectors_SD = 0, gTotalSectors_SM = 0;
NDRV_T _nandDiskDriver0 =
{
nandInit0,
nandpread0,
nandpwrite0,
nand_is_page_dirty0,
nand_is_valid_block0,
nand_ioctl,
nand_block_erase0,
nand_chip_erase0,
0
};
NDISK_T *ptMassNDisk;
void initPLL(void)
{
}
int count = 0;
int STATUS;
//void main(void)
int main(void)
{
int ii, jj;
unsigned int tick_bw, tick_aw, tick_w;
unsigned int tick_br, tick_ar, tick_r;
// InitUART();
// g_SetupTOK =0;
// g_SetupPKT=0;
// g_OutTOK = 0;
// g_SetupInTOK=0;
// g_TXD=0;
// g_RXD = 0;
// DrvSIO_printf("TEST %d\n",count);
initPLL();
sysSetTimerReferenceClock(TIMER0, 12000000); //External Crystal
sysStartTimer(TIMER0, 100, PERIODIC_MODE); /* 100 ticks/per sec ==> 1tick/10ms */
sysSetLocalInterrupt(ENABLE_IRQ);
/* initialize FMI (Flash memory interface controller) */
#ifndef OPT_FPGA_DEBUG
// sicIoctl(SIC_SET_CLOCK, 372000, 0, 0); /* clock from PLL */
sicIoctl(SIC_SET_CLOCK, 192000, 0, 0); /* clock from PLL */
#else
sicIoctl(SIC_SET_CLOCK, 27000, 0, 0); /* clock from FPGA clock in */
#endif
sicOpen();
//#define SD_0_TEST
//#define SD_1_TEST
#define SD_2_TEST
#ifdef SD_0_TEST
if (sicSdOpen0()<=0)
#endif
#ifdef SD_1_TEST
if (sicSdOpen1()<=0)
#endif
#ifdef SD_2_TEST
if (sicSdOpen2()<=0)
#endif
{
printf("Error in initializing SD card !! \n");
while(1);
}
else
{
#ifdef SD_0_TEST
printf("SD total sector is %4x !! --\n", pDisk_SD0 -> uTotalSectorN);
#endif
#ifdef SD_1_TEST
printf("SD total sector is %4x !! --\n", pDisk_SD1 -> uTotalSectorN);
#endif
#ifdef SD_2_TEST
printf("SD total sector is %4x !! --\n", pDisk_SD2 -> uTotalSectorN);
#endif
}
for(ii=0; ii<512*16*16; ii++)
g_ram0[ii] = rand();
// g_ram0[ii] = ii*(ii/512 + ii);
//#define SD_PERFORMANCE
#ifdef SD_PERFORMANCE
#define ACCESS_SIZE 10 // MB
u32SecCnt = 4;
while(1)
{
tick_bw = sysGetTicks(TIMER0);
for (jj = 1000; jj < ACCESS_SIZE*1000*2+1000; jj+=u32SecCnt) // write 100MB test
{
sicSdWrite0(jj, u32SecCnt, (UINT32)g_ram0);
}
tick_aw = sysGetTicks(TIMER0);
tick_br = sysGetTicks(TIMER0);
for (jj = 1000; jj < ACCESS_SIZE*1000*2+1000; jj+=u32SecCnt) // read 100MB test
{
sicSdRead0(jj, u32SecCnt, (UINT32)g_ram1);
}
tick_ar = sysGetTicks(TIMER0);
tick_r = tick_ar - tick_br;
tick_w = tick_aw - tick_bw;
printf("========================================\n");
printf("*** write SD test *** \n");
printf("write 10MB test per %d sectors !!!\n", u32SecCnt);
printf("write speed --- %d KB\n", (ACCESS_SIZE*1000*100/tick_w));
printf("*** read SD test *** \n");
printf("read 10MB test per %d sectors !!!\n", u32SecCnt);
printf("read speed --- %d KB\n", (ACCESS_SIZE*1000*100/tick_r));
printf("========================================\n");
u32SecCnt+= 4;
}
#else
while(1)
{
u32backup[0] = g_ram0[0];
#ifdef SD_0_TEST
for (jj = 1000; jj < pDisk_SD0->uTotalSectorN -0x100; jj+=u32SecCnt)
#endif
#ifdef SD_1_TEST
for (jj = 1000; jj < pDisk_SD1->uTotalSectorN -0x100; jj+=u32SecCnt)
#endif
#ifdef SD_2_TEST
for (jj = 1000; jj < pDisk_SD2->uTotalSectorN -0x100; jj+=u32SecCnt)
#endif
{
u32SecCnt = rand()&(0xFF);
if (u32SecCnt==0)
u32SecCnt = 1;
// u32SecCnt = 0x33;
#ifdef SD_0_TEST
sicSdWrite0(jj, u32SecCnt, (UINT32)g_ram0);
memset(g_ram1, 0x11, u32SecCnt);
sicSdRead0(jj, u32SecCnt, (UINT32)g_ram1);
#endif
#ifdef SD_1_TEST
sicSdWrite1(jj, u32SecCnt, (UINT32)g_ram0);
memset(g_ram1, 0x11, u32SecCnt);
sicSdRead1(jj, u32SecCnt, (UINT32)g_ram1);
#endif
#ifdef SD_2_TEST
sicSdWrite2(jj, u32SecCnt, (UINT32)g_ram0);
memset(g_ram1, 0x11, u32SecCnt);
sicSdRead2(jj, u32SecCnt, (UINT32)g_ram1);
#endif
if(memcmp(g_ram0, g_ram1, u32SecCnt*512) != 0)
{
printf("data compare ERROR at sector No. !! -- %4x \n", jj);
while(1);
}
printf("data compare OK at sector No. !! -- %4x \n", jj);
}
}
#endif
}
<file_sep>/VPOST/Lib/w55fa93_osd.h
#ifndef _W55FA93_OSD_H_
#define _W55FA93_OSD_H_
// Frame buffer data selection
#define DRVVPOST_OSD_RGB555 0x8 // RGB555
#define DRVVPOST_OSD_RGB565 0x9 // RGB565
#define DRVVPOST_OSD_RGBx888 0xA // xRGB888
#define DRVVPOST_OSD_RGB888x 0xB // RGBx888
#define DRVVPOST_OSD_ARGB888 0xC // ARGB888
#define DRVVPOST_OSD_CBYCRY 0x0 // Cb0 Y0 Cr0 Y1
#define DRVVPOST_OSD_YCBYCR 0x1 // Y0 Cb0 Y1 Cr0
#define DRVVPOST_OSD_CRYCBY 0x2 // Cr0 Y0 Cb0 Y1
#define DRVVPOST_OSD_YCRYCB 0x3 // Y0 Cr0 Y1 Cb0
typedef struct
{
UINT32 ucOSDSrcFormat; //User input Display source format
UINT32 nOSDScreenWidth; //Driver output,LCD width
UINT32 nOSDScreenHeight; //Driver output,LCD height
UINT32 nOSDX1StartPixel;
UINT32 nOSDY1StartPixel;
}OSDFORMATEX,*POSDFORMATEX;
typedef enum {
eOSD_SHOW = 0x01,
eOSD_HIDE,
eOSD_CLEAR,
eOSD_SET_TRANSPARENT,
eOSD_CLEAR_TRANSPARENT
} E_DRVVPOST_OSD_CTL;
VOID vpostOSDInit(POSDFORMATEX posdformatex, UINT32 *pOSDFramebuf);
VOID *vpostGetOSDFrameBuffer(void);
INT32 vpostSpitOSD(UINT32 OSDX1End, UINT32 OSDY1End, UINT32 XBarOffset, UINT32 YBarOffset);
VOID vpostGetBarXY(UINT32 *OSDX1End, UINT32 *OSDY1End, UINT32 *XBarOffset, UINT32 *YBarOffset);
INT32 vpostOSDControl(INT32 cmd, INT32 arg);
VOID vpostChangeOSDFrameBuffer(UINT32 *pOSDFramebuf);
#endif<file_sep>/VPOST/Example_OSD/Src/main_vpost.c
/****************************************************************************
*
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wbio.h"
#include "wbtypes.h"
//#include "WBChipDef.h"
//#include "usbd.h"
#include "w55fa93_vpost.h"
#include "w55fa93_reg.h"
#include "w55fa93_osd.h"
__align (32) UINT8 g_ram0[512*16*16];
__align (32) UINT8 g_ram1[512*16*16];
UINT32 u32SecCnt;
UINT32 u32backup[10];
__align(32) UINT8 Vpost_Frame[]=
{
// #include "roof_800x600_rgb565.dat" // for SVGA size test
// #include "sea_800x480_rgb565.dat"
// #include "roof_800x480_rgb565.dat"
// #include "roof_720x480_rgb565.dat" // for D1 size test
// #include "lake_720x480_rgb565.dat" // for D1 size test
// #include "mountain_640x480_rgb565.dat" // for VGA size test
// #include "river_480x272_rgb565.dat"
// #include "roof_320x240_rgb565.dat"
#ifdef N32903
#include "roof_320x240_yuv422.dat"
#endif
#ifdef N32901
#include "roof_320x240_yuv422.dat"
#endif
// #include "roof_320x240_rgbx888.dat"
#ifdef FA93SDN
// #include "nuvoton_320x240_rgb565.dat"
#include "river_480x272_rgb565.dat"
#endif
};
__align(32) UINT8 OSD_FrameRGB565[] =
{
#ifdef FA93SDN
#include "roof_320x240_rgb565.dat"
#endif
#ifdef N32903
#include "roof_320x240_yuv422.dat"
#endif
#ifdef N32901
#include "roof_320x240_yuv422.dat"
#endif
};
LCDFORMATEX lcdFormat;
OSDFORMATEX osdFormat;
int volatile gTotalSectors_SD = 0, gTotalSectors_SM = 0;
void initPLL(void)
{
}
int count = 0;
int STATUS;
int main(void)
{
UINT32 OSDX1End, OSDY1End, XBarOffset, YBarOffset,result;
// InitUART();
// g_SetupTOK =0;
// g_SetupPKT=0;
// g_OutTOK = 0;
// g_SetupInTOK=0;
// g_TXD=0;
// g_RXD = 0;
// DrvSIO_printf("TEST %d\n",count);
initPLL();
// lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_RGB565;
// lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_YCBYCR;
// lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_RGBx888;
// lcdFormat.nScreenWidth = 800;
// lcdFormat.nScreenHeight = 600;
// lcdFormat.nScreenWidth = 640;
// lcdFormat.nScreenHeight = 480;
// lcdFormat.nScreenWidth = 720;
// lcdFormat.nScreenHeight = 480;
#ifdef FA93SDN
lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_RGB565; // for FA93SDN
lcdFormat.nScreenWidth = 480;
lcdFormat.nScreenHeight = 272;
#endif
#ifdef N32903
lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_YCBYCR;
lcdFormat.nScreenWidth = 320;
lcdFormat.nScreenHeight = 240;
#endif
#ifdef N32901
lcdFormat.ucVASrcFormat = DRVVPOST_FRAME_YCBYCR;
lcdFormat.nScreenWidth = 320;
lcdFormat.nScreenHeight = 240;
#endif
vpostLCMInit(&lcdFormat, (UINT32*)Vpost_Frame);
#ifdef FA93SDN
// OSD Demo
osdFormat.ucOSDSrcFormat = DRVVPOST_OSD_RGB565;
#endif
#ifdef N32903
osdFormat.ucOSDSrcFormat = DRVVPOST_FRAME_YCBYCR;
#endif
#ifdef N32901
osdFormat.ucOSDSrcFormat = DRVVPOST_FRAME_YCBYCR;
#endif
osdFormat.nOSDScreenWidth = 320;
osdFormat.nOSDScreenHeight = 240;
osdFormat.nOSDX1StartPixel = 0;
osdFormat.nOSDY1StartPixel = 0;
vpostOSDInit(&osdFormat, (UINT32*)OSD_FrameRGB565 );
vpostOSDControl(eOSD_SHOW, 0);
do{
vpostOSDControl(eOSD_SET_TRANSPARENT, 0xF800); // Red Transparent
sysDelay(100);
vpostOSDControl(eOSD_SET_TRANSPARENT, 0x07E0); // Green Transparent
sysDelay(100);
vpostOSDControl(eOSD_SET_TRANSPARENT, 0x001F); // Blue Transparent
sysDelay(100);
vpostOSDControl(eOSD_CLEAR_TRANSPARENT, 0x0); // Disable Transparent
vpostGetBarXY(&OSDX1End, &OSDY1End,&XBarOffset,&YBarOffset);
sysDelay(100);
result = vpostSpitOSD(OSDX1End+10, OSDY1End+10, XBarOffset+10, YBarOffset+10);
if (result)
{
vpostOSDControl(eOSD_HIDE,0);
vpostSpitOSD(1, 1, 1, 1); // Merge 2 OSD Bar again
vpostOSDControl(eOSD_SHOW, 0);
}
} while(1);
while(1);
}
<file_sep>/NVT LOADER/production/NVT_Production.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_vpost.h"
#include "AviLib.h"
#include "nvtfat.h"
#include "nvtloader.h"
#include "w55fa93_kpi.h"
#include "w55fa93_gpio.h"
#include "InitFont.h"
__align(32) static S_DEMO_FONT s_sDemo_Font;
__align(32) UINT16 FrameBuffer[480*272];
void NVT_MassProduction(void)
{
initVPost(FrameBuffer);
int result;
while(1)
{
result = kpi_read(KPI_NONBLOCK);
sysprintf("0x%x\n", result);
}
} <file_sep>/SIC_SECC/example/Src/main_sd.c
/****************************************************************************
*
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wbio.h"
#include "wbtypes.h"
//#include "WBChipDef.h"
//#include "usbd.h"
#include "w55fa93_reg.h"
#include "w55fa93_sic.h"
#include "w55fa93_GNAND.h"
#include "nvtfat.h"
//#include "nvtfat.h"
__align (32) UINT8 g_ram0[512*16*16];
__align (32) UINT8 g_ram1[512*16*16];
UINT32 u32SecCnt;
UINT32 u32backup[10];
extern PDISK_T *pDisk_SD0;
extern PDISK_T *pDisk_SD1;
extern PDISK_T *pDisk_SD2;
int volatile gTotalSectors_SD = 0, gTotalSectors_SM = 0;
NDRV_T _nandDiskDriver0 =
{
nandInit0,
nandpread0,
nandpwrite0,
nand_is_page_dirty0,
nand_is_valid_block0,
nand_ioctl,
nand_block_erase0,
nand_chip_erase0,
0
};
NDISK_T *ptMassNDisk;
void initPLL(void)
{
}
int count = 0;
int STATUS;
//void main(void)
int main(void)
{
int ii, jj;
// InitUART();
// g_SetupTOK =0;
// g_SetupPKT=0;
// g_OutTOK = 0;
// g_SetupInTOK=0;
// g_TXD=0;
// g_RXD = 0;
// DrvSIO_printf("TEST %d\n",count);
initPLL();
/* initialize FMI (Flash memory interface controller) */
#ifndef OPT_FPGA_DEBUG
sicIoctl(SIC_SET_CLOCK, 372000, 0, 0); /* clock from PLL */
#else
sicIoctl(SIC_SET_CLOCK, 27000, 0, 0); /* clock from FPGA clock in */
#endif
sicOpen();
if (sicSdOpen0()<=0)
{
sysprintf("Error in initializing SD card !! \n");
while(1);
}
else
{
sysprintf("SD total sector is %4x !! --\n", pDisk_SD0 -> uTotalSectorN);
}
#if 0
sicSdRead0(0x979, 1, (UINT32)g_ram1);
while(1);
#endif
for(ii=0; ii<512*16*16; ii++)
g_ram0[ii] = rand();
// g_ram0[ii] = ii*(ii/512 + ii);
while(1)
{
u32backup[0] = g_ram0[0];
for (jj = 1000; jj < pDisk_SD0->uTotalSectorN -0x100; jj+=u32SecCnt)
{
u32SecCnt = rand()&(0xFF);
if (u32SecCnt==0)
u32SecCnt = 1;
// u32SecCnt = 0x33;
sicSdWrite0(jj, u32SecCnt, (UINT32)g_ram0);
memset(g_ram1, 0x11, u32SecCnt);
sicSdRead0(jj, u32SecCnt, (UINT32)g_ram1);
if(memcmp(g_ram0, g_ram1, u32SecCnt*512) != 0)
{
sysprintf("data compare ERROR at sector No. !! -- %4x \n", jj);
while(1);
}
sysprintf("data compare OK at sector No. !! -- %4x \n", jj);
}
}
}
<file_sep>/SIC_SECC/example/Src/main_nand.c
/****************************************************************************
*
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wbio.h"
#include "wblib.h"
#include "wbtypes.h"
#include "w55fa93_reg.h"
#include "w55fa93_sic.h"
#include "w55fa93_GNAND.h"
#define DBG_PRINTF printf
//#define DBG_PRINTF sysprintf
//#define DBG_PRINTF(...)
__align (32) UINT8 g_ram0[512*16*16];
__align (32) UINT8 g_ram1[512*16*16];
UINT32 u32SecCnt;
UINT32 u32backup[10];
int volatile gTotalSectors_SD = 0, gTotalSectors_SM = 0;
NDRV_T _nandDiskDriver0 =
{
nandInit0,
nandpread0,
nandpwrite0,
nand_is_page_dirty0,
nand_is_valid_block0,
nand_ioctl,
nand_block_erase0,
nand_chip_erase0,
0
};
NDRV_T _nandDiskDriver1 =
{
nandInit1,
nandpread1,
nandpwrite1,
nand_is_page_dirty1,
nand_is_valid_block1,
nand_ioctl,
nand_block_erase1,
nand_chip_erase1,
0
};
NDISK_T *ptMassNDisk;
NDISK_T MassNDisk;
void initPLL(void)
{
}
int count = 0;
int STATUS;
void Test()
{
DBG_PRINTF("test -> %d\n", ++count);
}
void Test1()
{
DBG_PRINTF("Hello World!\n");
}
void Test2()
{
DBG_PRINTF("timer 1 test\n");
}
void DemoAPI_Timer0(void)
{
// unsigned int volatile i;
volatile unsigned int btime, etime, tmp, tsec;
volatile UINT32 u32TimeOut = 0;
UINT32 u32ExtFreq;
u32ExtFreq = sysGetExternalClock()*1000;
DBG_PRINTF("Timer 0 Test...\n");
sysSetTimerReferenceClock(TIMER0, u32ExtFreq); //External Crystal
sysStartTimer(TIMER0, 100, PERIODIC_MODE); /* 100 ticks/per sec ==> 1tick/10ms */
tmp = sysSetTimerEvent(TIMER0, 100, (PVOID)Test); /* 100 ticks = 1s call back */
DBG_PRINTF("No. of Event [%d]\n", tmp);
tmp = sysSetTimerEvent(TIMER0, 300, (PVOID)Test1); /* 300 ticks/per sec */
DBG_PRINTF("No. of Event [%d]\n", tmp);
sysSetLocalInterrupt(ENABLE_IRQ);
btime = sysGetTicks(TIMER0);
tsec = 0;
tmp = btime;
while (1)
{
etime = sysGetTicks(TIMER0);
if ((etime - btime) >= 100)
{
DBG_PRINTF("tick = %d\n", ++tsec);
btime = etime;
u32TimeOut = u32TimeOut +1;
if(u32TimeOut==10) /* 10s Time out */
break;
}
}
DBG_PRINTF("Finish timer 0 testing...\n");
sysStopTimer(TIMER0);
}
int main(void)
{
int ii, jj;
int nSectorPerPage;
// DrvSIO_printf("TEST %d\n",count);
initPLL();
sysSetTimerReferenceClock(TIMER0, 12000000); //External Crystal
sysStartTimer(TIMER0, 100, PERIODIC_MODE); /* 100 ticks/per sec ==> 1tick/10ms */
sysSetLocalInterrupt(ENABLE_IRQ);
/* initialize FMI (Flash memory interface controller) */
sicIoctl(SIC_SET_CLOCK, 192000, 0, 0); /* clock from PLL */
sicOpen();
// NAND erase
#if 0
nandInit1(&MassNDisk);
nand_chip_erase1();
for (ii=0; ii< pSM1->uBlockPerFlash; ii++)
{
if (fmiCheckInvalidBlock(pSM1, ii))
printf("invald block No. %4d \n", ii);
}
while(1);
#endif
ptMassNDisk = (NDISK_T*)&MassNDisk;
if ( GNAND_InitNAND(&_nandDiskDriver0, (NDISK_T *)ptMassNDisk, TRUE))
// if ( GNAND_InitNAND(&_nandDiskDriver1, (NDISK_T *)ptMassNDisk, TRUE))
{
printf("GNAND init fail !!\n");
return 1;
}
nSectorPerPage = ptMassNDisk->nPageSize / 512;
//gTotalSectors_SM = ptMassNDisk->nZone * (ptMassNDisk->nLBPerZone-1) * ptMassNDisk->nPagePerBlock * nSectorPerPage - ptMassNDisk->nStartBlock;
gTotalSectors_SM = ptMassNDisk->nZone * (ptMassNDisk->nLBPerZone-1) * ptMassNDisk->nPagePerBlock * nSectorPerPage;
if (gTotalSectors_SM < 0)
{
GNAND_UnMountNandDisk(ptMassNDisk);
fmiSMClose(0);
while(1);
}
for(ii=0; ii<512*16*16; ii++)
g_ram0[ii] = rand();
while(1)
{
u32backup[0] = g_ram0[0];
for (jj = 3000; jj < 50000; jj+=u32SecCnt)
{
u32SecCnt = rand()&(0xFF);
if (u32SecCnt==0)
u32SecCnt = 1;
GNAND_write(ptMassNDisk, jj, u32SecCnt, g_ram0);
memset(g_ram1, 0x11, u32SecCnt);
GNAND_read(ptMassNDisk, jj, u32SecCnt, g_ram1);
if(memcmp(g_ram0, g_ram1, u32SecCnt*512) != 0)
{
printf("data compare ERROR at sector No. !! -- %4x \n", jj);
while(1);
}
printf("data compare OK at sector No. !! -- %4x \n", jj);
}
}
}
<file_sep>/SDWRITER/INI/TurboWriter.ini
[ADDRESS]
ADDRESS = 00900000
[CLOCK_SKEW]
DQSODS = 00001010
CKDQSDS = 00AAAA00
[USER_DEFINE]
<file_sep>/LOADER/NandLoader/user_define/user_define_func.h
/*-----------------------------------------------------------------------------------*/
/* Nuvoton Technology Corporation confidential */
/* */
/* Copyright (c) 2013 by Nuvoton Technology Corporation */
/* All rights reserved */
/* */
/*-----------------------------------------------------------------------------------*/
#ifndef _W55FA93_NANDLOADER_USER_DEFINE_FUNC_H
#define _W55FA93_NANDLOADER_USER_DEFINE_FUNC_H
/*-----------------------------------------------------------------------------------*/
/* This include file should keep empty if user define nothing for user_define_func() */
/*-----------------------------------------------------------------------------------*/
#ifdef __USER_DEFINE_FUNC
#include <string.h>
#include "wblib.h"
#include "turbowriter.h"
#include "w55fa93_vpost.h"
// for Nuvoton FA93 Demo Board panel 320x240
#define PANEL_WIDTH 320
#define PANEL_HEIGHT 240
// got Logo image from memory address FB_ADDR
#define FB_ADDR 0x00500000
#endif // end of #ifdef __USER_DEFINE_FUNC
#endif // end of _W55FA93_NANDLOADER_USER_DEFINE_FUNC_H
<file_sep>/SYSLIB/Src/wb_mem.c
/***************************************************************************
* *
* Copyright (c) 2008 Nuvoton Technolog. All rights reserved. *
* *
***************************************************************************/
/****************************************************************************
* FILENAME
* wb_timer.c
*
* VERSION
* 1.0
*
* DESCRIPTION
* The timer related function of Nuvoton ARM9 MCU
*
* HISTORY
* 2008-06-25 Ver 1.0 draft by <NAME>
*
* REMARK
* None
**************************************************************************/
#include "wblib.h"
#include "stdlib.h"
/* nv memory function, user could modify it */
void *nv_malloc(UINT32 u32byteno)
{
return (void *)malloc(u32byteno);
}
void nv_free(void *buffer)
{
free(buffer);
}
<file_sep>/MP3/Lib/MediaFileLib.h
#ifndef _MEDIA_FILE_LIB_H_
#define _MEDIA_FILE_LIB_H_
/*-------------------------------------------------------------------------*
* MFL error code table *
*-------------------------------------------------------------------------*/
/* general errors */
#define MFL_ERR_NO_MEMORY 0xFFFF8000 /* no memory */
#define MFL_ERR_HARDWARE 0xFFFF8002 /* hardware general error */
#define MFL_ERR_NO_CALLBACK 0xFFFF8004 /* must provide callback function */
#define MFL_ERR_AU_UNSUPPORT 0xFFFF8006 /* not supported audio type */
#define MFL_ERR_VID_UNSUPPORT 0xFFFF8008 /* not supported video type */
#define MFL_ERR_TRACK_UNSUPPORT 0xFFFF800A /* not supported track type */
#define MFL_ERR_OP_UNSUPPORT 0xFFFF800C /* unsupported operation */
#define MFL_ERR_PREV_UNSUPPORT 0xFFFF800E /* preview of this media type was not supported or not enabled */
#define MFL_ERR_FUN_USAGE 0xFFFF8010 /* incorrect function call parameter */
#define MFL_ERR_RESOURCE_MEM 0xFFFF8012 /* memory is not enough to play/record a media file */
/* stream I/O errors */
#define MFL_ERR_FILE_OPEN 0xFFFF8020 /* cannot open file */
#define MFL_ERR_FILE_TEMP 0xFFFF8022 /* temporary file access failure */
#define MFL_ERR_STREAM_IO 0xFFFF8024 /* stream access error */
#define MFL_ERR_STREAM_INIT 0xFFFF8026 /* stream was not opened */
#define MFL_ERR_STREAM_EOF 0xFFFF8028 /* encounter EOF of file */
#define MFL_ERR_STREAM_SEEK 0xFFFF802A /* stream seek error */
#define MFL_ERR_STREAM_TYPE 0xFFFF802C /* incorrect stream type */
#define MFL_ERR_STREAM_METHOD 0xFFFF8030 /* missing stream method */
#define MFL_ERR_STREAM_MEMOUT 0xFFFF8032 /* recorded data has been over the application provided memory buffer */
#define MFL_INVALID_BITSTREAM 0xFFFF8034 /* invalid audio/video bitstream format */
/* MP4/3GP file errors */
#define MFL_ERR_MP4_FILE 0xFFFF8050 /* wrong MP4 file format or not supported */
#define MFL_ERR_3GP_FILE 0xFFFF8052 /* wrong 3GP file format or not supported */
#define MFL_ERR_NO_TKHD 0xFFFF8054 /* preceding 'tkhd' not present */
#define MFL_ERR_MP4_STSC 0xFFFF8056 /* MP4 'stsc' atom contain error */
#define MFL_ERR_MP4_STTS 0xFFFF8058 /* MP4 'stts' atom contain error */
#define MFL_ERR_ATOM_UNKNOWN 0xFFFF805A /* unknown atom type */
#define MFL_ERR_DATA_REF 0xFFFF805C /* media data is not in the same file, currently not supported */
#define MFL_ERR_SAMPLE_OVERSIZE 0xFFFF8060 /* MP4/3GP video or audio sample size too large */
#define MFL_ERR_PLAY_DONE 0xFFFF8062 /* MFL internal use, not an error */
#define MFL_ERR_SEEK_FAIL 0xFFFF8070 /* MFL can not seek to specified time position */
#define MFL_ERR_CLIP_EXCEED 0xFFFF8072 /* media clipping position exceed range */
#define MFL_ERR_CLIP_LOCATE 0xFFFF8074 /* media clipping can not locate position */
#define MFL_ERR_CLIP_CREATE 0xFFFF8076 /* media clipping can not create output file */
#define MFL_ERR_H264_COMBO 0xFFFF8078 /* MFL internal use, not an error */
/* AVI errors */
#define MFL_ERR_AVI_FILE 0xFFFF8080 /* Invalid AVI file format */
#define MFL_ERR_AVI_VID_CODEC 0xFFFF8081 /* AVI unsupported video codec type */
#define MFL_ERR_AVI_AU_CODEC 0xFFFF8082 /* AVI unsupported audio codec type */
#define MFL_ERR_AVI_CANNOT_SEEK 0xFFFF8083 /* The AVI file is not fast-seekable */
#define MFL_ERR_AVI_SIZE 0xFFFF8080 /* Exceed estimated size */
/* AMR errors */
#define MFL_ERR_AMR_FORMAT 0xFFFF8090 /* incorrect AMR frame format */
#define MFL_ERR_AMR_DECODE 0xFFFF8092 /* AMR decode error */
#define MFL_ERR_AMR_ENCODE 0xFFFF8094 /* AMR encode error */
#define MFL_AMR_DECODER_INIT 0xFFFF8096 /* failed to init AMR decoder */
#define MFL_AMR_ENCODER_INIT 0xFFFF8098 /* failed to init AMR decoder */
#define MFL_ERR_AMR_UNSUPPORT 0xFFFF809A /* unsupported AMR frame type */
/* AAC errors */
#define MFL_ERR_AAC_FORMAT 0xFFFF80B0 /* incorrect AAC frame format */
#define MFL_ERR_AAC_DECODE 0xFFFF80B2 /* AAC decode error */
#define MFL_ERR_AAC_ENCODE 0xFFFF80B4 /* AAC encode error */
#define MFL_ERR_AAC_UNSUPPORT 0xFFFF80B6 /* unsupported AAC frame type */
#define MFL_ERR_AAC_CHANNELS 0xFFFF80B8 /* more than 2 channels is not supported */
/* MP3 errors */
#define MFL_ERR_MP3_FORMAT 0xFFFF80D0 /* incorrect MP3 frame format */
#define MFL_ERR_MP3_DECODE 0xFFFF80D2 /* MP3 decode error */
/* WAV errors */
#define MFL_ERR_WAV_FILE 0xFFFF80F0 /* wave file format error */
#define MFL_ERR_WAV_UNSUPPORT 0xFFFF80F2 /* unsupported wave format */
#define MFL_ERR_ADPCM_SUPPORT 0xFFFF80F4 /* can only handle 4-bit IMA ADPCM in wav files */
/* hardware engine errors */
#define MFL_ERR_HW_NOT_READY 0xFFFF8100 /* the picture is the same as the last one */
#define MFL_ERR_VID_NOT_DTIME 0xFFFF8102 /* not specified decode time, internal use */
#define MFL_ERR_SHORT_BUFF 0xFFFF8104 /* buffer size is not enough */
#define MFL_ERR_VID_DEC_ERR 0xFFFF8106 /* video decode error */
#define MFL_ERR_VID_DEC_BUSY 0xFFFF8108 /* video decoder is busy */
#define MFL_ERR_VID_ENC_ERR 0xFFFF810A /* video encode error */
#define MFL_VID_IS_INTRA 0xFFFF810B /* not an error code */
#define MFL_ERR_AU_PBUF_FULL 0xFFFF810C /* audio play buffer full, internal use */
#define MFL_ERR_AU_RDATA_LOW 0xFFFF8110 /* audio record data not enough, internal use */
#define MFL_ERR_AU_UNDERFLOW 0xFFFF8112 /* audio record data underflow, internal use */
#define MFL_ERR_AU_OVERFLOW 0xFFFF8114 /* audio play data overflow, internal use */
/* MPEG4 codec error */
#define MFL_ERR_H263_SIZE 0xFFFF8140 /* wrong H.263 header */
#define MFL_ERR_VOL_NOT_FOUND 0xFFFF8150 /* MPEG4 video VOL not found */
/* Audio post processing error */
#define MFL_ERR_3D_INIT 0xFFFF8160 /* 3D initialize error */
/* other errors */
#define MFL_ERR_INFO_NA 0xFFFF81E0 /* media information not enough */
#define MFL_ERR_UNKNOWN_MEDIA 0xFFFF81E2 /* unknow media type */
#define MFL_ERR_MOVIE_PLAYING 0xFFFF81E4 /* movie is still in play */
#define MFL_ERR_ULTRAM_TMPF 0xFFFF81E6 /* ultra merge file stream must use temp file */
#define MAX_VOLUME_VALUE 63
/*-------------------------------------------------------------------------*
* Media type enumeration *
*-------------------------------------------------------------------------*/
typedef enum media_type_e
{
MFL_MEDIA_MP4,
MFL_MEDIA_3GP,
MFL_MEDIA_M4V,
MFL_MEDIA_AAC,
MFL_MEDIA_AMR,
MFL_MEDIA_MP3,
MFL_MEDIA_ADPCM,
MFL_MEDIA_WAV,
MFL_MEDIA_MIDI,
MFL_MEDIA_AVI,
MFL_MEDIA_ASF,
MFL_MEDIA_WMV,
MFL_MEDIA_WMA,
MFL_MEDIA_SMAF,
MFL_MEDIA_M4A,
MFL_MEDIA_WBKTV,
MFL_MEDIA_UNKNOWN = 1000
} MEDIA_TYPE_E;
/*-------------------------------------------------------------------------*
* S/W audio codec enumeration *
*-------------------------------------------------------------------------*/
typedef enum au_codec_e
{
MFL_CODEC_PCM,
MFL_CODEC_AMRNB,
MFL_CODEC_AMRWB,
MFL_CODEC_AAC,
MFL_CODEC_AACP,
MFL_CODEC_EAACP,
MFL_CODEC_ADPCM,
MFL_CODEC_MP3,
MFL_CODEC_UNKNOWN = 1000
} AU_CODEC_E;
/*-------------------------------------------------------------------------*
* H/W video codec enumeration *
*-------------------------------------------------------------------------*/
typedef enum vid_codec_e
{
MFL_CODEC_H263,
MFL_CODEC_MPEG4,
MFL_CODEC_H264,
MFL_CODEC_JPEG
} VID_CODEC_E;
/*-------------------------------------------------------------------------*
* MFL data stream type enumeration *
*-------------------------------------------------------------------------*/
typedef enum stream_type_e
{
MFL_STREAM_MEMORY,
MFL_STREAM_FILE,
MFL_STREAM_USER
} STRM_TYPE_E;
/*-------------------------------------------------------------------------*
* Physical audio playback device type enumeration *
*-------------------------------------------------------------------------*/
typedef enum au_play_dev_e
{
MFL_PLAY_AC97 = 0,
MFL_PLAY_I2S = 1,
MFL_PLAY_UDA1345TS = 2,
MFL_PLAY_DAC = 4,
MFL_PLAY_MA3 = 5,
MFL_PLAY_MA5 = 6,
MFL_PLAY_W5691 = 7,
MFL_PLAY_WM8753 = 8,
MFL_PLAY_WM8751 = 9,
MFL_PLAY_WM8978 = 10,
MFL_PLAY_MA5I = 11,
MFL_PLAY_MA5SI = 12,
MFL_PLAY_W56964 = 13,
MFL_PLAY_AK4569 = 14,
MFL_PLAY_TIAIC31 = 15,
MFL_PLAY_WM8731 = 16
} AU_PLAY_DEV_E;
/*-------------------------------------------------------------------------*
* Physical audio record device type enumeration *
*-------------------------------------------------------------------------*/
typedef enum au_rec_dev_e
{
MFL_REC_AC97 = 0,
MFL_REC_I2S = 1,
MFL_REC_UDA1345TS = 2,
MFL_REC_ADC = 3,
MFL_REC_W5691 = 7,
MFL_REC_WM8753 = 8,
MFL_REC_WM8751 = 9,
MFL_REC_WM8978 = 10,
MFL_REC_AK4569 = 14,
MFL_REC_TIAIC31 = 15,
MFL_REC_WM8731 = 16
} AU_REC_DEV_E;
/*-------------------------------------------------------------------------*
* Audio sampling rate enumeration *
*-------------------------------------------------------------------------*/
typedef enum au_srate_e
{
AU_SRATE_8000 = 8000,
AU_SRATE_11025 = 11025,
AU_SRATE_12000 = 12000,
AU_SRATE_16000 = 16000,
AU_SRATE_22050 = 22050,
AU_SRATE_24000 = 24000,
AU_SRATE_32000 = 32000,
AU_SRATE_44100 = 44100,
AU_SRATE_48000 = 48000
} AU_SRATE_E;
/*-------------------------------------------------------------------------*
* MFL playback control enumeration *
*-------------------------------------------------------------------------*/
typedef enum play_ctrl_e
{
PLAY_CTRL_FF = 0,
PLAY_CTRL_FB,
PLAY_CTRL_FS,
PLAY_CTRL_PAUSE,
PLAY_CTRL_RESUME,
PLAY_CTRL_STOP,
PLAY_CTRL_SPEED
} PLAY_CTRL_E;
enum
{
PLAY_SPEED_QUARTER = 0x0104,
PLAY_SPEED_HALF = 0x0102,
PLAY_SPEED_NORMAL = 0x0101,
PLAY_SPEED_DOUBLE = 0x0201,
PLAY_SPEED_QUADRUPLE = 0x0401
};
/*-------------------------------------------------------------------------*
* MFL record control enumeration *
*-------------------------------------------------------------------------*/
typedef enum rec_ctrl_e
{
REC_CTRL_PAUSE = 0,
REC_CTRL_RESUME,
REC_CTRL_STOP
} REC_CTRL_E;
/*-------------------------------------------------------------------------*
* MFL equalizer settings enumeration *
*-------------------------------------------------------------------------*/
typedef enum eq_eft_e
{
EQ_DEFAULT = 0,
EQ_CLASSICAL,
EQ_CLUB,
EQ_DANCE,
EQ_FULL_BASS,
EQ_LIVE,
EQ_POP,
EQ_ROCK,
EQ_SOFT,
EQ_USER_DEFINED
} EQ_EFT_E;
/*-------------------------------------------------------------------------*
* QSound 3D surround settings *
*-------------------------------------------------------------------------*/
typedef enum
{
MFL_Q3D_ROOM = 1,
MFL_Q3D_BATHROOM,
MFL_Q3D_CONCERTHALL,
MFL_Q3D_CAVE,
MFL_Q3D_ARENA,
MFL_Q3D_FOREST,
MFL_Q3D_CITY,
MFL_Q3D_MOUNTAINS,
MFL_Q3D_UNDERWATER,
MFL_Q3D_AUDITORIUM,
MFL_Q3D_ALLEY,
MFL_Q3D_HALLWAY,
MFL_Q3D_HANGAR,
MFL_Q3D_HANGER,
MFL_Q3D_LIVINGROOM,
MFL_Q3D_SMALLROOM,
MFL_Q3D_MEDIUMROOM,
MFL_Q3D_LARGEROOM,
MFL_Q3D_MEDIUMHALL,
MFL_Q3D_LARGEHALL,
MFL_Q3D_PLATE,
MFL_Q3D_GENERIC,
MFL_Q3D_PADDEDCELL,
MFL_Q3D_STONEROOM,
MFL_Q3D_CARPETEDHALLWAY,
MFL_Q3D_STONECORRIDOR,
MFL_Q3D_QUARRY,
MFL_Q3D_PLAIN,
MFL_Q3D_PARKINGLOT,
MFL_Q3D_SEWERPIPE
} Q3D_REVERB_T;
typedef enum
{
MFL_Q3D_SPEAKERS,
MFL_Q3D_HEADPHONES
} Q3D_OUTTYPE_T;
typedef enum
{
MFL_Q3D_GEOMETRY_SPEAKER_DESKTOP,
MFL_Q3D_GEOMETRY_SPEAKER_FRONT,
MFL_Q3D_GEOMETRY_SPEAKER_SIDE
} Q3D_GEOMETRY_T;
typedef struct q3d_config_t
{
Q3D_REVERB_T eQ3D_Reverb;
Q3D_OUTTYPE_T eQ3D_OutType;
Q3D_GEOMETRY_T eQ3D_Geometry;
} Q3D_CONFIG_T;
/*-------------------------------------------------------------------------*
* MFL data stream function set *
*-------------------------------------------------------------------------*/
struct stream_t;
typedef struct strm_fun
{
INT (*open)(struct stream_t *ptStream, CHAR *suFileName, CHAR *szAsciiName,
UINT8 *pbMemBase, UINT32 ulMemLen, INT access);
INT (*is_opened)(struct stream_t *ptStream);
INT (*seek)(struct stream_t *ptStream, INT nOffset, INT nSeek);
INT (*get_pos)(struct stream_t *ptStream);
INT (*close)(struct stream_t *ptStream);
INT (*read)(struct stream_t *ptStream, UINT8 *pucBuff, INT nCount, BOOL bIsSkip);
INT (*write)(struct stream_t *ptStream, UINT8 *pucBuff, INT nCount);
INT (*peek)(struct stream_t *ptStream, UINT8 *pucBuff, INT nCount);
INT (*get_bsize)(struct stream_t *ptStream);
} STRM_FUN_T;
typedef struct stream_t
{
STRM_TYPE_E eStrmType;
UINT8 *pucMemBase; /* start address of memory block used by this stream */
UINT8 *pucMemEnd; /* end address of memory block used by this stream */
UINT32 uMemValidSize; /* valid size in the memory block used by this stream */
UINT8 *pucMemPtr; /* current read/write address of stream in memory */
BOOL bIsRealocable; /* the in-memory can be realloc */
UINT8 ucByte; /* the last read bytes */
UINT8 ucBitRemainder; /* bits not read in the last byte */
INT hFile; /* file handle */
STRM_FUN_T *ptStrmFun; /* stream method */
} STREAM_T;
/*-------------------------------------------------------------------------*
* MFL ID3 tag information (stored in movie information) *
*-------------------------------------------------------------------------*/
typedef struct id3_ent_t
{
INT nLength; /* tag length */
CHAR sTag[128]; /* tag content */
BOOL bIsUnicode; /* 1: is unicode, 0: is ASCII */
} ID3_ENT_T;
typedef struct id3_pic_t
{
BOOL bHasPic; /* 1: has picture, 0: has no picture in ID3 tag */
CHAR cType;
ID3_ENT_T tTitle;
INT nPicOffset; /* picture offset in file */
INT nPicSize; /* picture size */
struct id3_pic_t *ptNextPic; /* always NULL in current version */
} ID3_PIC_T;
typedef struct id3_tag_t
{
ID3_ENT_T tTitle;
ID3_ENT_T tArtist;
ID3_ENT_T tAlbum;
ID3_ENT_T tComment;
CHAR szYear[16];
CHAR szTrack[16];
CHAR szGenre[16];
CHAR cVersion; /* reversion of ID3v2. ID3v2.2.0 = 0x20, ID3v2.3.0 = 0x30 */
/* reversion of ID3v1. ID3v1.0 = 0x00, ID3v1.1 = 0x10 */
ID3_PIC_T tPicture;
} ID3_TAG_T;
/*-------------------------------------------------------------------------*
* MFL movie information (run-time and preview) *
*-------------------------------------------------------------------------*/
typedef struct mv_info
{
UINT32 uInputFileSize; /* the file size of input media file */
UINT32 uMovieLength; /* in 1/100 seconds */
UINT32 uPlayCurTimePos; /* for playback, the play time position, in 1/100 seconds */
UINT32 uCreationTime;
UINT32 uModificationTime;
/* audio */
AU_CODEC_E eAuCodecType;
UINT32 uAudioLength; /* in 1/100 seconds */
INT nAuRecChnNum; /* 1: record single channel, Otherwise: record left and right channels */
AU_SRATE_E eAuRecSRate; /* audio record sampling rate */
UINT32 uAuRecBitRate; /* audio record bit rate */
UINT32 uAuRecMediaLen; /* Currently recorded audio data length */
BOOL bIsVBR; /* input audio file is VBR or not */
INT nAuPlayChnNum; /* 1:Mono, 2:Stero */
AU_SRATE_E eAuPlaySRate; /* audio playback sampling rate */
UINT32 uAuPlayBitRate; /* audio playback bit rate */
UINT32 uAuTotalFrames; /* For playback, it's the total number of audio frames. For recording, it's the currently recorded frame number. */
UINT32 uAuFramesPlayed; /* Indicate how many audio frames have been played */
UINT32 uAuPlayMediaLen; /* Indicate how many audio data have been played (bytes) */
UINT32 uAuMP4BuffSizeDB; /* MP4 audio decode buffer size (recorded in MP4 file) */
UINT32 uAuMP4AvgBitRate; /* MP4 audio average bit rate (recorded in MP4 file) */
UINT32 uAuMP4MaxBitRate; /* MP4 audio maximum bit rate (recorded in MP4 file) */
/* video */
VID_CODEC_E eVidCodecType;
UINT32 uVideoLength; /* in 1/100 seconds */
UINT32 uVideoFrameRate; /* only available in MP4/3GP/ASF/AVI files */
BOOL bIsShortHeader; /* TRUE:H.263, FALSE: MPEG4 */
UINT16 usImageWidth;
UINT16 usImageHeight;
UINT32 uVidTotalFrames; /* For playback, it's the total number of video frames. For recording, it's the currently recorded frame number. */
UINT32 uVidFramesPlayed; /* Indicate how many video frames have been played */
UINT32 uVidFramesSkipped; /* For audio/video sync, some video frames may be dropped. */
UINT32 uVidPlayMediaLen; /* Indicate how many video data have been played (bytes) */
UINT32 uVidRecMediaLen; /* Currently recorded video data length */
UINT32 uVidMP4BuffSizeDB; /* MP4 video decode buffer size (recorded in MP4 file) */
UINT32 uVidMP4AvgBitRate; /* MP4 video average bit rate (record/playback) */
UINT32 uVidMP4MaxBitRate; /* MP4 video maximum bit rate (recorded in MP4 file) */
INT nMPEG4HeaderPos; /* The file offset of MPEG4 video header in the input MP4 file */
INT nMPEG4HeaderLen; /* The length of MPEG4 video header in the input MP4 file */
INT n1stVidFramePos; /* The file offset of first video frame in the input MP4/3GP file */
INT n1stVidFrameLen; /* The lenght of first video frame in the input MP4/3GP file */
INT nMediaClipProgress; /* The progress of media clipping, 0 ~ 100 */
INT nRecDataPerSec; /* Recorder consumed storage space per second (in bytes) */
INT nMP4RecMetaReserved;/* MP4/3GP recorder required reserving meta data storage space (in bytes) */
INT nMP4RecMetaSize; /* Only available in 3GP/MP4 record to memory */
INT nMP4RecMediaSize; /* Only available in 3GP/MP4 record to memory */
/* ID3 tag */
ID3_TAG_T tID3Tag;
INT puVisualData[32]; /* value range 0~31 */
/* MP3 lyric */
INT nLyricLenInFile; /* 0: no lyric, otherwise: the length of MP3 lyric in the MP3 file */
INT nLyricOffsetInFile; /* 0: no lyric, otherwise: the file offset of lyric in the Mp3 file */
UINT32 uLyricCurTimeStamp; /* in 1/100 seconds, time offset of the current lyric from the start of MP3 */
CHAR pcLyricCur[256]; /* on playback MP3, it contained the current lyric */
UINT32 uLyricNextTimeStamp;/* in 1/100 seconds, time offset of the next lyric from the start of MP3 */
CHAR pcLyricNext[256]; /* on playback MP3, it contained the current lyric */
BOOL bIsEncrypted; /* DRM or not */
INT nReserved1;
INT nReserved2;
INT nReserved3;
INT nReserved4;
} MV_INFO_T;
/*-------------------------------------------------------------------------*
* MFL movie configuration (playback, record, and preview) *
*-------------------------------------------------------------------------*/
typedef struct mv_cfg_t
{
/* Media and stream */
MEDIA_TYPE_E eInMediaType; /* PLAY - indicae the type of media to be played */
MEDIA_TYPE_E eOutMediaType; /* RECORD - indicate the type of media to generate */
STRM_TYPE_E eInStrmType; /* PLAY - indicae the input stream method */
STRM_TYPE_E eOutStrmType; /* RECORD - indicate the output stream method */
AU_CODEC_E eAuCodecType; /* RECORD - indicate the audio encode type */
VID_CODEC_E eVidCodecType; /* RECORD - indicate the video encode type */
STRM_FUN_T *ptStrmUserFun; /* BOTH - user defined streaming method */
CHAR *suInMediaFile; /* PLAY - if in stream type is MFL_STREAM_FILE */
CHAR *szIMFAscii; /* PLAY - if in stream type is MFL_STREAM_FILE */
CHAR *suInMetaFile; /* PLAY - if in stream type is MFL_STREAM_FILE */
CHAR *szITFAscii; /* PLAY - if in stream type is MFL_STREAM_FILE */
CHAR *suOutMediaFile; /* RECORD - if out stream type is MFL_STREAM_FILE */
CHAR *szOMFAscii; /* RECORD - if out stream type is MFL_STREAM_FILE */
CHAR *suOutMetaFile; /* RECORD - if out stream type is MFL_STREAM_FILE */
CHAR *szOTFAscii; /* RECORD - if out stream type is MFL_STREAM_FILE */
UINT32 uInMediaMemAddr; /* PLAY - if in stream type is MFL_STREAM_MEMORY */
UINT32 uInMediaMemSize; /* PLAY - if in stream type is MFL_STREAM_MEMORY */
UINT32 uInMetaMemAddr; /* PLAY - if in stream type is MFL_STREAM_MEMORY */
UINT32 uInMetaMemSize; /* PLAY - if in stream type is MFL_STREAM_MEMORY */
UINT32 uOutMediaMemAddr; /* RECORD - if out stream type is MFL_STREAM_MEMORY */
UINT32 uOutMediaMemSize; /* RECORD - if out stream type is MFL_STREAM_MEMORY */
UINT32 uOutMetaMemAddr; /* RECORD - if out stream type is MFL_STREAM_MEMORY */
UINT32 uOutMetaMemSize; /* RECORD - if out stream type is MFL_STREAM_MEMORY */
BOOL bUseTempFile; /* PLAY - use temporary file? */
INT uStartPlaytimePos; /* PLAY - On MP3 playback start, just jump to a
specific time offset then start playback. The time position unit is 1/100 seconds. */
BOOL bStartAndPause; /* PLAY - On MP4/3GP playback, start and pause */
INT nClipStartTime; /* CLIP - media clipping start time offset (in 1/100 secs) */
INT nClipEndTime; /* CLIP - media clipping end time offset (in 1/100 secs) */
BOOL bDoClipVideo; /* CLIP - clip video or not */
/* audio */
BOOL bIsRecordAudio; /* RECORD - 1: recording audio, 0: No */
INT nAuABRScanFrameCnt; /* PLAY - on playback, ask MFL scan how many leading frames
to evaluate average bit rate. -1 means scan the whole file */
INT nAudioPlayVolume; /* PLAY - volume of playback, 0~31, 31 is max. */
INT nAudioRecVolume; /* RECORD - volume of playback, 0~31, 31 is max. */
UINT8 nAuRecChnNum; /* RECORD - 1: record single channel, Otherwise: record left and right channels */
BOOL bIsSbcMode; /* PLAY - work with Bluetooth SBC */
AU_PLAY_DEV_E eAudioPlayDevice; /* PLAY - specify the audio playback audio device */
AU_REC_DEV_E eAudioRecDevice; /* RECORD - specify the audio record device */
AU_SRATE_E eAuRecSRate; /* RECORD - audio record sampling rate */
UINT32 uAuRecBitRate; /* RECORD - audio record initial bit rate */
UINT32 uAuBuffSizeDB; /* RECORD - audio decoder required buffer size */
UINT32 uAuRecAvgBitRate; /* RECORD - audio record average bit rate */
UINT32 uAuRecMaxBitRate; /* RECORD - audio record maxmum bit rate */
/* video */
CHAR bIsRecordVideo; /* RECORD - 1: recording video, 0: No */
INT nMP4VidMaxSSize; /* PLAY - direct MFL should allocate how many memory for MP4/3GP video sample buffer */
INT nVidPlayFrate; /* PLAY - video playback frame rate, only used in M4V file */
INT nVidRecFrate; /* RECORD - video record frame rate */
INT nVidRecIntraIntval; /* RECORD - video record intra frame interval, -1: one first intra, 0: all intra */
UINT16 sVidRecWidth; /* RECORD - width of record image */
UINT16 sVidRecHeight; /* RECORD - height of record image */
UINT32 uVidBuffSizeDB; /* RECORD - video decoder required buffer size */
UINT32 uVidRecAvgBitRate; /* RECORD - video record average bit rate */
UINT32 uVidRecMaxBitRate; /* RECORD - video record maxmum bit rate */
/* callback */
VOID (*ap_time)(struct mv_cfg_t *ptMvCfg);
INT (*au_sbc_init)(struct mv_cfg_t *ptMvCfg);
VOID (*au_sbc_reset_buff)(VOID);
INT (*au_sbc_encode)(struct mv_cfg_t *ptMvCfg, UINT8 *pucPcmBuff, INT nPcmDataLen);
BOOL (*au_is_sbc_ready)(VOID);
INT (*vid_init_decode)(VID_CODEC_E eDecoder, UINT8 *pucBitStrmBuff, UINT32 uBitStrmSize, BOOL *bIsShortHeader,
UINT16 *usImageWidth, UINT16 *usImageHeight);
INT (*vid_init_encode)(UINT8 *pucM4VHeader, UINT32 *puHeaderSize,
BOOL bIsH263, UINT16 usImageWidth, UINT16 usImageHeight);
INT (*vid_enc_frame)(PUINT8 *pucFrameBuff, UINT32 *puFrameSize);
VOID (*vid_rec_frame_done)(UINT8 *pucFrameBuff);
INT (*vid_dec_frame)(VID_CODEC_E eDecoder, BOOL bIsSilent, UINT8 *pucFrameBuff, UINT32 *puFrameSize);
INT (*vid_dec_state)(VOID);
VOID (*au_on_start)(struct mv_cfg_t *ptMvCfg);
VOID (*au_on_stop)(struct mv_cfg_t *ptMvCfg);
VOID (*the_end)(struct mv_cfg_t *ptMvCfg);
/*
* others - for MFL internal used
*/
VOID *data_mv;
VOID *data_info;
INT data_play_action;
INT data_play_param;
INT data_rec_action;
INT data_rec_param;
/* for extra parameters */
VOID *param1;
VOID *param2;
VOID *param3;
VOID *param4;
} MV_CFG_T;
/*-------------------------------------------------------------------------*
* MFL KTV maker settings *
*-------------------------------------------------------------------------*/
typedef struct ktv_cfg_t
{
AU_CODEC_E eAuCodecType; /* MP3 or AAC */
CHAR *suInMP4File; /* Full path name of the input MP4/3GP file */
CHAR *suInAudioFile; /* Full path name of the input MP3/AAC file */
CHAR *suInLyricFile; /* Full path name of the input lyric file */
CHAR *suOutMediaFile; /* Output media file */
CHAR *szOMFAscii;
CHAR *suOutMetaFile; /* Output meta file */
CHAR *szOTFAscii;
BOOL bStopIfVideoEnd; /* If there's no more video frames, stop KTV maker. */
BOOL bStopIfAudioEnd; /* If there's no more audio frames, stop KTV maker. */
INT nVideoClipStart; /* The video clip start time position in 1/100 seconds */
INT nVideoClipEnd; /* The video clip end time position in 1/100 seconds */
INT nAudioClipStart; /* The video clip start time position in 1/100 seconds */
INT nAudioClipEnd; /* The video clip end time position in 1/100 seconds */
BOOL bUseTempFile;
INT nMP4VidMaxSSize;
/* callback */
VOID (*ap_time)(struct mv_cfg_t *ptMvCfgKtv);
VOID (*the_end)(struct mv_cfg_t *ptMvCfgKtv);
/*
* others - for MFL internal used
*/
MV_CFG_T tMvCfgMp4;
MV_CFG_T tMvCfgAu;
MV_CFG_T tMvCfgKtv;
} KTV_CFG_T;
/*-------------------------------------------------------------------------*
* MFL API List *
*-------------------------------------------------------------------------*/
extern INT mflMediaPlayer(MV_CFG_T *ptMvCfg);
extern INT mflMovieMaker(MV_CFG_T *ptMvCfg);
extern INT mflMediaClipper(MV_CFG_T *ptMvCfg);
extern INT mflKtvMaker(KTV_CFG_T *ptKtvMk);
extern INT mflGetMovieInfo(MV_CFG_T *ptMvCfg, MV_INFO_T **ptMvInfo);
extern INT mflPlayControl(MV_CFG_T *ptMvCfg, PLAY_CTRL_E ePlayCtrl, INT nParam);
extern INT mflRecControl(MV_CFG_T *ptMvCfg, REC_CTRL_E eRecCtrl, INT nParam);
extern INT mflSetEqualizer(EQ_EFT_E eEqEft, INT nPreAmp, INT *pnBands);
extern INT mflGetEqualizer(MV_CFG_T *ptMvCfg, INT *pnBands);
extern VOID mflEnableVisualizer(INT nFrameInterval);
extern VOID mflDisableVisualizer(VOID);
extern VOID mflDisableEqualizer(VOID);
extern VOID mflSetAudioPlayVolume(MV_CFG_T *ptMvCfg, INT volume);
extern VOID mflSetAudioRecVolume(MV_CFG_T *ptMvCfg, INT volume);
extern INT mflPreviewMediaInfo(MV_CFG_T *ptMvCfg, MV_INFO_T *ptMinfo);
extern INT mflEnable3DSurround(VOID *pConfig);
extern INT mflDisable3DSurround(VOID);
extern INT mflTuneQ3DSurround(INT nSpread, INT nDelay);
extern VOID mflAuGetAudioRecData(UINT32 *uStartAddress, UINT32 *uLength);
extern UINT32 mflEstimateAviFileSize(MV_CFG_T *ptMvCfg);
extern INT mflShrinkAviFile(CHAR *suFileName);
extern INT mfl_avi_preview(MV_CFG_T *ptMvCfg, MV_INFO_T *ptMvInfo);
#endif /* _MEDIA_FILE_LIB_H_ */<file_sep>/NVT LOADER/production/EMU_Draw.c
#include "Font.h"
void Draw_InitialBorder(S_DEMO_FONT* ptFont)
{
S_DEMO_RECT s_sDemo_Rect;
UINT16 u16FontColor;
u16FontColor = DemoFont_GetFontColor(ptFont);
DemoFont_ChangeFontColor(ptFont,
0xFFE0);
s_sDemo_Rect.u32StartX =0;
s_sDemo_Rect.u32StartY = 0;
s_sDemo_Rect.u32EndX = _LCM_WIDTH_-1,
s_sDemo_Rect.u32EndY = _LCM_HEIGHT_-1;
DemoFont_Border(ptFont,
&s_sDemo_Rect,
_BORDER_WIDTH_);
DemoFont_ChangeFontColor(ptFont,
u16FontColor);
}
void Draw_ItemBorder(S_DEMO_FONT* ptFont)
{
S_DEMO_RECT s_sDemo_Rect;
UINT16 u16FontColor;
u16FontColor = DemoFont_GetFontColor(ptFont);
DemoFont_ChangeFontColor(ptFont,
0xFFE0);
s_sDemo_Rect.u32StartX =0;
s_sDemo_Rect.u32StartY = 0;
s_sDemo_Rect.u32EndX = _LCM_WIDTH_-1,
s_sDemo_Rect.u32EndY = _FONT_RECT_HEIGHT_-1;
DemoFont_Border(ptFont,
&s_sDemo_Rect,
_BORDER_WIDTH_);
DemoFont_ChangeFontColor(ptFont,
u16FontColor);
}<file_sep>/NVT LOADER/production/EMU_Font.c
/****************************************************************************
* *
* Copyright (c) 2011 Nuvoton Tech. Corp. All rights reserved. *
* *
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_sic.h"
#include "nvtfat.h"
#include "Font.h"
#include "emuProduct.h"
void EMU_InitFont(
S_DEMO_FONT* ptFont,
UINT32 u32FrameBufAddr
)
{
InitFont(ptFont,
u32FrameBufAddr);
} <file_sep>/NVTFAT/example/RAMDiskDriver.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef W90N740
#include "supports.h"
#else
#include "wbio.h"
#endif
#include "nvtfat.h"
UINT32 _RAMDiskBase;
static INT ram_disk_init(PDISK_T *ptPDisk)
{
return 0;
}
static INT ram_disk_ioctl(PDISK_T *ptPDisk, INT control, VOID *param)
{
return 0;
}
static INT ram_disk_read(PDISK_T *ptPDisk, UINT32 uSecNo,
INT nSecCnt, UINT8 *pucBuff)
{
memcpy(pucBuff, (UINT8 *)(_RAMDiskBase + uSecNo * 512), nSecCnt * 512);
return FS_OK;
}
static INT ram_disk_write(PDISK_T *ptPDisk, UINT32 uSecNo,
INT nSecCnt, UINT8 *pucBuff, BOOL bWait)
{
memcpy((UINT8 *)(_RAMDiskBase + uSecNo * 512), pucBuff, nSecCnt * 512);
return FS_OK;
}
STORAGE_DRIVER_T _RAMDiskDriver =
{
ram_disk_init,
ram_disk_read,
ram_disk_write,
ram_disk_ioctl,
};
INT InitRAMDisk(UINT32 uStartAddr, UINT32 uDiskSize)
{
PDISK_T *ptPDisk;
_RAMDiskBase = uStartAddr;
ptPDisk = malloc(sizeof(PDISK_T));
ptPDisk->nDiskType = DISK_TYPE_HARD_DISK | DISK_TYPE_DMA_MODE;
ptPDisk->uTotalSectorN = uDiskSize / 512;
ptPDisk->nSectorSize = 512;
ptPDisk->uDiskSize = uDiskSize;
ptPDisk->ptDriver = &_RAMDiskDriver;
fsPhysicalDiskConnected(ptPDisk);
return 0;
}
<file_sep>/VPOST/Example_OSD/Src/W55FA93_VPOST_OSD.c
#include "wblib.h"
#include "w55fa93_vpost.h"
#include "w55fa93_reg.h"
#include "w55fa93_osd.h"
VOID vpostOSDInit(POSDFORMATEX posdformatex, UINT32 *pOSDFramebuf)
{
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) & ~OSD_CTL_OSD_FSEL | (posdformatex-> ucOSDSrcFormat << 24));
outp32(REG_LCM_LINE_STRIPE, inp32(REG_LCM_LINE_STRIPE) & LINE_STRIPE_F1_LSL);
outp32(REG_LCM_OSD_SIZE, ((posdformatex->nOSDScreenWidth-1) & 0x3FF) | ((posdformatex->nOSDScreenHeight-1) & 0x3FF)<<16); // Set OSD Size
outp32(REG_LCM_OSD_SP, (posdformatex->nOSDX1StartPixel & 0x3FF) | ((posdformatex->nOSDX1StartPixel & 0xFF) << 16));
outp32(REG_LCM_OSD_ADDR, (UINT32) pOSDFramebuf);
outp32(REG_LCM_OSD_BEP, 0x00010001);
outp32(REG_LCM_OSD_BO, 0x00010001);
}
VOID *vpostGetOSDFrameBuffer(void)
{
return (void *)inp32(REG_LCM_OSD_ADDR);
}
VOID vpostChangeOSDFrameBuffer(UINT32 *pOSDFramebuf)
{
outp32(REG_LCM_OSD_ADDR, (UINT32) pOSDFramebuf);
}
INT32 vpostSpitOSD(UINT32 OSDX1End, UINT32 OSDY1End, UINT32 XBarOffset, UINT32 YBarOffset)
{
if ((int)OSDX1End <= (int)(inp32(REG_LCM_OSD_SP) & 0x3FF))
return -1;
if ((int)OSDY1End <= (int)(inp32(REG_LCM_OSD_SP)>>16 & 0x3FF))
return -1;
if ((int)(OSDX1End + XBarOffset) >= (int)(inp32(REG_LCM_OSD_SIZE) & 0x3FF))
return -1;
if ((int)(OSDY1End + YBarOffset) >= (int)(inp32(REG_LCM_OSD_SIZE)>>16 & 0x3FF))
return -1;
outp32(REG_LCM_OSD_BEP, (OSDX1End & 0x3FF) | ((OSDY1End & 0x3FF) << 16) );
outp32(REG_LCM_OSD_BO, (XBarOffset & 0x3FF) | ((YBarOffset & 0x3FF) << 16) );
return 0;
}
VOID vpostGetBarXY(UINT32 *OSDX1End, UINT32 *OSDY1End, UINT32 *XBarOffset, UINT32 *YBarOffset)
{
*OSDX1End = inp32(REG_LCM_OSD_BEP) & 0x3FF;
*OSDY1End = (inp32(REG_LCM_OSD_BEP) >> 16) & 0x3FF;
*XBarOffset = inp32(REG_LCM_OSD_BO) & 0x3FF;
*YBarOffset = (inp32(REG_LCM_OSD_BO) >> 16) & 0x3FF;
}
INT32 vpostOSDControl(INT32 cmd, INT32 arg)
{
switch(cmd)
{
case eOSD_SHOW:
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) | OSD_CTL_OSD_EN);
break;
case eOSD_HIDE:
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) & ~OSD_CTL_OSD_EN);
break;
case eOSD_CLEAR:
break;
case eOSD_SET_TRANSPARENT:
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) & ~OSD_CTL_OSD_TC | (arg & 0xFFFF));
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) | (0x01 << 28));
break;
case eOSD_CLEAR_TRANSPARENT:
outp32(REG_LCM_OSD_CTL, inp32(REG_LCM_OSD_CTL) & ~BIT28);
break;
}
return 0;
}
<file_sep>/UDC/example/video_class/vendor_mass.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wblib.h"
#include "w55fa93_reg.h"
#include "usbd.h"
#include "mass_storage_class.h"
#ifndef __RAM_DISK_ONLY__
#include "nvtfat.h"
#include "w55fa93_sic.h"
#include "w55fa93_gnand.h"
#endif
BOOL USB_Check(VOID)
{
return TRUE;
}
VOID vendor_mass(VOID)
{
INT32 status;
udcOpen();
mscdInit();
mscdFlashInit(NULL,status);
udcInit();
mscdMassEvent(USB_Check);
mscdDeinit();
udcDeinit();
udcClose();
}
<file_sep>/NVT LOADER/production/EMU_EDMA.c
/***************************************************************************
* *
* Copyright (c) 2008 <NAME>. All rights reserved. *
* *
***************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include "wblib.h"
#include "nvtfat.h"
#include "AviLib.h"
#include "W55FA93_reg.h"
#include "W55FA93_Vpost.h"
#include "USB.h"
#include "Font.h"
#include "nvtloader.h"
#include "emuProduct.h"
EMU_EDMA(
S_DEMO_FONT* ptFont,
UINT32 u32FrameBufAddr
)
{
INT nStatus, u32Ypos=0;
char Array1[64];
Font_ClrFrameBuffer(u32FrameBufAddr);
sprintf(Array1, "EDMA Test...");
DemoFont_PaintA(ptFont,
0,
u32Ypos,
Array1);
}<file_sep>/SYSLIB/Example/demo.h
#define DBG_PRINTF sysprintf
//#define DBG_PRINTF(...)<file_sep>/UDC/example/video_class/GCD.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "wblib.h"
UINT8 GCD(UINT16 m1, UINT16 m2)
{
UINT16 m;
if(m1<m2)
{
m=m1; m1=m2; m2=m;
}
if(m1%m2==0)
return m2;
else
return (GCD(m2,m1%m2));
}
|
da0b6e25c6898734296099de90069ed76ed1d65b
|
[
"C",
"INI"
] | 41
|
C
|
OpenNuvoton/N32901-3_NonOS_BSP
|
8315e28d519a83a9245c288e0f60f5934af1c09f
|
65f40e204aadf86e613dc6062d3959db44f9b05d
|
refs/heads/master
|
<file_sep>require File.join(Rails.root, 'bot/tattletale.rb')
<file_sep># Instroduction
freestyle bot in slack

# Usage
set up in local
```
bundle install
export SLACK_API_TOKEN= ...
rails s
```
if you want to deploy to heroku
```
heroku config:set SLACK_API_TOKEN= ...
git push heroku master
```
# Resource
- [How to create my slack bot](https://api.slack.com/bot-users)
- [slack-ruby-client](https://github.com/slack-ruby/slack-ruby-client)
- [slack-bot-on-rails](https://github.com/slack-ruby/slack-bot-on-rails)
<file_sep>$:.unshift File.dirname(__FILE__)
require 'freestyle'
Thread.abort_on_exception = true
Thread.new do
@client.start!
end
<file_sep>require 'slack-ruby-client'
require 'nokogiri'
require 'open-uri'
Slack.configure do |config|
config.token = ENV['SLACK_API_TOKEN']
config.logger = Logger.new(STDOUT)
config.logger.level = Logger::INFO
fail 'Missing ENV[SLACK_API_TOKEN]!' unless config.token
end
client = Slack::RealTime::Client.new
client.on :hello do
puts client.self.id
puts "Successfully connected, welcome '#{client.self.name}' to the '#{client.team.name}' team at https://#{client.team.domain}.slack.com."
end
client.on :message do |data|
# client.typing channel: data.channel
case data.text
# when 'bot hi' then
# client.message channel: data.channel, text: "Hi <@#{data.user}>!"
# when 'hippopman' then
# client.message channel: data.channel, text: "Hi <@#{data.user}>!"
# when "<@#{client.self.id}>" then
# client.message channel: data.channel, text: "Hi <@#{data.user}>!"
# when /^bot/ then
# client.message channel: data.channel, text: "Sorry <@#{data.user}>, what?"
when /^<@#{client.self.id}>\s*(.*)/ then
keyword = data.text.match(/^<@#{client.self.id}\s*(.*)/).captures[0] || ''
puts "keyword: #{keyword}"
targetUrl = "http://m.niucodata.com/freestyle/freestyle.php?key=#{CGI::escape(keyword)}"
doc = Nokogiri::HTML(open(targetUrl))
content = doc.css('div.mdui-container').text
startIndex = content.index("\n", 3)
endIndex = content.index('欣赏')
freestyleText = content[startIndex...endIndex]
freestyle = freestyleText.gsub("\n", '')
puts freestyle
client.message channel: data.channel, text: "#{freestyle}"
end
end
# client.on :close do |_data|
# puts 'Connection closing, exiting.'
# end
#
# client.on :closed do |_data|
# puts 'Connection has been disconnected.'
# end
# client.start!
@client = client
|
b80af708c7b66b38cbdf8b5796ef2eb2519bcb2b
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
chengcyber/slack-hiphopman
|
9d87fb8f866033d58d00533ecdeab41a9fcccf3b
|
3c0905391c61072432183b8f8ca8bf62c6710b80
|
refs/heads/master
|
<file_sep>$:.unshift File.dirname($0)
require 'ants.rb'
def log s
# $stderr.puts s
end
ai=AI.new
history = {}
visits = {}
ai.setup do |ai|
# your setup code here, if any
end
ai.run do |ai|
current_orders = {}
ai.my_ants.each_with_index do |ant, i|
log "Distance between -1,0 and 0,5:"
log ai.distance([-1,0], [0,5])
log "Fastest route between 0,0 and 1,1:"
log ai.direction([0,0], [1,1])
log "\nAnt #{i}:"
close_foods = ai.foods.sort { |food|
ai.distance([ant.row, ant.col], [food[0], food[1]])
}.reject { |food|
ai.distance([ant.row, ant.col], [food[0], food[1]]) > ai.viewradius*2
}
close_hills = ai.enemy_hills.sort { |hill|
ai.distance([ant.row, ant.col], [hill[0], hill[1]])
}.reject { |hill|
ai.distance([ant.row, ant.col], [hill[0], hill[1]]) > ai.viewradius*2
}
scores = [:N, :E, :S, :W].map { |dir|
dest = ant.square.neighbor(dir)
if !dest.land? or dest.ant?
score = nil
elsif history[dest]
# Higher age is good
score = ai.turn_number - history[dest]
# if age < 5 and age > 2
# score = score + 1000
# else
# score = age
# end
else
# Untravelled is best choice
score = 1001
end
if score
if close_hills.length > 0 and
ai.direction([ant.row, ant.col], close_hills[0]).member? dir
log "******************* HILL HUNT *************************"
score += 300
end
if close_foods.length > 0 and
ai.direction([ant.row, ant.col], close_foods[0]).member? dir
log "******************* FOOD HUNT *************************"
score += 300
end
score = score - (visits[dest] or 0) * ai.my_ants.length.to_f / 10
log "ant #{i} - #{dir} - score #{score or 'nil'}" unless !score
end
{ dir => score }
}
scores = scores.reduce(Hash.new) { |memo, obj|
memo.merge obj
}
# log "scores for ant #{i}:"
# scores.each_pair do |key, value|
# log "direction #{key} - score #{value}"
# end
directions = [:N, :E, :S, :W].sort {|x| 0.5 <=> rand }.reject { |dir|
scores[dir] == nil
}.sort { |x,y|
scores[x] <=> scores[y]
}.reverse
# log "Possible moves, in order:"
# directions.each {|dir|
# log "#{dir} - #{scores[dir]}"
# }
if directions.length > 0
dir = directions.first
dest = ant.square.neighbor(dir)
log "ant #{i} going #{dir} with #{visits[dest] or 0} visits"
if !current_orders[dest]
ant.order dir
current_orders[dest] = true
history[dest] = ai.turn_number
visits[dest] = (visits[dest] or 0) + 1
else
log "Blocked"
end
else
log "No good move for ant #{i}"
end
# all_blocked = directions.reject { |dir|
# loc = ant.square.neighbor(dir)
# !loc.land? or
# (history[loc] and (history[loc] > ai.turn_number - AVOID_TIME + AVOID_TIME/4)) or
# ant.square.neighbor(dir).ant?
# }.empty?
# directions.each do |dir|
# loc = ant.square.neighbor(dir)
# if loc.land? and
# (all_blocked or !(history[loc] and (history[loc] > ai.turn_number - AVOID_TIME))) and
# not current_orders[loc] and
# not loc.ant?
# history[loc] = ai.turn_number unless all_blocked
# current_orders[loc] = true
# ant.order dir
# break
# end
# end
end
end
|
653022b5e51d053ae8262169f8ee59efb9420ff6
|
[
"Ruby"
] | 1
|
Ruby
|
kek/antbot
|
bed2432d91d20c47814b3658d636168356a09ff6
|
ccfa513825c6dda6a6f9d2404507e8338d819928
|
refs/heads/master
|
<repo_name>ghostlpx/alertUI<file_sep>/js/widget.js
//为Widget类添加统一的生命周期
define(function(){
function Widget(){
//this.handlers = {};
this.boundingBox = {}; //属性:最外层容器
}
Widget.prototype = {
on : function(type,handle){
if( typeof this.handlers[type] == 'undefined' ){
this.handlers[type] = [];
}
this.handlers[type].push(handle);
return this;
},
fire : function( type,data ){
if( this.handlers[type] instanceof Array ){
var handlers = this.handlers[type];
for( var i=0; i<handlers.length; i++ ){
handlers[i](data);
}
}
},
//调用render方法可直接执行子类实现的接口方法
render : function(container){ //方法:渲染组件
this.renderUI();
this.handlers = {}; //DOM节点被删除之后,清空handlers
this.bindUI();
this.syncUI();
$(container || document.body).append( this.boundingBox );
},
destroy : function(){ //方法:销毁组件
this.destructor();
this.boundingBox.off(); //取消对boundingBox节点的事件监听
this.boundingBox.remove();
},
//以下4个接口需要子类去实现具体的方法
renderUI : function(){}, //接口:添加DOM节点
bindUI : function(){}, //接口:监听事件
syncUI : function(){}, //接口:初始化组件属性
destructor : function(){} //接口:组件销毁前的处理函数
}
return {
Widget : Widget
}
});<file_sep>/README.md
可定制尺寸、位置、皮肤,接口丰富。
使用requireJS进行模块化管理,偷懒使用了jquery并导入了jqueryUI插件实现了拖拽接口。
css可能不太美观,不过后期如果有好的UI设计的话,可以通过皮肤接口来随心所欲地换肤~
通过widget抽象类来尽可能地统一开发风格,规范开发方法。
<file_sep>/js/window.js
//jqueryUI模块被导入之后,jquery对象就自动新增了一些方法,事实上这里$UI其实并没有用到
define(['widget','jquery','jqueryUI'],function(widget,$,$UI){ //导入widget抽象类
function Window(){
this.cfg = {
width : 500,
height : 300,
title : '系统消息',
content : '',
text4AlertBtn : '确定', //定制按钮文案
text4ConfirmBtn : '确定',
text4CancelBtn : '取消',
text4PromptBtn : '确定',
isPromptInputPassword : false,
defaultValue4PromptInput : '',
maxlength4PromptInput : 10,
hasMask : true, //模态弹窗
hasCloseBtn : false,
skinClassName : null, //皮肤接口
isDraggable : true, //拖拽接口
dragHandle : null, //拖拽把手
handler4AlertBtn : null, //所要执行的回调函数
handler4CloseBtn : null ,
handler4ConfirmBtn : null,
handler4CancelBtn : null,
handler4PromptBtn : null
};
};
Window.prototype = $.extend({},new widget.Widget(),{ //Window.prototype继承自widget抽象类
renderUI : function(){ //增添DOM节点
var footContent = '';
switch(this.cfg.winType){
case 'alert':
footContent = '<input type="button" value='+ this.cfg.text4AlertBtn +' class="window_alertBtn" />';
break;
case 'confirm':
footContent = '<input type="button" value='+ this.cfg.text4ConfirmBtn +
' class="window_confirmBtn" /><input type="button" value='+
this.cfg.text4CancelBtn +' class="window_cancelBtn" />';
break;
case 'prompt':
this.cfg.content += '<p class="window_promptInputWrapper"><input type="'+
(this.cfg.isPromptInputPassword?"password":"text")+'" value="'+ this.cfg.defaultValue4PromptInput
+'" maxlength="'+ this.cfg.maxlength4PromptInput +'" class="window_promptInput" /></p>';
footContent = '<input type="button" value='+ this.cfg.text4PromptBtn +
' class="window_promptBtn" /><input type="button" value='+
this.cfg.text4CancelBtn +' class="window_cancelBtn" />';
break;
}
this.boundingBox = $('<div class="window_boundingBox">'+
'<div class="window_body">'+ this.cfg.content +'</div>'
+'</div>');
if( this.cfg.winType != 'common' ){
this.boundingBox.prepend('<div class="window_header">'+ this.cfg.title +'</div>');
this.boundingBox.append('<div class="window_footer">'+ footContent +'</div>');
}
if( this.cfg.hasMask ){
this._mask = $('<div class="window_mask"></div>');
this._mask.appendTo('body');
}
if( this.cfg.hasCloseBtn ){
this.boundingBox.append('<span class="window_closeBtn">X</span>');
}
this.boundingBox.appendTo(document.body);
this._promptInput = this.boundingBox.find('.window_promptInput');
},
bindUI : function(){ //事件绑定和触发
var This = this;
this.boundingBox.delegate('.window_alertBtn','click',function(){
This.fire('alert');
This.destroy();
}).delegate('.window_closeBtn','click',function(){
This.fire('close');
This.destroy();
}).delegate('.window_confirmBtn','click',function(){
This.fire('confirm');
This.destroy();
}).delegate('.window_cancelBtn','click',function(){
This.fire('cancel');
This.destroy();
}).delegate('.window_promptBtn','click',function(){
This.fire('prompt',This._promptInput.val());
This.destroy();
});
if(this.cfg.handler4AlertBtn){
this.on( 'alert',this.cfg.handler4AlertBtn );
}
if(this.cfg.handler4CloseBtn){
this.on( 'close',this.cfg.handler4CloseBtn );
}
if(this.cfg.handler4ConfirmBtn){
this.on( 'confirm',this.cfg.handler4ConfirmBtn );
}
if(this.cfg.handler4CancelBtn){
this.on( 'cancel',this.cfg.handler4CancelBtn );
}
if(this.cfg.handler4PromptBtn){
this.on( 'prompt',this.cfg.handler4PromptBtn );
}
},
syncUI : function(){ //初始化组件属性
this.boundingBox.css({
width : this.cfg.width + 'px',
height : this.cfg.height + 'px',
left : ( this.cfg.x || (window.innerWidth - this.cfg.width)/2 ) + 'px',
top : ( this.cfg.y || ( window.innerHeight - this.cfg.height )/2 ) + 'px'
});
if( this.cfg.skinClassName ){
boundingBox.addClass(this.cfg.skinClassName);
}
if( this.cfg.isDraggable ){
if( this.cfg.dragHandle ){
this.boundingBox.draggable({ handle:this.cfg.dragHandle }); //默认情况下jquery是没有draggable方法的,这是导入jqueryUI模块后增加的
}else{
this.boundingBox.draggable();
}
}
},
destructor : function(){
this._mask && this._mask.remove();
},
//alert已经被简化到如下
alert : function(cfg){
$.extend(this.cfg, cfg, {winType:'alert'});
this.render();
return this;
},
confirm : function(cfg){
$.extend(this.cfg, cfg, {winType:'confirm'});
this.render();
return this;
},
prompt : function(cfg){
$.extend(this.cfg, cfg, {winType:'prompt'});
this.render();
this._promptInput.focus();
return this;
},
common : function(cfg){
$.extend(this.cfg, cfg, {winType:'common'});
this.render();
return this;
}
});
return {
Window:Window
};
});
|
2a4b1c788ee2e6eea277a23040f6a5ce19828813
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
ghostlpx/alertUI
|
74c989d7211cfe9bf856a7796813b0f263256290
|
0ce1f95cd3851f37e30777430a1acb144b47fd8c
|
refs/heads/master
|
<repo_name>Kyramee/La_poutine_avec_tables<file_sep>/poutine/src/poutine/Facture.java
package poutine;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
public class Facture {
private ArrayList<String> listeClients;
private ArrayList<String> listeNomPlats;
private ArrayList<String> listePrixPlats;
private ArrayList<String> mapKeyTable;
private HashMap<String, ArrayList<String>> clientsKey;
private HashMap<String, HashMap<String, Double>> listeTable;
private BufferedWriter ficEcriture;
public String ligneFac; // Ligne utile uniquement pour tester
// Constructeur
public Facture() {
this.listeClients = new ArrayList<>();
this.listeNomPlats = new ArrayList<>();
this.listePrixPlats = new ArrayList<>();
this.mapKeyTable = new ArrayList<>();
this.listeTable = new HashMap<>();
this.clientsKey = new HashMap<>();
ecrire();
ecrire("Bienvenue chez Barette!");
}
public void addListeClients(String client) {
this.listeClients.add(client);
}
public void addListePlats(String plat) {
String[] platSplit = plat.split(" ");
this.listeNomPlats.add(platSplit[0]);
this.listePrixPlats.add(platSplit[1]);
}
public void addListeCommandes(String commande) {
String[] comSplit = commande.split(" ");
if (comSplit.length != 4) {
ecrire("La commande " + commande + " ne possède pas un format de commande invalide");
} else if (!this.listeClients.contains(comSplit[1])) {
ecrire("Pour la commande " + commande + ", le nom du client n'est pas dans la liste");
} else if (!this.listeNomPlats.contains(comSplit[2])) {
ecrire("Pour la commande " + commande + ", le nom du plat n'est pas dans la liste");
} else if (Integer.parseInt(comSplit[3]) < 1) {
ecrire("Pour la commande " + commande
+ ", la quantité de nourriture ne peux pas être négative ou égal à 0");
} else {
if (this.mapKeyTable.contains(comSplit[0])) {
if(this.listeTable.get(comSplit[0]).containsKey(comSplit[1])) {
this.listeTable.get(comSplit[0]).put(comSplit[1], this.listeTable.get(comSplit[0]).get(comSplit[1]) + calculerCoutPlat(comSplit));
} else {
this.clientsKey.get(comSplit[0]).add(comSplit[1]);
this.listeTable.get(comSplit[0]).put(comSplit[1], calculerCoutPlat(comSplit));
}
} else {
this.mapKeyTable.add(comSplit[0]);
this.listeTable.put(comSplit[0], new HashMap<>());
this.listeTable.get(comSplit[0]).put(comSplit[1], calculerCoutPlat(comSplit));
this.clientsKey.put(comSplit[0], new ArrayList<>());
this.clientsKey.get(comSplit[0]).add(comSplit[1]);
}
}
}
public void affichageFacture() {
ArrayList<String> clients = new ArrayList<>();
ecrire("\n");
ecrire("FACTURE:");
for (String table : this.mapKeyTable) {
clients = this.clientsKey.get(table);
//"Table: " + table
ecrire(table , clients);
ecrire("\n");
}
try {
ficEcriture.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void ecrire() {
String timeStamp = new SimpleDateFormat("dd_MM_yy-HH;mm").format(Calendar.getInstance().getTime());
String filename = "Facture-du-" + timeStamp + ".txt";
try {
ficEcriture = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset()));
} catch (IOException err) {
System.out.print(err);
}
}
private void ecrire(String message) {
System.out.println(message);
try {
ficEcriture.write(message);
ficEcriture.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private void ecrire(String table, ArrayList<String> listeClient) {
double prix = 0;
String ligneClient = "";
DecimalFormat df = new DecimalFormat("0.##");
for ( String client : listeClient ) {
prix += this.listeTable.get(table).get(client);
ligneClient += client + "\n";
}
double tps = prix * 0.05;
double tvq = prix * 0.10;
if ( prix > 100 || listeClient.size() >= 3 ) {
double frais = prix * 0.15;
ecrire( "Table: " + table + ", Prix: " + df.format(prix) + "$, Frais: " + df.format( frais ) + "$ TPS: " + df.format(tps)
+ "$ TVQ: " + df.format(tvq)
+ "$ Total: " + df.format((prix + tps + tvq + frais)) + "$" );
} else {
ecrire( "Table: " + table + ", Prix: " + df.format(prix) + "$, TPS: " + df.format(tps) + "$ TVQ: " + df.format(tvq)
+ "$ Total: " + df.format((prix + tps + tvq)) + "$" );
}
ecrire(ligneClient);
}
private double calculerCoutPlat(String[] comSplit) {
return Double.parseDouble(this.listePrixPlats.get(this.listeNomPlats.indexOf(comSplit[2])))
* Double.parseDouble(comSplit[3]);
}
}
|
d91262888f1dfc25dbaaaff520bc7364d2427702
|
[
"Java"
] | 1
|
Java
|
Kyramee/La_poutine_avec_tables
|
88757af9d5dcfb20df465f333113c562481e9ad0
|
897c8349d189d7d739b9b90491e8293134ea6608
|
refs/heads/master
|
<repo_name>dr4g0nsr/xtreamui<file_sep>/README.md
So this has been a long time coming, but here's a new release. Okay it's still early access, I just needed to get something out there for the following reasons:
To show I'm back
To fix some security issues that could affect earlier releases
Now this release addresses a vulnerability in Xtream Codes where a person could restream your streams without a valid user ID, making them invisible. To address this I've enforced some security settings, also implemented a cron that checks for invalid streams and kills them. On top of this I've enforced mag locks and minimum password length of 8 characters for resellers. You CAN change these settings back, but they're forced on every update.
An Xtream UI flaw I've known about for a while is relating to XSS (Cross-Site Scripting), I planned to fix this months ago but never really got around to it, and didn't really anticipate how dangerous this could be so I've made much more of an effort this time around. I now believe this release to be fully patched against any XSS attacks and I've also reinforced any SQL statements to ensure they're correctly escaped to block SQL injection attacks. This is easily the most secure release yet.
I've removed auto-update entirely, however the current version can be checked by going to the Settings page. As well as this, I've also included a GeoLite2 update option. Head to the settings page and if an update is available you can click to install it. My server periodically downloads the GeoLite2 database direct from MaxMind so it's all automated.
On top of the above I've also reintegrated the database editor, however password protected with your MySQL password. To get this MySQL password, run the config.py file in the pytools folder and decrypt your configuration file. Store this somewhere so you can access the database when required.
Tables are updated automatically now so there's no need to click the Update Tables option etc. This will only work if permissions are correct, and Xtream UI will warn you if this isn't the case on the login screen. To fix permissions run the new permissions.sh file in /home/xtreamcodes/iptv_xtream_codes.
This may not seem like the biggest update in the world, but it's a very important one and marks my return to releasing new features. Release schedule will be set in advance, with the plan to be fortnightly. This will happen once 22 becomes official, integrating a few more features and bugfixes before that happens.
The rest of this release consists of various bugfixes, I've read through various posts and integrated what I could.
Next Official Release (22 Official):
I will be implementing further bugfixes along with completing the translation. The current release is about 80% translation mapped, once this is 100% I'll have it translated into various languages for 22 official.
Future Release (23 EA):
VPN Integration! I told you it was coming, and it will be. Okay okay, there was a delay, but still. It's coming.
The plan is to give Xtream UI users the ability to host their own VPN servers, with Xtream UI automatically installing and managing those servers for you. You click Install VPN, give it the IP and root SSH credentials and the installer will do it's thing.
VPN capability can be allocated to packages, with a separate option for max simultaneous connections. The VPN will only be authenticated during the period of the package. When a user is given access to the VPN, they authenticate to the API using their line username and password so they don't need an additional set of credentials, however the actual VPN authentication takes place with a secure certificate generated on the main panel. The VPN servers will have NFS access to the certificate folder to authenticate, and will use an API to communicate back to the main server to show usage statistics, upload, download, current users, CPU usage, memory usage, uptime etc.
VPN servers will be load balanced per country / city, will adhere to max connection per server limits and you'll be able to see throughput on the dashboard to ensure your servers aren't overloaded. Full logging is available in the interface.
As it's OpenVPN based, you can connect via the OpenVPN client for Windows, Android, iOS or many other devices. The users will be able to download their certificates from the panel (if the setting is enabled) or use an URL / QR Code. I've built a very basic Android app that's completely open source and will be provided free of charge, I want those more experienced with Java than I am to make improvements to it and release to the public, and the idea is that whoever wants it can rebrand it and utilise it.
Here's a quick demo of the basic app:
https://streamable.com/a9s51
I'll be providing my own API, but will also ensure Xtream UI is backwards compatible with other VPN API's such as DeployVPN.
Changelog for this Release:
Refined santisation for speed. No longer sanitises MySQL output, only input.
Added STB lock reset to MAG Events for those who have issues with MAG devices.
Added a timeout to mysql queries for those with too many user_activity entries for the page to load.
Removed auto-refresh on user_activity as there are usually too many entries.
Fixed sort functions on User IP's page.
Fixed stream table on created channel page.
Added a sanitisation script to scan the database for unsanitised input and correct it. Only needs to be run once (see below).
To run the sanitisation script, if you believe your server to have been infiltrated in previous releases, run this:
CODE: SELECT ALL
/home/xtreamcodes/iptv_xtream_codes/php/bin/php /home/xtreamcodes/iptv_xtream_codes/adtools/sanitise.php
It'll take a while but it checks the entire database for any malformed or malicious input.
Previously in R22 Early Access (A-D):
Fixed movies not showing in bouquet order.
Forced security upgrades to fix Xtream Codes exploit.
Patched all files against XSS exploits.
Added GeoLite2 updater.
Reintegrated database editor.
Added user-agent to Live Connections page.
Fixed search not being actioned on refresh.
Added stream icons to stream page.
Added EPG status indicator to stream page.
Added settings option to disable auto-refresh by default.
Ensured quotes " don't appear in bouquets in SQL. Can break things otherwise.
Fixed any bouquet issues (I believe).
Added noindex and nofollow to header to deter search engines from indexing.
Updated NGINX to newer, faster version.
Removed reseller API for now, the code may be insecure.
Fixed activity logs page.
Added interactive connection statistics to dashboard plus cron. Enable in Settings.
Added port selection to Install Load Balancer.
Added ability to change port. Edit server, change the ports. Restart server afterwards.
Added ability to reboot server instead of just restart services.
Fixed newline in textareas.
Changed year to appear in brackets instead of after a hyphen.
Added option to extend sidebar in profile.
Fixed various bugs.
70% translation completed... taking it's swweeeett time.
Hidden expired MAG / Enigma passwords in reseller dashboard.
Added current release to Settings page so you can stay up to date.
Added advanced manual channel order.
Added bouquet ordering.
Partial localisation.
Fixed movie and episode adding, MySQL was parsing order as a command rather than column.
Fixed various page bugs due to XSS parsing by implementing HTML Purifier.
Fixed 2020 years not parsing in the python parser.
Fixed EPG URL not parsing correctly due to XSS decode not being available.
Fixed unicode line username and passwords not working.
Fixed never for expiration date (NULL was being parsed as 'NULL').
Fixed Restrictions not showing selected IP's or User-Agents.
New bouquet will be added to end of bouquet list rather than beginning.
Fixed bouquet ordering.
Fixed missing action buttons on Stream page.
Stream icon will show blank if not PNG, this is a limitation of no GD library.
Moved Hash Load Balancers to Settings page under Streaming instead of forced.
Added page to show User IP's per line for the previous Hour, 24 Hours or 7 Days.
Modified directory scanning to work with remote mounts like NextCloud.
Added "strict" to Geo IP options.
Added ISP to Activity Logs. Requires modifications to your main & LB's. Enable in settings.
Various bug fixes.
Yes this includes a rudimentary implementation of ISP's. I'll be adding ISP blocking etc in the next release but for now I've just implemented the API that actually grabs them. It's currently limited to 1,000 requests per day so if you have a lot of connections don't turn it on yet or you'll exhaust your limit immediately. Wait until I implement it in full as I'll have an unlimited supplier then.
To enable this, go to Settings, Streaming and tick Enable ISP's. You will also need to modify your /etc/hosts file to include the following:
CODE: SELECT ALL
127.0.0.1 api.xtream-codes.com
Next up, you need to modify your Nginx config located at /home/xtreamcodes/iptv_xtream_codes/nginx/conf/nginx.conf and add the following below the last server entry, restart services afterwards. This will only work on port 80 currently, so if you have apache2 running you'll have to kill it:
CODE: SELECT ALL
server {
listen 80;
root /home/xtreamcodes/iptv_xtream_codes/isp/;
location / {
allow 127.0.0.1;
deny all;
}
location ~ \.php$ {
limit_req zone=one burst=8;
try_files $uri =404;
fastcgi_index index.php;
fastcgi_pass php;
include fastcgi_params;
fastcgi_buffering on;
fastcgi_buffers 96 32k;
fastcgi_buffer_size 32k;
fastcgi_max_temp_file_size 0;
fastcgi_keep_conn on;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
}
ISP's will show up in User Activity then. Let me know how it goes. If you run a large server, please don't enable this yet as you will overload my request limit and it won't work for anyone.
YOUTUBE TUTORIALS - THANKS emre1393:
https://www.youtube.com/playlist?list=P ... k3JH5U2ekn
TROUBLESHOOTING:
You'll notice most issues are down to permissions, you should probably take note.
PROCESS MONITOR - HIGH CPU / MEMORY USAGE
If you're having issues with high cpu or memory usage, you can list the processes that are causing issues using the process monitor function. Go to the dashboard and click the CPU / Memory Usage of an individual server or select Process Monitor from the settings cog dropdown to begin. It can take a few seconds to enumerate processes but will list anything that is being used by the Xtream Codes user. You can then see what individual streams or processes are causing you the biggest issues.
An example that can cause high CPU usage is having movies set up on one server, but the video files themselves are hosted on another server. This will cause XC to download those files using the system_api.php file to the server and attempt to process them upon completion. Doing this with hundreds of movies will cause you big issues. Best practice is to host the movies on the same server as the one encoding / symlinking them. Try to use symlink more often than not as it's the least intensive.
For high memory usage where you can't isolate the issue, try the following:
viewtopic.php?f=13&t=3014&p=14819
Notes from a trusted user who had 100% CPU and 100% Memory, managed to reduce this drastically using process monitor:
Make sure pid_monitor is in crons.
Clean up streams_sys using stream tools.
Restart services.
For Any high percentage vod - make sure its set to same server as the source and symlink is on.
Any live streams that are high percentage that aren't being transcoded for a reason are likely starting and stopping too much: turn them direct or on demand.
BACKUPS
If backups aren't working for you, run the following command:
CODE: SELECT ALL
sudo chown -R xtreamcodes:xtreamcodes /home/xtreamcodes/
TMDb ISN'T WORKING
Your database may not have updated correctly. Ensure the admin folder has the correct permissions by running the below command:
CODE: SELECT ALL
sudo chown -R xtreamcodes:xtreamcodes /home/xtreamcodes/
Now go to Settings -> Database, click Update Tables.
If it still doesn't work, ensure your TMDb API key is correct and active. If it definitely is, then your mysql user for XC probably doesn't have the right permissions to modify tables. Give the user all the available permissions and it try the above again.
WATCH FOLDERS
To set up folder watching, go to the Settings dropdown, Folder Watch and click Settings. You need to set up your Genre matching here. So firstly, click Update from TMDb to get the latest genres. You can attribute a category that you have created to each TMDb Genre. The first genre for each TV Show or Movie will be the one it selects.
The above is optional, this is for more accurate matching, however you can override these settings in the next step.
To set up a folder to be watched, click the + button on the Folder Watch page and fill out the required details. Make sure you select the correct type or you'll have a bunch of incorrectly allocated movies or episodes. The override settings allow you to select a category that the movie / tv show will default to, or a fallback incase it doesn't match the category allocation you may have set up in the first step. It also has various other options for those who want to customise their matches more.
If your scan doesn't seem to be running, check your crontab with the following command:
CODE: SELECT ALL
sudo crontab -e -u xtreamcodes
Look for watch_folders.php. If it isn't there, delete the crontab_refresh file from the tmp folder of xtreamcodes, and restart the service. If it still isn't there, maybe your crontab for xtreamcodes is immutable as it can't be changed. Up to you to figure that one out.
PROCESS MONITORING
So I've made a process killer that checks all PID's in the database against live PID's on the server, killing any it doesn't need. This could potentially help people running into CPU issues, or just help in general as XC isn't the best at killing PID's.
pid_monitor.zip
(957 Bytes) Downloaded 284 times
To install it, download the file from above and extract it here (on each server you want it running on, include LB's):
CODE: SELECT ALL
/home/xtreamcodes/iptv_xtream_codes/crons/
INSTALL
For manual update, download the release from the link below.
http://xtream-ui.com/releases/release_22e.zip
Update Script
CODE: SELECT ALL
apt-get install unzi<file_sep>/isp/api.php
<?php
$rURL = "https://www.iplocate.io/api/lookup/";
if ((isset($_GET["ip"])) && (filter_var($_GET["ip"], FILTER_VALIDATE_IP))) {
if (!file_exists("./data/".md5($_GET["ip"]))) {
$rData = json_decode(file_get_contents($rURL.$_GET["ip"]), True);
if (($rData["org"]) OR ($rData["isp"])) {
$rISP = Array("isp_info" => Array("description" => $rData["isp"] ? $rData["isp"] : $rData["org"], "type" => "Custom", "is_server" => false));
file_put_contents("./data/".md5($_GET["ip"]), json_encode($rISP));
}
}
if (file_exists("./data/".md5($_GET["ip"]))) {
echo file_get_contents("./data/".md5($_GET["ip"]));
}
}
?><file_sep>/crons/stats.php
<?php
include "/home/xtreamcodes/iptv_xtream_codes/admin/functions.php";
$rPID = getmypid();
if (isset($rAdminSettings["stats_pid"])) {
if ((file_exists("/proc/".$rAdminSettings["stats_pid"])) && (strlen($rAdminSettings["stats_pid"]) > 0)) {
exit;
} else {
$db->query("UPDATE `admin_settings` SET `value` = ".intval($rPID)." WHERE `type` = 'stats_pid';");
}
} else {
$db->query("INSERT INTO `admin_settings`(`type`, `value`) VALUES('stats_pid', ".intval($rPID).");");
}
checkTable("dashboard_statistics");
$rAdminSettings = getAdminSettings();
$rSettings = getSettings();
$rTimeout = 3000; // Limit by time.
set_time_limit($rTimeout);
ini_set('max_execution_time', $rTimeout);
$rStatistics = Array("users" => Array(), "conns" => Array());
$rPeriod = intval($rAdminSettings["dashboard_stats_frequency"]) ?: 600;
if (($rPeriod >= 60) && ($rAdminSettings["dashboard_stats"])) {
$rResult = $db->query("SELECT MIN(`date_start`) AS `min` FROM `user_activity`;");
$rMin = roundUpToAny(intval($rResult->fetch_assoc()["min"]), $rPeriod);
$rResult = $db->query("SELECT MAX(`time`) AS `max` FROM `dashboard_statistics` WHERE `type` IN ('users', 'conns');");
$rMinProc = roundUpToAny(intval($rResult->fetch_assoc()["max"]), $rPeriod);
if ($rMinProc > $rMin) {
$rMin = $rMinProc - ($rPeriod * 3);
}
$rRange = range($rMin, roundUpToAny(time(), $rPeriod), $rPeriod);
foreach ($rRange as $rDate) {
$rCount = 0;
$rResult = $db->query("SELECT COUNT(`activity_id`) AS `count` FROM `user_activity` WHERE `date_start` <= ".intval($rDate)." AND `date_end` >= ".intval($rDate).";");
$rCount += $rResult->fetch_assoc()["count"];
$rResult = $db->query("SELECT COUNT(`activity_id`) AS `count` FROM `user_activity_now` WHERE `date_start` <= ".intval($rDate).";");
$rCount += $rResult->fetch_assoc()["count"];
$rStatistics["conns"][] = Array(intval($rDate), $rCount);
$rCount = 0;
$rResult = $db->query("SELECT COUNT(DISTINCT(`activity_id`)) AS `count` FROM `user_activity` WHERE `date_start` <= ".intval($rDate)." AND `date_end` >= ".intval($rDate).";");
$rCount += $rResult->fetch_assoc()["count"];
$rResult = $db->query("SELECT COUNT(DISTINCT(`activity_id`)) AS `count` FROM `user_activity_now` WHERE `date_start` <= ".intval($rDate).";");
$rCount += $rResult->fetch_assoc()["count"];
$rStatistics["users"][] = Array(intval($rDate), $rCount);
}
$db->query("DELETE FROM `dashboard_statistics` WHERE `type` IN ('users', 'conns') AND `time` >= ".intval($rMin).";");
foreach ($rStatistics as $rType => $rData) {
foreach ($rData as $rValue) {
$db->query("INSERT INTO `dashboard_statistics`(`type`, `time`, `count`) VALUES('".$db->real_escape_string($rType)."', ".intval($rValue[0]).", ".intval($rValue[1]).");");
}
}
}
?>
|
8f76b534c8d2ad97d6cbdf4aac06a7cef1cb1acf
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
dr4g0nsr/xtreamui
|
2ae921f8b0967cf9c5a2cc065809f8d5917b666a
|
1ec7bf53991577786efe2bf5cb0be6a7c93fced1
|
refs/heads/master
|
<repo_name>tslwn/digging-the-data<file_sep>/README.md
# theme2d
This visualisation is in response to 360Giving's challenge ['Digging the Data'](https://www.threesixtygiving.org/data/reports-publications-and-analysis/data-visualisation-challenge/), for which I chose to answer the question 'Who has funded what themes throughout the years?'.
On reading it I was struck by the word 'theme'. After exploring the data in GrantNav, I wondered whether techniques from Natural Language Processing and Machine Learning could evince a notion of theme from the text associated with each grant. In brief, I obtained a 2-d vector corresponding to each grant by taking a weighted average of vector representations of its words and reducing each vector in this set to two dimensions so that they could be visualised in the browser. The aim therefore is that the position of each circle encodes its 'theme'; the area in each case corresponds to the amount awarded (GBP). The circles are coloured according to the funding organisation.
To obtain a vector corresponding to each grant I took the average of [pre-trained word vectors](https://code.google.com/archive/p/word2vec) for the title, description and recipient organisation of each grant, weighted by the inverse document frequency (IDF) of that word among grants of the same funding organisation. I chose this weighting to suppress the influence of funding organisation on the clustering of the grants; for certain organisations the same words or phrases appeared frequently. To reduce the number of dimensions of this set of vectors from 300 to 2, I applied truncated singular value decomposition (SVD) and t-distributed Stochastic Neighbour Embedding (t-SNE). Because many of the circles overlap (due to the large variation in the order of magnitude of the amount awarded) I decided to 'collide' the circles in D3.js; effectively each circle is tethered to its position.
The data I chose to display in the final visualisation comprises grants of at least £1m awarded between 2004 and 2017; however, the vectors were calculated using the full GrantNav data set. This restriction improves the load time and real-time performance of the visualisation, both of which are lacking.
The question, of course, is whether this representation is meaningful or useful. This is to say, do the relationships between the grants in 2-d space correspond to our intuition? Medical topics occupy the northernmost area of the page and appear better-separated than other grants - I expect this is because of the precise vocabulary and often detailed descriptions. This approach is less successful with terse or boilerplate text, such as 'towards core costs'.
This is very much the start of an investigation, and in future I hope to apply these techniques in other ways, e.g. performing classification tasks by evaluating the nearest neighbours of an unknown datapoint. I would encourage you to explore the landscape for yourself and see what semantic relationships you can find.
<file_sep>/static/obtain_grant_vectors.py
# -*- coding: utf-8 -*-
"""
Obtains a 2-d vector for each record in the CSV export from GrantNav
(grantnav.threesixtygiving.org).
"""
from collections import Counter
from math import log
from re import findall
from sklearn.decomposition import TruncatedSVD
from sklearn.manifold import TSNE
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import scale
import gensim
import numpy as np
import pandas as pd
# TODO: Retain common phrases, e.g. 'Los Angeles', like the word2vec model.
def string_to_words(string):
"""Splits text into lowercase words, removing characters other than
apostrophes, hyphens and the Latin alphabet.
Parameters:
-----------
A string of text.
Returns:
--------
A list that holds the words.
"""
return findall(r"[A-z'-]+", string.lower())
def term_doc_freq(corpus):
"""Counts the number of documents in a corpus in which each word in the
corpus appears.
Parameters:
-----------
A list (corpus) of lists (documents) of strings (words).
Returns:
--------
A Counter object (dict) that maps a word to the number of documents in
which it appears.
"""
return Counter(word for document in corpus for word in set(string_to_words(document)))
def term_freq_funding_org(dataframe):
"""Counts the total number of documents .
Parameters:
-----------
A DataFrame object that includes the columns 'Funding Org:Identifier'
and 'text'.
Returns:
--------
A dict that maps a Funding Org to a dict that holds the total number
of grants with that Funding Org and a dict that maps a word to the
number of grants with that Funding Org in which it appears.
"""
aggregation = {
'text': {
'term_freq': term_doc_freq,
'total': 'count'
}
}
grouped = dataframe.groupby('Funding Org:Identifier').agg(aggregation)
grouped.columns = grouped.columns.droplevel(level=0)
return grouped.to_dict('index')
if __name__ == '__main__':
# Create DataFrame from CSV
csv = 'grantnav-all.csv'
dataframe = pd.read_csv(csv, dtype={
'Identifier': str,
'Title': str,
'Description': str,
'Currency': str,
'Amount Applied For': float,
'Amount Awarded': float,
'Amount Disbursed': float,
'Award Date': str,
'URL': str,
'Planned Dates:Start Date': str,
'Planned Dates:End Date': str,
'Planned Dates:Duration (months)': float,
'Actual Dates:Start Date': str,
'Actual Dates:End Date': str,
'Actual Dates:Duration (months)': float,
'Recipient Org:Identifier': str,
'Recipient Org:Name': str,
'Recipient Org:Charity Number': str,
'Recipient Org:Company Number': str,
'Recipient Org:Postal Code': str,
'Recipient Org:Location:0:Geographic Code Type': str,
'Recipient Org:Location:0:Geographic Code': str,
'Recipient Org:Location:0:Name': str,
'Recipient Org:Location:1:Geographic Code Type': str,
'Recipient Org:Location:1:Geographic Code': str,
'Recipient Org:Location:1:Name': str,
'Recipient Org:Location:2:Geographic Code Type': str,
'Recipient Org:Location:2:Geographic Code': str,
'Recipient Org:Location:2:Name': str,
'Funding Org:Identifier': str,
'Funding Org:Name': str,
'Funding Org:Postal Code': str,
'Grant Programme:Code': str,
'Grant Programme:Title': str,
'Grant Programme:URL': str,
'Beneficiary Location:0:Name': str,
'Beneficiary Location:0:Country Code': str,
'Beneficiary Location:0:Geographic Code': str,
'Beneficiary Location:0:Geographic Code Type': str,
'Beneficiary Location:1:Name': str,
'Beneficiary Location:1:Country Code': str,
'Beneficiary Location:1:Geographic Code': str,
'Beneficiary Location:1:Geographic Code Type': str,
'Beneficiary Location:2:Name': str,
'Beneficiary Location:2:Country Code': str,
'Beneficiary Location:2:Geographic Code': str,
'Beneficiary Location:2:Geographic Code Type': str,
'Beneficiary Location:3:Name': str,
'Beneficiary Location:3:Country Code': str,
'Beneficiary Location:3:Geographic Code': str,
'Beneficiary Location:3:Geographic Code Type': str,
'Beneficiary Location:4:Name': str,
'Beneficiary Location:4:Country Code': str,
'Beneficiary Location:4:Geographic Code': str,
'Beneficiary Location:4:Geographic Code Type': str,
'Beneficiary Location:5:Name': str,
'Beneficiary Location:5:Country Code': str,
'Beneficiary Location:5:Geographic Code': str,
'Beneficiary Location:5:Geographic Code Type': str,
'Beneficiary Location:6:Name': str,
'Beneficiary Location:6:Country Code': str,
'Beneficiary Location:6:Geographic Code': str,
'Beneficiary Location:6:Geographic Code Type': str,
'Beneficiary Location:7:Name': str,
'Beneficiary Location:7:Country Code': str,
'Beneficiary Location:7:Geographic Code': str,
'Beneficiary Location:7:Geographic Code Type': str,
'From An Open Call?': str,
'The following fields are not in the 360 Giving Standard and are added by GrantNav.': str,
'Data Source': str,
'Publisher:Name': str,
'Recipient Region': str,
'Recipient District': str,
'Recipient District Geographic Code': str,
'Recipient Ward': str,
'Recipient Ward Geographic Code': str,
'Retrieved for use in GrantNav': str,
'License (see note)': str,
'Note, this file also contains OS data © Crown copyright and database right 2016, Royal Mail data © Royal Mail copyright and Database right 2016, National Statistics data © Crown copyright and database right 2015 & 2016, see http://grantnav.threesixtygiving.org/datasets/ for more information.': str
})
# Retain columns of interest
dataframe = dataframe[[
'Identifier',
'Award Date',
'Title',
'Description',
'Currency',
'Amount Awarded',
'Recipient Org:Identifier',
'Recipient Org:Name',
'Funding Org:Identifier',
'Funding Org:Name'
]]
# Get inverse document frequencies among grants with same funding org
dataframe['text'] = dataframe['Title'].map(str) + ' ' + dataframe['Description'].map(str) + ' ' + dataframe['Recipient Org:Name'].map(str)
funding_org_freq = term_freq_funding_org(dataframe)
# Loads 300-d word vectors as a KeyedVectors instance
model = gensim.models.KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)
# Create a list of lists that holds the weighted word embeddings for each record
vectors = [
[
model[word] * log(funding_org_freq[record['Funding Org:Identifier']]['total'] / funding_org_freq[record['Funding Org:Identifier']]['term_freq'][word])
for word in string_to_words(record['text']) if word in model
]
for record in dataframe.to_dict('records')
]
# Average to give a single 300-d vector for each record
vectors = [np.mean(vector, axis=0) if vector else np.zeros_like(model['empty']) for vector in vectors]
# Replace NaN values to prevent ValueError
X = Imputer(missing_values='NaN', strategy='mean', axis=0, verbose=1).fit_transform(vectors)
# Scale to zero mean and unit variance
X_scaled = scale(X, axis=0)
print(X_scaled)
# Reduce number of features
X_reduced = TruncatedSVD(n_components=50, random_state=0).fit_transform(X_scaled)
print(X_reduced)
# Obtain 2-d vectors by t-SNE
X_embedded = TSNE(verbose=1).fit_transform(X_reduced)
print(X_embedded)
# Append to DataFrame and save to CSV
dataframe['x'] = X_embedded[:,0]
dataframe['y'] = X_embedded[:,1]
print(dataframe.head())
dataframe.to_csv('result.csv')
<file_sep>/script.js
class Chart {
constructor(opts) {
this.data = opts.data;
this.chart = opts.chart;
this.header = opts.header;
this.tooltip = opts.tooltip;
this.draw();
}
draw() {
this.width = this.chart.offsetWidth;
this.height = this.chart.offsetHeight;
this.margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
};
this.chart.innerHTML = '';
const svg = d3.select(this.chart).append('svg');
svg.attr('width', this.width);
svg.attr('height', this.height);
this.plot = svg.append('g')
.attr('transform',`translate(${this.margin.left},${this.margin.top})`);
// Zoom behaviour
const zoomed = () => {
this.plot.selectAll('.grant')
.attr('transform', d3.event.transform);
}
const zoom = d3.zoom()
.scaleExtent([0.01, 100])
.on('zoom', zoomed);
svg.call(zoom);
// Force layout
const ticked = () => {
this.plot.selectAll('.grant')
.attr('cx', d => d.x)
.attr('cy', d => d.y);
}
this.simulation = d3.forceSimulation()
.force('collide', d3.forceCollide(d => this.rScale(Math.sqrt(d.amount))))
.on('tick', ticked)
.stop();
this.createScales();
this.update();
}
// TODO: Correct scaling for different currencies
createScales() {
const xExtent = d3.extent(this.data, d => d.x);
const yExtent = d3.extent(this.data, d => d.y);
const rExtent = d3.extent(this.data, d => Math.sqrt(d.amount));
this.xScale = d3.scaleLinear()
.range([0, this.width-(this.margin.left+this.margin.right)])
.domain(xExtent);
this.yScale = d3.scaleLinear()
.range([0, this.height-(this.margin.top+this.margin.bottom)])
.domain(yExtent);
this.rScale = d3.scaleLinear()
.range([0, Math.min(this.height, this.width)/10])
.domain(rExtent);
this.uniqueFundingOrgs = this.data.map(d => d.fundingOrg)
.filter((value, index, self) => self.indexOf(value) === index);
this.colourScale = d3.scaleSequential()
.domain([0, 1])
.interpolator(d3.interpolateRainbow);
}
// Event handlers
handleMouseOver(d, _this) {
let html = '';
html += '<h1>' + d.fundingOrg + ' awarded ' + d.recipientOrg + ' ';
html += d.amount.toLocaleString('en-GB', {style: 'currency', currency: d.currency}) + '</h1>';
html += '<div id="tooltip">';
html += '<span id="grant-title" class="q">' + d.title + '</span></div>';
d3.select(_this.header)
.html(html);
}
handleMouseOut(d, _this) {
// d3.select(_this.tooltip)
// .style('display', 'none');
let html = '<h1>Who has funded what themes throughout the years?</h1>';
d3.select(_this.header)
.html(html);
}
update(newData) {
if (newData) {
this.data = newData;
}
const t = d3.transition()
.duration(400);
// JOIN new data with old elements
const circle = this.plot.selectAll('circle')
.data(this.data, d => d.id);
// EXIT old elements not present in new data
circle.exit()
.transition(t)
.attr('r', () => 0)
.remove();
// UPDATE old elements present in new data
circle
.attr('cx', d => this.xScale(d.x))
.attr('cy', d => this.yScale(d.y))
.attr('r', d => this.rScale(Math.sqrt(d.amount)));
// ENTER new elements present in new data
circle.enter()
.append('a')
.attr('href', d => "http://grantnav.threesixtygiving.org/grant/" + d.id)
.attr('target', 'blank')
.append('circle')
.attr('class', 'grant')
.attr('cx', d => this.xScale(d.x))
.attr('cy', d => this.yScale(d.y))
.style('fill', d => this.colourScale(this.uniqueFundingOrgs.indexOf(d.fundingOrg) / this.uniqueFundingOrgs.length))
.on('mouseover', d => this.handleMouseOver(d, this))
.on('mouseout', d => this.handleMouseOut(d, this))
.transition(t)
.attr('r', d => this.rScale(Math.sqrt(d.amount)));
const zoomTransform = d3.zoomTransform(d3.select('svg').node());
this.plot.selectAll('.grant')
.attr('transform', zoomTransform);
// Restart simulation
const strength = 0.1;
this.simulation
.nodes(this.data)
.force('x', d3.forceX(d => this.xScale(d.x)).strength(strength))
.force('y', d3.forceY(d => this.yScale(d.y)).strength(strength))
.alpha(1)
.restart();
}
}
|
21a3680da896a5e50eb50f6bd9668d04ba2f9fb1
|
[
"Markdown",
"Python",
"JavaScript"
] | 3
|
Markdown
|
tslwn/digging-the-data
|
1aa2d8d02bc840050cc5b76fe25404c9201cb4c7
|
1f8aaa6313984a3626d4bfc07f144780490e3758
|
refs/heads/master
|
<repo_name>ahmadnassri/node-oas-fastify<file_sep>/lib/plugin.js
const convertPath = require('./helpers/convert-path')
const parameters = require('./helpers/parameters')
const security = require('./helpers/security')
module.exports = function (instance, opts, next) {
// TODO check & validate opts.spec
// associate schema
instance.addSchema(opts.spec)
// process all paths
for (const path in opts.spec.paths) {
// process each path spec
const pathSpec = opts.spec.paths[path]
// process each method
for (const method in pathSpec) {
const oasRoute = pathSpec[method]
// construct the fastify route
const fastifyRoute = {
method: method.toUpperCase(),
url: convertPath(path),
schema: {
params: parameters(oasRoute.parameters, 'path'),
query: parameters(oasRoute.parameters, 'query'),
headers: parameters(oasRoute.parameters, 'header'),
response: {}
}
}
// Get the security schema from the spec, fallback to empty security schema
if (opts.spec.components && opts.spec.components.securitySchemes) {
// Get the global security that is applied to all routes
const globalSecurity = opts.spec.security
// Get the route specific security that overrides the global security
const routeSecurity = oasRoute.security || globalSecurity
/* istanbul ignore else */
if (routeSecurity) {
security(fastifyRoute, opts.spec.components.securitySchemes, routeSecurity)
}
}
// if a requestBody is present, get the first one
// OAS 3.x supports multiple body types, where fastify only supports one
if (oasRoute.requestBody &&
oasRoute.requestBody.content) {
// get the first one
const [[contentType, { schema }]] = Object.entries(oasRoute.requestBody.content)
fastifyRoute.schema.headers.required.push('content-type')
fastifyRoute.schema.headers.properties['content-type'] = {
const: contentType
}
// add body schema
fastifyRoute.schema.body = schema
}
// process all responses
for (const status in oasRoute.responses) {
// skip "default"
if (status === 'default') continue
// process each response schema
const responseSpec = oasRoute.responses[status]
// TODO handle other types
let responseSchema
// TODO: const json = responseSpec?.content?.['application/json']?.schema 😭
if (responseSpec.content &&
responseSpec.content['application/json'] &&
responseSpec.content['application/json'].schema) {
responseSchema = responseSpec.content['application/json'].schema
}
// add to route
if (responseSchema) fastifyRoute.schema.response[status] = responseSchema
}
// associate handler
/* istanbul ignore next */
fastifyRoute.handler = function routeHandler (request, reply) {
// TODO: should throw 404
return opts.handler[oasRoute.operationId](request, reply, instance)
}
instance.route(fastifyRoute)
}
}
next()
}
<file_sep>/test/parameters.js
const { test } = require('tap')
const parameters = require('../lib/helpers/parameters')
const defaultSchema = {
type: 'object',
required: [],
properties: {}
}
test('params: only accept arrays', assert => {
assert.plan(3)
assert.type(parameters({}, 'query'), Object)
assert.type(parameters(null, 'query'), Object)
assert.type(parameters(undefined, 'query'), Object)
})
test('params: convert to schema', assert => {
assert.plan(2)
const fixture = [{
name: 'foo',
in: 'query',
description: 'foobar',
required: false,
schema: {
type: 'integer'
}
}]
assert.strictSame(parameters(fixture, 'path'), defaultSchema)
assert.strictSame(parameters(fixture, 'query'), {
type: 'object',
required: [],
properties: {
foo: {
type: 'integer'
}
}
})
})
test('params: convert to schema', assert => {
assert.plan(1)
const fixture = [{
name: 'foo',
in: 'path',
description: 'foobar',
required: true,
schema: {
type: 'string'
}
}]
assert.strictSame(parameters(fixture, 'path'), {
type: 'object',
required: ['foo'],
properties: {
foo: {
type: 'string'
}
}
})
})
<file_sep>/test/full.js
const plugin = require('../lib')
const { test } = require('tap')
const openAPISpec = require('./fixtures/openapi.json')
const fastifySpec = require('./fixtures/fastify.json')
const openAPISpecSecurity = require('./fixtures/openapi-with-security.json')
const fastifySpecSecurity = require('./fixtures/fastify-with-security.json')
test('oas-to-fastify', assert => {
assert.plan(2)
let schema
const result = []
// fastify mock
const fastify = {
addSchema: (spec) => (schema = spec),
route: (route) => result.push(route)
}
plugin(fastify, { spec: openAPISpec, handler: {} }, () => {})
// replace handler Placeholder with Function for comparison
const fastifySpecWithFunc = fastifySpec.map(route => ({ ...route, handler: Function }))
assert.match(result, fastifySpecWithFunc)
assert.strictSame(openAPISpec, schema)
})
test('oas-to-fastify with security', assert => {
assert.plan(2)
let schema
const result = []
// fastify mock
const fastify = {
addSchema: (spec) => (schema = spec),
route: (route) => result.push(route)
}
// handler mock
const handler = {}
plugin(fastify, { spec: openAPISpecSecurity, handler }, () => {})
assert.match(result, fastifySpecSecurity)
assert.strictSame(openAPISpecSecurity, schema)
})
<file_sep>/lib/helpers/security.js
module.exports = function (fastifyRoute, securitySchemes, routeSecurity) {
// Either the securitySchemes or the security definition for the method is missing
if (!securitySchemes || Object.keys(securitySchemes).length === 0 || !routeSecurity) {
return false
}
const routeSecurityKeys = routeSecurity.map(security => Object.keys(security)).flat()
// loop through all securitySchemes
Object.entries(securitySchemes)
.filter(([name]) => routeSecurityKeys.includes(name)) // filter to matching names
.forEach(([name, security]) => {
// handle http security
if (security.type === 'http') {
// flag "Authorization" header as required
// doesn't matter if it's duplicated
fastifyRoute.schema.headers.required.push('authorization')
// define schema for "Authorization" header if it doesn't exist
/* istanbul ignore else */
if (!fastifyRoute.schema.headers.properties.authorization) {
fastifyRoute.schema.headers.properties.authorization = {
type: 'string'
}
}
}
// handle apiKey security
if (security.type === 'apiKey') {
const securitySchema = security.in === 'query' ? 'query' : 'headers'
const securityName = security.in === 'cookie' ? 'Set-Cookie' : security.name
// flag securityName as required
fastifyRoute.schema[securitySchema].required.push(securityName)
// define schema for securityName if it doesn't exist
/* istanbul ignore else */
if (!fastifyRoute.schema[securitySchema].properties[securityName]) {
fastifyRoute.schema[securitySchema].properties[securityName] = {
type: 'string'
}
}
}
// TODO oauth2, openIdConnect
})
}
<file_sep>/docs/README.md
## Usage
```js
const fastify = require('fastify')()
const spec = require('./petstore.json')
// your handler object properties map to the OAS "operationId"
const handler = {
listPets: () => { ... }
createPets: () => { ... }
showPetById: () => { ... }
}
fastify.register(require('oas-fastify'), { spec, handler })
```
#### Yaml Support?
<details>
<summary>This package does not support OAS Yaml format, but you can easily convert to JSON before calling `oas-fastify`</summary>
###### using [`js-yaml`](https://www.npmjs.com/package/js-yaml)
```js
const yaml = require('js-yaml')
const fs = require('fs')
const spec = yaml.safeLoad(fs.readFileSync('openapi.yml', 'utf8'))
fastify.register(require('oas-fastify'), { spec, handler })
```
###### using [`apidevtools/swagger-cli`](https://www.npmjs.com/package/@apidevtools/swagger-cli)
```bash
npx apidevtools/swagger-cli bundle spec/openapi.yml --outfile spec.json
```
</details>
### Options
The plugin accepts an `options` object with the following properties:
- **`spec`**: a valid [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/) **JSON** object
- **`handler`**: an object with properties that map to the spec's `operationId` names, with the values as functions that will handle the request
###### Example
```js
const spec = {
"paths": {
"/pets": {
"get": {
"operationId": "listPets",
...
}
}
}
}
const handler = {
listPets: function (request, reply, fastify) {
// fastify instance passed in for convenience
reply.send({ hello: 'world' })
}
}
```
<file_sep>/README.md
# OAS to Fastify Plugin
OAS 3.x to Fastify routes automation
[![license][license-img]][license-url]
[![release][release-img]][release-url]
[![super linter][super-linter-img]][super-linter-url]
[![test][test-img]][test-url]
[![semantic][semantic-img]][semantic-url]
## Usage
``` js
const fastify = require('fastify')()
const spec = require('./petstore.json')
// your handler object properties map to the OAS "operationId"
const handler = {
listPets: () => { ... }
createPets: () => { ... }
showPetById: () => { ... }
}
fastify.register(require('oas-fastify'), { spec, handler })
```
#### Yaml Support?
<details>
<summary>This package does not support OAS Yaml format, but you can easily convert to JSON before calling `oas-fastify`</summary>
###### using [`js-yaml`][]
``` js
const yaml = require('js-yaml')
const fs = require('fs')
const spec = yaml.safeLoad(fs.readFileSync('openapi.yml', 'utf8'))
fastify.register(require('oas-fastify'), { spec, handler })
```
###### using [`apidevtools/swagger-cli`][]
``` bash
npx apidevtools/swagger-cli bundle spec/openapi.yml --outfile spec.json
```
</details>
### Options
The plugin accepts an `options` object with the following properties:
- **`spec`**: a valid [OpenAPI Specification][] **JSON** object
- **`handler`**: an object with properties that map to the spec's `operationId` names, with the values as functions that will handle the request
###### Example
``` js
const spec = {
"paths": {
"/pets": {
"get": {
"operationId": "listPets",
...
}
}
}
}
const handler = {
listPets: function (request, reply, fastify) {
// fastify instance passed in for convenience
reply.send({ hello: 'world' })
}
}
```
[`js-yaml`]: https://www.npmjs.com/package/js-yaml
[`apidevtools/swagger-cli`]: https://www.npmjs.com/package/@apidevtools/swagger-cli
[OpenAPI Specification]: https://github.com/OAI/OpenAPI-Specification/
----
> Author: [<NAME>](https://www.ahmadnassri.com/) •
> Twitter: [@AhmadNassri](https://twitter.com/AhmadNassri)
[license-url]: LICENSE
[license-img]: https://badgen.net/github/license/ahmadnassri/node-oas-fastify
[release-url]: https://github.com/ahmadnassri/node-oas-fastify/releases
[release-img]: https://badgen.net/github/release/ahmadnassri/node-oas-fastify
[super-linter-url]: https://github.com/ahmadnassri/node-oas-fastify/actions?query=workflow%3Asuper-linter
[super-linter-img]: https://github.com/ahmadnassri/node-oas-fastify/workflows/super-linter/badge.svg
[test-url]: https://github.com/ahmadnassri/node-oas-fastify/actions?query=workflow%3Atest
[test-img]: https://github.com/ahmadnassri/node-oas-fastify/workflows/test/badge.svg
[semantic-url]: https://github.com/ahmadnassri/node-oas-fastify/actions?query=workflow%3Arelease
[semantic-img]: https://badgen.net/badge/📦/semantically%20released/blue
<file_sep>/lib/index.js
const plugin = require('./plugin')
const metadata = {
fastify: '3.x',
name: 'oas-fastify'
}
module.exports = require('fastify-plugin')(plugin, metadata)
<file_sep>/test/convert-path.js
const convert = require('../lib/helpers/convert-path')
const { test } = require('tap')
test('convert paths', assert => {
assert.plan(2)
assert.equal(convert('/pets/{petId}'), '/pets/:petId')
assert.equal(convert('/{entity}/{id}'), '/:entity/:id')
})
<file_sep>/lib/helpers/parameters.js
module.exports = function (parameters = [], type) {
const schema = {
type: 'object',
required: [],
properties: {}
}
if (!Array.isArray(parameters)) return schema
// find by type
const params = parameters.filter(p => p.in === type)
// exit early
if (params.length === 0) return schema
// configure url parameters
for (const param of params) {
// add to required array
if (param.required) schema.required.push(param.name)
// add schema to route
schema.properties[param.name] = param.schema
}
return schema
}
<file_sep>/lib/helpers/convert-path.js
// TODO: this is weak sauce
module.exports = function convertPath (str) {
return str.replace(/\{/g, ':').replace(/}/g, '')
}
<file_sep>/test/global-security.js
const plugin = require('../lib')
const { test } = require('tap')
const fixtures = {
oas: {
openapi: '3.0.0',
info: {
version: '1.0.0',
title: 'Auth Example'
},
security: [
{
httpAuth: []
}
],
paths: {
'/foo': {
get: {
operationId: 'foo'
}
}
},
components: {
securitySchemes: {
httpAuth: {
type: 'http',
scheme: 'basic'
}
}
}
},
fastify: [
{
method: 'GET',
url: '/foo',
schema: {
headers: {
type: 'object',
required: [
'authorization'
],
properties: {
authorization: {
type: 'string'
}
}
}
}
}
]
}
test('global security', assert => {
assert.plan(2)
let schema
const result = []
// fastify mock
const fastify = {
addSchema: (spec) => (schema = spec),
route: (route) => result.push(route)
}
plugin(fastify, { spec: fixtures.oas, handler: {} }, () => {})
assert.match(result, fixtures.fastify)
assert.strictSame(fixtures.oas, schema)
})
|
9c637eadea6272f23d9212fa5ea76ffbf9b57866
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
ahmadnassri/node-oas-fastify
|
c60d5f4002c196c30b0bf0a18dbac0c3e44e5f03
|
7dc7297bf36fa1f5b588aec34ce97e1558b17b8e
|
refs/heads/master
|
<file_sep>import ot
import numpy as np
from scipy.spatial import distance_matrix
def compute_map(A, B, metric="euclidean"):
M = compute_dist(A,B)
na = A.shape[0]
a = np.ones(na) / na
nb = B.shape[0]
b = np.ones(nb) / nb
return ot.emd(a, b, M)
def compute_wasserstein(A, B, metric="euclidean"):
M = compute_dist(A,B)
na = A.shape[0]
a = np.ones(na) / na
nb = B.shape[0]
b = np.ones(nb) / nb
return ot.emd2(a, b, M)
def compute_dist(A,B, metric="euclidean"):
return ot.dist(A, B, metric)
def compute_entropic(A,B, reg=1, metric="euclidean"):
M = compute_dist(A,B)
na = A.shape[0]
a = np.ones(na) / na
nb = B.shape[0]
b = np.ones(nb) / nb
return ot.sinkhorn(a, b, M, reg)
def get_matches(index, mapping):
"""
:param index: the index of the row you want
:param mapping: the transport mapping
:return: return the indicies of the mapped objects
"""
#get the row with the specified index
index_row = mapping[index]
#get the indices where there is a non-zero transport mass
indices = np.where(index_row != 0)
return indices
def unfairness_metric(T, X0, X1):
d = distance_matrix(X0,X1)
uf = np.sum( np.multiply(T, d), axis = 1) # element-wise mult + row sums
return uf
def unfairness_metric_norm(T, X0, X1):
"""
:param T: The Transport map/optimal coupling
:param X: Features
:return:
"""
d = distance_matrix(X0,X1)
max_distance = np.amax(d, axis = 1) # get max along rows
uf = np.sum( np.multiply(T, d), axis = 1) # element-wise mult + row sums
uf_norm = np.divide(uf, max_distance) * X0.shape[0] # normalize by worst possible case
return uf_norm
<file_sep># ot_bias
wasserstein and vibes
<file_sep>import networkx as nx
import matplotlib as mpl
from transport import *
from PIL import Image
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
import plotly.express as px
import plotly.graph_objects as go
import seaborn as sns
def normalize_unit(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
def adjMatrixEdges(M, a_nodes, b_nodes=None):
"""
Creates the edges in a NetworkX graph given some adjacency matrix
:param M: adjacency matrix
:param a_nodes: one group of nodes
:param b_nodes: second group of nodes
:return:
"""
#Get the cordinates where transport is happening
x, y = np.where(M > 0)
assert len(x) == len(y), "these should be the same"
#Easier on the eyes
m = len(x)
#Draw edges from A to A (same sample case)
if b_nodes is None:
edges = [(a_nodes[x[i]], a_nodes[y[i]], M[x[i]][y[i]]) for i in range(m)]
#Draw edges from A to B
else:
edges = [(a_nodes[x[i]][0], b_nodes[y[i]][0], M[x[i]][y[i]]) for i in range(m)]
return edges
class Map:
def __init__(self, transport_map, X1, X2=None, symmetric=False, groups=None):
"""
Class that contains the actual graph that I'm creating
:param X1: the features for one sample of size n , np.ndarry n x (num_features)
:param X2: the features for the otner sample of size m, np.ndarry m x (num_features)
:param transport: n x m matrix, np.ndarry n x m
:param symmetric: boolean denoting if the samples are the same items
:param groups: denote if the nodes are to be grouped, or if this is an 1-to-1 graph
"""
self.A = X1
self.B = X2
self.transport_map = transport_map
self.symmetric = symmetric
self.group_graph = None
self.normalized = True
if self.B is None:
# Assume graph is symmetric if only one sample is recieved
# self.B = X1
symmetric = True
else:
symmetric = False
#Make groups
self.groups = []
#Make a graph
self.graph = nx.DiGraph()
"""
if this group param is None, then we are making an individual 1-to-1 directed graph
Each node corresponds to an individual and each edge describes which element is mapped to which other
element. The edge weights denote the mass of transport
"""
#Make graph
A_nodes = [("A%d" % i, {"feature": self.A[i]}) for i in range(len(self.A))]
if symmetric:
#Quick check that the samples are the same size, if they're symetric
# assert len(self.A) == len(self.B), "samples must be of the same length"
#Add to graph
# self.graph.add_nodes_from(A_nodes)
for i in range(len(self.A)):
self.graph.add_node("A%d" % i, feature=self.A[i])
#Get edges
edges = adjMatrixEdges(self.transport_map, list(self.graph.nodes))
#Add Edges to graph
self.graph.add_weighted_edges_from(edges)
else:
#Graph is not symetric so A, B are diff. sets of nodes
B_nodes = [("B%d" % i, {"feature": self.B[i]}) for i in range(len(self.B))]
self.graph.add_nodes_from(A_nodes, bipartite=0)
self.graph.add_nodes_from(B_nodes, bipartite=1)
# Get edges
edges = adjMatrixEdges(self.transport_map, A_nodes, B_nodes)
# Add Edges to graph
self.graph.add_weighted_edges_from(edges)
def add_group(self, rule, name=None):
#Get nodes as tuple (name, data_dict)
nodes = self.graph.nodes(data=True)
#Get the names of the nodes that are grouped according to a rule
#Get the n[0] (name) according to the filter over features n[1]
grouped = [n[0] for n in nodes if rule(n[1]['feature'])]
#Add to the big list of groups
if grouped not in self.groups:
self.groups.append((name, grouped))
if len(self.groups) >= 2:
self.create_grouped_graph()
def create_grouped_graph(self):
assert len(self.groups) >= 2, "must have at least two groups to create this graph"
#For brevity
M = self.transport_map
groups = self.groups
num_groups = len(groups)
#Make the graph
group_graph = nx.DiGraph()
#Add a node for each group
for i in range(num_groups):
group_name, group_nodes = groups[i]
if group_name is None:
group_name = "G%d" % i
group_graph.add_node(group_name, nodes=group_nodes)
#Compute edge weights in adjacency matrix
group_adjacency_matrix = np.zeros((num_groups, num_groups))
for node in self.graph:
side, index = node[0], int(node[1:])
#Get the indices of a match
if side == 'A':
#Get all the groups that the node is in
node_groups = [i for i in range(len(groups)) if node in groups[i][1]]
#Get all the nodes that it is matched to
match_indices = get_matches(index, mapping=M)
#Determine the side of the matched node
if self.symmetric:
match_side = "A"
else:
match_side = "B"
"""
Below we're making the adjacency matrix for the graph representation
Its kinda alot so it gets a block comment
First we're going to iterate through all the indices that our 'node' (defined above) is matched to
Then we get the groups for each of those matches - a match can be in multiple groups
Finally, we update the adjacency matrix using the group indices, with the weight of the transport
from the individual level using the individual indices
"""
# all of the indices in the original graph 'node' is matched to,
# match_indices[0] because its a tuple for some reason? the indices are in the 0 spot
for m_i in match_indices[0]:
match_groups_indices = [i for i in range(len(groups)) if "%s%d" % (match_side, m_i) in groups[i][1]]
for m_g_i in match_groups_indices:
for n_g in node_groups:
group_adjacency_matrix[n_g][m_g_i] += M[index][m_i]
self.group_adj = group_adjacency_matrix
#Get the edges for the group graph
group_edges = adjMatrixEdges(group_adjacency_matrix, list(group_graph.nodes))
#Add the edges to the group graph
for u, v, weight in group_edges:
group_graph.add_edge(u, v, weight=weight)
self.group_graph = group_graph
if self.group_graph is not None and self.group_adj is not None and self.normalized:
self.normalize_weights()
return group_graph
def resetGroupEdges(self):
assert self.group_graph is not None and self.group_adj is not None, "Group Graph not instantiated"
self.group_graph = nx.create_empty_copy(self.group_graph, with_data=True)
group_edges = adjMatrixEdges(self.group_adj, list(self.group_graph.nodes))
for u, v, weight in group_edges:
self.group_graph.add_edge(u, v, weight=weight)
def normalize_weights(self):
if self.group_graph is not None:
self.group_adj = normalize(self.group_adj, axis=1, norm="l1")
self.resetGroupEdges()
return self.group_adj
def show_graph(self,
grouped=False,
sizeNodesBy=None,
numNodeSizes=3,
nodeSizeConstanst=50,
nodeSizeSmallest=1000,
nodeColorRule=None,
nodeSizeRule=None,
numNodeColors=2,
edgeColorRule=None,
):
if grouped:
assert self.group_graph is not None, "Must have a group graph!"
G = self.group_graph
else:
G = self.graph
for u, v, d in G.edges(data=True):
d['label'] = "%.3f" % d.get('weight', '')
d['arrowsize'] = .6
if grouped:
for name, feature in G.nodes(data=True):
lol = 2
G.nodes[name]['height'] = lol
G.nodes[name]['width'] = lol
if grouped:
G.graph['K'] = 3
A = nx.nx_agraph.to_agraph(G)
# A.layout(prog='dot')
A.layout(prog="fdp")
A.draw("simple.png")
img = Image.open("simple.png")
plt.figure(figsize=(12, 10))
plt.imshow(img)
plt.show()
def adj_to_sankey_weighted(self, s, t):
source = []
target = []
value = []
for i in range(len(self.group_adj)): # fix a class in the source
j = 0
num_t = np.round(self.group_adj[i][j]*s[i]) # count how many were mapped to this target in t
count_t = 0
for s_i in range(s[i]):
source.append(i) # add an invidivual in this group
target.append(j + len(self.group_adj[i]))
value.append(1)
count_t += 1
# move to the next group in the target if these are done
if count_t > num_t:
count_t = 0
j += 1
num_t = np.round(self.group_adj[i][j]*s[i])
return source, target, value
def parallel_plot(self, s, t):
src, tar, val = self.adj_to_sankey_weighted(s, t)
groups = [gr[0] for gr in self.groups]
color_swatch = sns.color_palette("colorblind", as_cmap=True)
offset = 0
colors = [color_swatch[i+offset] for i in src]
fig = go.Figure(data=[go.Sankey(
arrangement = "snap",
node = dict(
pad = 15,
thickness = 20,
line = dict(color = "black", width = 1),
label = groups*2,
color = color_swatch[offset:len(groups)+offset]*2,
),
link = dict(
source = src,
target = tar,
value = val,
color = colors[:len(val)]
))]
)
fig.update_layout(font_size=14, width = 500)
fig.show()
# pos = nx.layout.spring_layout(G)
#
# nodes = G.nodes(data=True)
# if sizeNodesBy is not None:
# nodes = sizeNodesBy(nodes)
#
# node_colors_ = []
# color_marker = 0
#
# labels = None
#
# node_sizes = []
# size_marker = 0
#
# if self.symmetric:
#
# for i in range(len(nodes)):
# if i >= len(nodes)*(size_marker + 1)/(numNodeSizes):
# size_marker += 1
# node_sizes.append(nodeSizeSmallest + ((size_marker + 1) * nodeSizeConstanst))
# if nodeColorRule is None:
# if i >= len(nodes)*(color_marker + 1)/(numNodeColors):
# color_marker += 1
# node_colors_.append((color_marker + 1) / (numNodeColors))
# else:
# node_colors_.append(nodeColorRule(nodes[i]))
#
# #Not symmetric case
# else:
#
# if nodeColorRule is not None:
# node_colors_ = [nodeColorRule(nodes[i]) for i in range(len(nodes))]
# else:
# node_colors_ = [1] * len(nodes)
# if nodeSizeRule is None:
# node_sizes = [nodeSizeSmallest] * len(nodes)
# else:
# node_sizes = [nodeSizeRule(nodes[i]) for i in range(len(nodes))]
#
#
#
# M = G.number_of_edges()
# edge_cmap = plt.get_cmap("Greys", lut=M)
# edge_weights = np.array([(e[-1] + .5)/.6 for e in G.edges.data("weight")])
# edge_colors = [edge_cmap(e_n) for e_n in edge_weights]
#
# node_cmap = plt.get_cmap(name='viridis', lut=len(G))
# node_colors = [node_cmap(c) for c in node_colors_]
#
# nx.draw(
# G,
# pos=pos,
# with_labels=True,
# node_size = node_sizes,
# node_color = node_colors,
# alpha=.4
# )
#
#
# nx.draw_networkx_edges(
# G,
# pos,
# node_size=node_sizes,
# arrowstyle="->",
# arrowsize=10,
# edge_color=edge_colors,
# edge_cmap=plt.cm.Blues,
# width=2,
# )
#
# labels = nx.get_edge_attributes(G, 'weight')
# nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
#
# ax = plt.gca()
# ax.set_axis_off()
# plt.show()
#TODO: Draw group graph with labels
<file_sep>import numpy as np
import pandas as pd
from responsibly.dataset import COMPASDataset
from responsibly.dataset import GermanDataset
from responsibly.dataset import AdultDataset
from sklearn.preprocessing import StandardScaler
def compas():
# Get the whole dataset, already nicely filtered for us from this library
compas_ds = COMPASDataset()
# Make the dataframe
cdf = compas_ds.df
"""
There are some columns that need to be adjusted, and a bunch that need to be dropped
- length jail sentence becomes one column instead of c_jail_in and c_jail_out
- time in custody becomes one column instead of cusotdy_in and custody_out
- I encode binary attributes 0,1 where 0 is majority class 1 is minority class
Male => 0 Female => 1,
Misdemeanor => 0, Felony => 1
"""
# Turn the length of jail sentence a single variable
c_jail_out = pd.to_datetime(cdf['c_jail_out'])
c_jail_in = pd.to_datetime(cdf['c_jail_in'])
c_jail_time = (c_jail_out - c_jail_in).apply(lambda x: x.days + x.seconds / 3600)
cdf["c_jail_time"] = c_jail_time
# Turn the length of custody into a single variable
custody_in = pd.to_datetime(cdf['in_custody'])
custody_out = pd.to_datetime(cdf['out_custody'])
custody_delta = (custody_out - custody_in).apply(lambda x: x.days + x.seconds / 3600)
cdf["custody_length"] = custody_delta
# Encode Male Female
cdf = cdf.replace({'sex': {'Male': 0, 'Female': 1}})
# Encode Charge Degree
cdf = cdf.replace({'c_charge_degree': {'M': 0, 'F': 1}})
# One Hot Encode Race
cdf = one_hot(cdf, "race")
# Remove Nans (not even sure how those show up for crimes?)
cdf = cdf.replace({np.nan: "other"})
charges = cdf["c_charge_desc"].unique()
# I dropped all of these columns because they didn't seem useful (idk what I was saying earlier)
# If you disagree just commit it out I guess idrc (this is still true)
cdf = cdf.drop(["name", "id", "dob", "first", "last", "compas_screening_date",
"age_cat", "c_case_number", "r_case_number", "vr_case_number", "decile_score.1",
"type_of_assessment", "score_text", "screening_date", "v_type_of_assessment", "priors_count.1",
"v_score_text", "v_screening_date", "in_custody", "out_custody", "length_of_stay",
"c_jail_out", "c_jail_in", "age_cat", "c_charge_desc", "c_offense_date",
"c_arrest_date", "c_offense_date", "r_charge_degree", "r_days_from_arrest",
"r_offense_date", "r_charge_desc", "r_jail_in", "r_jail_out", "violent_recid",
"vr_charge_degree", "vr_offense_date", "score_factor", "vr_charge_desc",
"v_decile_score", "c_days_from_compas", "start", "end", "event",
"days_b_screening_arrest"], axis=1)
return cdf
def adultDataset():
#Get the whole dataset, already nicely filtered for us from this library
adult_ds = AdultDataset()
#Make the dataframe
adf = adult_ds.df
#Make the occupations 1-hot
adf = one_hot(adf, "occupation", drop=True)
#Clean up Education
adf = adf.replace({'education': {
'Assoc-acdm': "HS-grad",
'Some-college': "HS-grad",
'Assoc-voc': "HS-grad",
"Prof-school": "HS-grad",
"11th": "No-HSD",
"9th": "No-HSD",
"10th": "No-HSD",
"12th": "No-HSD",
"5th-6th": "No-HSD",
"7th-8th": "No-HSD",
"1st-4th": "No-HSD",
"Preschool": "No-HSD"
}})
#Drop smaller racial categories for now
adf = adf[adf["race"] != "Amer-Indian-Eskimo"]
adf = adf[adf["race"] != "Asian-Pac-Islander"]
adf = adf[adf["race"] != "Other"]
#Only united states (~40k/48k)
# United States non US (~40k/48k)
adf.loc[adf['native_country'] != ' United-States', 'native_country'] = 'Non-US'
adf.loc[adf['native_country'] == ' United-States', 'native_country'] = 'US'
adf['native_country'] = adf['native_country'].map({'US': 1, 'Non-US': 0}).astype(int)
adf.head()
#mMake race and gender binary (yuck)
adf = adf.replace({'sex': {
'Female': 1,
'Male': 0,
}})
adf = adf.replace({'race': {
'Black': 1,
'White': 0,
}})
#Make all categorical 1-hot
adf = one_hot(adf, "education", drop=True)
#Simply work classes
adf['workclass'] = adf['workclass'].replace(['State-gov', 'Local-gov', 'Federal-gov'], 'Gov')
adf['workclass'] = adf['workclass'].replace(['Self-emp-inc', 'Self-emp-not-inc'], 'Self_employed')
adf = one_hot(adf, "workclass", drop=True)
#Make Marital status binary
adf['marital_status'] = adf['marital_status'].replace(['Divorced', 'Married-spouse-absent', 'Never-married', 'Separated', 'Widowed'], 'Single')
adf['marital_status'] = adf['marital_status'].replace(['Married-AF-spouse', 'Married-civ-spouse'], 'Couple')
adf = one_hot(adf, "marital_status", drop=True)
#Make relationships one-hot
adf = one_hot(adf, "relationship", drop=True)
#Make the income variables binary
adf = adf.replace({'income_per_year': {
'<=50K': 0,
'>50K': 1,
}})
return adf
def germanDataset():
# import data
german_ds = GermanDataset()
# Make the dataframe
cdf = german_ds.df
# Rename the columns of status and sex as they seem to be swapped
cdf = cdf.rename(columns = {'sex': 'marital_status', 'status': 'sex'}, inplace = False)
# Encode credit classification
cdf = cdf.replace({'credit': {'good': 1, 'bad': 0}})
# Encode Male Female
cdf = cdf.replace({'sex': {'male': 0, 'female': 1}})
# redo age factor so it's not an interval
cdf = cdf.drop(["age_factor"], axis=1) # remove age factor since age is also a variable
cdf['age_factor'] = cdf['age'] >= 25
# remove the random columns that are duplicated
cdf = cdf.loc[:,~cdf.columns.duplicated()]
# deal with categorical values by one hot encoding
catvars = ['credit_history', 'purpose', 'savings',
'present_employment','marital_status', 'other_debtors', 'property',
'installment_plans', 'housing', 'job']
for x in catvars:
cdf = one_hot(cdf, x)
cdf = cdf.rename(columns = {'none': 'no_guarantor_co-applicant', 'stores': 'store_installment',
'bank':'bank_installment'}, inplace = False)
return cdf
def one_hot(df, column, drop=True):
"""
:param df: the dataframe we're manipulating (pandas)
:param column: the name of the column we wanna 1-hot (string)
:param drop: drop the column we encoded in the return df (bool)
:return:
"""
#Get all the possible values, these will be the new colums in the new encoding
values = df[column].unique()
#Go through the values and create the encodings, i think this is straight forward idk
for v in values:
one_hot = df[column].apply(lambda x: x == v)
df[v] = one_hot
if drop:
df = df.drop([column], axis=1)
return df
#TODO: Is this what i want? not sure
# def write_compas():
# # Write to CSV file
# os.chdir("..")
# cdf.to_csv("./data/compas.csv")
|
3913bc08a804d45268506d644315544499e6e720
|
[
"Markdown",
"Python"
] | 4
|
Python
|
kwekuka/ot
|
5149c03ea21bd41b8cb8bc9b715a2a994b564b65
|
ddce97d06a9666bbf984882e361239e1ef67f7a6
|
refs/heads/master
|
<repo_name>infomaniac50/ecwid-wordpress-plugin<file_sep>/templates/admin/welcome-connect.php
<div class="ec-form">
<div class="ec-button">
<form action="<?php echo $connect_url; ?>" method="post">
<button type="submit" class="btn btn--large btn--orange"><?php _e( 'Connect Your Store', 'ecwid-shopping-cart' ); ?></button>
</form>
</div>
<?php if ( !Ecwid_Config::is_no_reg_wl() ) { ?>
<a target="_blank" href="<?php echo esc_attr(ecwid_get_register_link()); ?>"><?php _e( 'Create store', 'ecwid-shopping-cart' ); ?> ›</a>
<?php } ?>
</div>
<?php
if( !$connection_error ) {
$note = sprintf(
__( 'To display your store on this site, you need to allow WordPress to access your %1$s products. Please press connect to provide permission.', 'ecwid-shopping-cart' ),
Ecwid_Config::get_brand()
);
echo $this->get_welcome_page_note( $note );
} else {
$error_note = __( 'Connection error - after clicking button you need to login and accept permissions to use our plugin. Please, try again.', 'ecwid-shopping-cart' );
$oauth_error = $ecwid_oauth->get_error();
if( !empty($oauth_error) ) {
if ($ecwid_oauth->get_error() == 'other') {
$error_note = sprintf( __( 'Looks like your site does not support remote POST requests that are required for %s API to work. Please, contact your hosting provider to enable cURL.', 'ecwid-shopping-cart' ), Ecwid_Config::get_brand() );
} else {
$error_note = sprintf( __( 'To sell using %1$s, you must allow WordPress to access the %1$s plugin. The connect button will direct you to your %1$s account where you can provide permission.', 'ecwid-shopping-cart' ), Ecwid_Config::get_brand() );
}
}
echo $this->get_welcome_page_note( $error_note, 'ec-connection-error' );
}
if( $ecwid_oauth->get_reconnect_message() ) {
echo $this->get_welcome_page_note( $ecwid_oauth->get_reconnect_message() );
}
?>
|
a4f8a2ee3a50ba10f1a4ad1122beaab6ed41127c
|
[
"PHP"
] | 1
|
PHP
|
infomaniac50/ecwid-wordpress-plugin
|
944b9db2ee67c0894d64afd8f5e7f18a2d943cca
|
e6661eb5268942bf815a83ddf52820b56a0c58cb
|
refs/heads/master
|
<file_sep>@javax.xml.bind.annotation.XmlSchema(namespace = "http://server.suma/")
package suma.server;
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>co.servicios</groupId>
<artifactId>clienteSuma</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>ClientSuma</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>prime-repo</id>
<name>Prime Repo</name>
<url>http://repository.primefaces.org</url>
</repository>
</repositories>
<dependencies>
<!-- PrimeFaces -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- JSF -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<!-- EL -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.jax-ws-commons</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlFiles>
<wsdlFile>localhost_8080/ServerSuma/WebServiceSuma.wsdl</wsdlFile>
</wsdlFiles>
<packageName></packageName>
<wsdlLocation>http://localhost:8080/ServerSuma/WebServiceSuma?WSDL</wsdlLocation>
<staleFile>${project.build.directory}/jaxws/stale/WebServiceSuma.stale</staleFile>
</configuration>
<id>wsimport-generate-WebServiceSuma</id>
<phase>generate-sources</phase>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>webservices-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<configuration>
<sourceDestDir>${project.build.directory}/generated-sources/jaxws-wsimport</sourceDestDir>
<xnocompile>true</xnocompile>
<verbose>true</verbose>
<extension>true</extension>
<catalog>${basedir}/src/jax-ws-catalog.xml</catalog>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<webResources>
<resource>
<directory>src</directory>
<targetPath>WEB-INF</targetPath>
<includes>
<include>jax-ws-catalog.xml</include>
<include>wsdl/**</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
81013c38aa43f009c834eebb4364ae488d0659a8
|
[
"Java",
"Maven POM"
] | 2
|
Java
|
LisbethHernandez/WSInformatica
|
c555095ab6673644e7845eb9d1d08d84a75b8d06
|
5619111d82b2f55f618f6f812a8f3a4a05f7bef4
|
refs/heads/master
|
<repo_name>halfs2/bootcamp-dio-pratica-net<file_sep>/src/Entity/EntityBase.cs
using System;
using FluentValidation.Results;
namespace DIO.Series.Entity
{
public abstract class EntityBase
{
protected ValidationResult ValidationResult;
public int Id { get; private set; }
public EntityBase(int id)
{
Id = id;
ValidationResult = new ValidationResult();
}
protected void AdicionarErro(string mensagem)
{
ValidationResult.Errors.Add(new ValidationFailure(string.Empty, mensagem));
}
}
}<file_sep>/src/Entity/Serie.cs
using System;
using System.Collections.Generic;
using System.Linq;
using DIO.Series.Enums;
using FluentValidation;
namespace DIO.Series.Entity
{
public class Serie : EntityBase
{
public string Titulo { get; private set; }
public string Descricao { get; private set; }
public int Ano { get; private set; }
public Genero Genero { get; private set; }
public Serie(int id, string titulo, string descricao, int ano, Genero genero) : base(id)
{
Titulo = titulo;
Descricao = descricao;
Ano = ano;
Genero = genero;
}
public bool IsValid()
{
SerieValidator validator = new SerieValidator();
var result = validator.Validate(this);
foreach(var erro in result.Errors)
{
AdicionarErro(erro.ErrorMessage);
}
return result.IsValid;
}
public IEnumerable<string> ObterErros()
{
return ValidationResult.Errors.Select(e => e.ErrorMessage).ToList();
}
public override string ToString()
{
string retorno = "";
retorno += "Gênero: " + this.Genero + Environment.NewLine;
retorno += "Titulo: " + this.Titulo + Environment.NewLine;
retorno += "Descrição: " + this.Descricao + Environment.NewLine;
retorno += "Ano de Início: " + this.Ano + Environment.NewLine;
return retorno;
}
class SerieValidator : AbstractValidator<Serie>
{
public SerieValidator()
{
RuleFor(s => s.Id)
.NotEmpty();
RuleFor(s => s.Titulo)
.NotNull()
.MinimumLength(4);
RuleFor(s => s.Descricao)
.NotNull()
.MinimumLength(4);
RuleFor(s => s.Ano)
.NotEmpty();
RuleFor(s => s.Genero)
.IsInEnum();
}
}
}
}<file_sep>/src/Repository/SerieRepository.cs
using System;
using System.Collections.Generic;
using DIO.Series.Entity;
using DIO.Series.Interfaces;
namespace DIO.Series.Repository
{
public class SerieRepository : IRepository<Serie>
{
private int _ultimoId = 5;
private List<Serie> _listaSerie = new List<Serie>()
{
new Serie(1, "Alf o eteimoso", "Um alienigena que curte gatos", 1980, Enums.Genero.Comedia),
new Serie(2, "The office", "Um escritorio muito louco", 2005, Enums.Genero.Comedia),
new Serie(3, "Parks and recreations", "Um orgao do governo muito louco", 2005, Enums.Genero.Comedia),
new Serie(4, "<NAME>", "Um garoto e seu avo em multiversos", 2015, Enums.Genero.Comedia),
new Serie(5, "Invencivel", "Um adolescente com codinome invencivel mas que é bem 'vencivel'", 2021, Enums.Genero.Acao)
};
public void Atualizar(int id, Serie entidade)
{
var index = _listaSerie.FindIndex(s => s.Id.Equals(entidade.Id));
_listaSerie[index] = entidade;
}
public void Excluir(int id)
{
var item = _listaSerie.Find(s => s.Id.Equals(id));
_listaSerie.Remove(item);
}
public void Inserir(Serie entidade)
{
_listaSerie.Add(entidade);
}
public List<Serie> Listar()
{
return _listaSerie;
}
public Serie RetornaPorId(int id)
{
return _listaSerie.Find(s => s.Id.Equals(id));
}
public int ProximoId()
{
_ultimoId += 1;
return _ultimoId;
}
}
}
|
2a3af7e4535157521248e620536353af2d333358
|
[
"C#"
] | 3
|
C#
|
halfs2/bootcamp-dio-pratica-net
|
4336e1fb264e8640cbcb256b40057b7913f085f7
|
0b0b28e03295791110004e7869da28940a2bcb9e
|
refs/heads/master
|
<file_sep>package blackjack;
public class Player {
private String name;
private Hand hand;
public Player(String name) {
this.name = name;
this.hand = new Hand();
}
//here i made a constructor for the Dealer
public Player() {
this.name = "Dealer";
this.hand = new Hand();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Player [name=");
builder.append(name);
builder.append(", hand=");
builder.append(hand);
builder.append("]");
return builder.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Hand getHand() {
return hand;
}
public void setHand(Hand hand) {
this.hand = hand;
}
}
<file_sep>package blackjack;
public class Card {
Actualcard a;
Rankvalue r;
Suits s;
public Card(Actualcard a, Rankvalue r, Suits s) {
this.a = a;
this.r = r;
this.s = s;
}
public Actualcard getA() {
return a;
}
public void setA(Actualcard a) {
this.a = a;
}
public int getR() {
return r.getValue();
}
public void setR(Rankvalue r) {
this.r = r;
}
public String getS() {
return s.getValue2();
}
public void setS(Suits s) {
this.s = s;
}
}
<file_sep>package blackjack;
import java.time.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class GameTest {
Player user;
Player dealer;
Hand h = new Hand();
Deck d = new Deck();
public static void main(String[] args) {
GameTest cardsarefun = new GameTest();
cardsarefun.playBlackJack();
}
public void playBlackJack() {
user = new Player("Player 1");
dealer = new Player();
LocalDate today = LocalDate.now();
//LocalTime timeNow = LocalTime.now();
long input;
boolean help = true;
Scanner keyboard=new Scanner(System.in);
System.out.println(" ____Today is " + today + "____");
System.out.println(" ____Welcome to the game of BlackJack____");
System.out.println(" ____also known as \"21\"____");
System.out.println(" ____please press any number to start____\n\n");
input = keyboard.nextLong();
if (help && (input <= 900_000_000_000_000_000L)) {
System.out.println("Enter how many rounds you'd like to play: ");
int rd =keyboard.nextInt();
System.out.println("Let's play some BlackJack, shall we?");
BlackjackGameLogic ngame = new BlackjackGameLogic();
for (int i = 0; i < rd; i++) {
d.makeandshuffleCards();
ngame.letsplay(d, user, dealer);
}
}
else {
System.out.println("Please enter actual number greater than zero that makes logical sense.");
}
// List<Card> d = new ArrayList<>(52);
// for (Actualcard a: Actualcard.values()) {
// for (Rankvalue r : Rankvalue.values()) {
// for (Suits s : Suits.values()) {
// d.add(new Card( a, r, s));
// }
// }
// }
// System.out.println("\n\nThese are the cards shuffled!\n\n");
// Collections.shuffle(d);
//
// for (Card card1 : d) {
// System.out.println(card1);
// }
keyboard.close();
}
}
<file_sep>## Week 3 - BlackJack Project
# This is my weekend project for week 3.
### <NAME>, Skill Distillery student
*focus on OO Class Structure
I am going to start off with a UML.
I tried to think about each class, piece by piece, before making my Main GameTest class. In total, I ended up creating 6 classes and 3 enums. I had fun creating the enums, one for Suits, one for the Ranks, and one for the actual card value.
As for the classes, in chronological order, I created my Card class, Hand class, Deck class, Player class, Game Logic Class, and finally, my GameTest class. In my Game Logic class is where I utilized the most
of my time writing blocks of statements. I tried to make sure that the player has a choice to hit or stay in Line 25, and i also wanted to ensure that I check for cases when dealer hits blackjack in the first two cards in the Hand. So in line 116, i added a 'wonorlost' method to check for dealer blackjack right off the bat. This method helped me to see whether or not the player (user) either pushes with the dealer, beats the dealer, or loses. Then I reset each hand in order to clear out the total value of User and total Value of the dealer for possible next round. Given more time, I would have added another Map, in order to load the shuffled cards onto a list and show their individual card values!
|
4c9cd34cc88fd169c00ee20bf3644b7b393b1da1
|
[
"Markdown",
"Java"
] | 4
|
Java
|
moseslee88/BlackJackProject
|
11e7149b44d9d1fde1c87fe0df503f6ad4cfe867
|
baf0a65cd27addebac71f750b97e69ef6c389dbd
|
refs/heads/master
|
<repo_name>mykhailog/ember-math-helpers<file_sep>/addon/helpers/gcd.js
import { helper } from '@ember/component/helper';
/**
* Returns the greatest positive integer that divides each of two integers
*/
export function gcd([_a = 0, _b = 0]) {
const a = Math.abs(_a);
const b = Math.abs(_b);
if (a === 0) {
return b;
}
if (b === 0) {
return a;
}
return gcd([b, a % b]);
}
export default helper(gcd);
<file_sep>/tests/dummy/app/controllers/application.js
import Controller from '@ember/controller';
export default Controller.extend({
addTemplate: '{{add 1 2}}',
divTemplate: '{{div 20 10}}',
modTemplate: '{{mod 11 10}}',
multTemplate: '{{mult 6 6}}',
subTemplate: '{{sub 10 2}}',
gcdTemplate: '{{gcd 10 2}}',
composableSub: '{{sub 10 1 2 3}}',
composableComplex: '{{mult (div (add 15 5) 2) 10}}'
});
|
17db5980b4fa5a20800ef9a7fe7cbe6fcfca2b54
|
[
"JavaScript"
] | 2
|
JavaScript
|
mykhailog/ember-math-helpers
|
4b6bab817bd4fcf94c4b42f9ffdcc43e6c558a8e
|
48cfa635bfefb71209fbfe7ddbe698594e53f937
|
refs/heads/master
|
<file_sep>package com.quandoo.reservoir.model;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
import io.realm.CustomerRealmProxy;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by ercanozcan on 03/09/16.
*/
@Parcel(implementations = { CustomerRealmProxy.class },
value = Parcel.Serialization.BEAN,
analyze = { Customer.class })
public class Customer extends RealmObject {
@SerializedName("id")
@PrimaryKey
private int id;
@SerializedName("customerFirstName")
private String firstName;
@SerializedName("customerLastName")
private String lastName;
int reservedTableNumber = -1;// means none
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getReservedTableNumber() {
return reservedTableNumber;
}
public void setReservedTableNumber(int reservedTableNumber) {
this.reservedTableNumber = reservedTableNumber;
}
}
<file_sep>package com.quandoo.reservoir.view.adapter;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.quandoo.reservoir.R;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by ercanozcan on 04/09/16.
*/
public class TableAdapter extends RecyclerView.Adapter<TableAdapter.ViewHolder> {
private List<Boolean> tables;
public TableAdapter(List<Boolean> tables) {
this.tables = tables;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_table_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Resources resources = holder.itemView.getContext().getResources();
if(tables.get(position)){
holder.itemView.setBackgroundColor(resources.getColor(R.color.greenPositive));
} else {
holder.itemView.setBackgroundColor(resources.getColor(R.color.redNegative));
}
TextDrawable drawable = TextDrawable.builder()
.buildRound(""+ position,resources.getColor(R.color.transparent) );//the first letter of the customers name
holder.imgTable.setImageDrawable(drawable);
}
@Override
public int getItemCount() {
return tables.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.imgTable)
ImageView imgTable;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public List<Boolean> getTables() {
return tables;
}
public void setTables(List<Boolean> tables) {
this.tables = tables;
}
}
<file_sep>package com.quandoo.reservoir;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.quandoo.reservoir.view.adapter.CustomerAdapter;
import com.quandoo.reservoir.view.presenter.GreetActivityPresenter;
import butterknife.BindView;
import butterknife.ButterKnife;
public class GreetActivity extends AppCompatActivity {
public static final String DEBUG_TAG = "GreetActivity";
@BindView(R.id.customerList)
public RecyclerView customerList;
private CustomerAdapter customerAdapter;
private GreetActivityPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_greet);
ButterKnife.bind(this);
customerList.setLayoutManager(new LinearLayoutManager(this));
presenter = new GreetActivityPresenter(this);
presenter.onCreate();
}
public CustomerAdapter getCustomerAdapter() {
return customerAdapter;
}
public void setCustomerAdapter(CustomerAdapter customerAdapter) {
this.customerAdapter = customerAdapter;
customerList.setAdapter(customerAdapter);
}
@Override
protected void onDestroy() {
presenter.onDestroy();
presenter = null;
super.onDestroy();
}
}
<file_sep>package com.quandoo.reservoir.view.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.quandoo.reservoir.R;
import com.quandoo.reservoir.model.Customer;
import com.quandoo.reservoir.view.presenter.GreetActivityPresenter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by ercanozcan on 03/09/16.
*/
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
private GreetActivityPresenter presenter;
private List<Customer> customers;
public CustomerAdapter(List<Customer> customers, GreetActivityPresenter presenter) {
this.customers = customers;
this.presenter = presenter;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_customer_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder,final int position) {
holder.lblName.setText(customers.get(position).getFirstName());
holder.lblSurname.setText(customers.get(position).getLastName());
int color = ColorGenerator.MATERIAL.getRandomColor();
TextDrawable drawable = TextDrawable.builder()
.buildRound(customers.get(position).getFirstName().substring(0, 1), color);//the first letter of the customers name
holder.imgCustomer.setImageDrawable(drawable);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.onCustomerItemClick(customers.get(position));
}
});
}
@Override
public int getItemCount() {
return customers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.lblName)
TextView lblName;
@BindView(R.id.lblSurname)
TextView lblSurname;
@BindView(R.id.imgCustomer)
ImageView imgCustomer;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
|
e2e32b6c51fe233deea249ab43fce6da8b5ea5d9
|
[
"Java"
] | 4
|
Java
|
aercanozcan/Reservoir
|
82f12e080aba44623dcf055bb8aa96afb8ca03e9
|
ceb81e2d79dd406d4f398d005d4c82f6f9f67d7c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.